From 558fbf166b546214340a33815ee6e382e39862de Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 16 Oct 2026 19:36:32 +0200 Subject: [PATCH] Initial public OpenBMH 0.1 source (by Codex) --- .gitattributes | 2 + .github/ISSUE_TEMPLATE/bug_report.yml | 39 + .github/workflows/ci.yml | 93 + .github/workflows/release.yml | 40 + .gitignore | 43 + ACKNOWLEDGEMENTS.md | 11 + AGENTS.md | 18 + CMakeLists.txt | 1090 +++ CONTRIBUTING.md | 26 + LICENSE | 674 ++ README.md | 108 + THIRD_PARTY_NOTICES.md | 21 + docs/BUILDING.md | 52 + docs/BUILD_PLATFORMS.md | 9 + docs/CLI_CONCEPT/01-grundlagen.md | 53 + docs/CLI_CONCEPT/02-fenster.md | 67 + docs/CLI_CONCEPT/03-start.md | 57 + docs/CLI_CONCEPT/04-schreibtisch.md | 77 + docs/CLI_CONCEPT/05-information.md | 139 + docs/CLI_CONCEPT/06-verein.md | 351 + docs/CLI_CONCEPT/07-spieltag.md | 57 + docs/CLI_CONCEPT/08-einstellungen.md | 24 + docs/CLI_CONCEPT/09-texte.md | 9 + docs/CLI_CONCEPT/10-agenten-und-tests.md | 9 + docs/CLI_CONCEPT/12-beispiele.md | 69 + docs/CLI_CONCEPT/15-frontends.md | 13 + docs/CLI_CONCEPT/README.md | 26 + docs/CLI_CONCEPT/commands.csv | 349 + docs/COMPATIBILITY.md | 13 + docs/CONSOLE_CLIENTS.md | 47 + docs/DIFFERENCES.md | 37 + docs/RNG.md | 31 + docs/ROADMAP.md | 29 + docs/architecture.md | 39 + docs/formats/COL.md | 7 + docs/formats/CONFIG.md | 11 + docs/formats/EIN.md | 7 + docs/formats/EXECUTABLE_LAYOUT.md | 1985 ++++ docs/formats/FBM.md | 33 + docs/formats/FNT.md | 27 + docs/formats/LE.md | 15 + docs/formats/M3D.md | 37 + docs/formats/M3DAT.md | 7 + docs/formats/M3MEN.md | 20 + docs/formats/README.md | 25 + docs/formats/SOUND.md | 36 + docs/formats/STATE.md | 27 + docs/formats/TEXTD.md | 16 + docs/formats/VGA.md | 16 + docs/formats/WAPPEN.md | 7 + docs/licenses/LGPL-2.1.txt | 504 + docs/licenses/LZMA-SDK.txt | 7 + docs/licenses/Nuked-OPL3-notices.txt | 31 + docs/licenses/README.md | 14 + docs/licenses/SDL2-HIDAPI-BSD.txt | 26 + docs/licenses/SDL2-HIDAPI-options.txt | 13 + docs/licenses/SDL2-HIDAPI-original.txt | 9 + docs/licenses/SDL2-yuv2rgb.txt | 27 + docs/licenses/SDL2.txt | 18 + docs/licenses/miniz-source-notices.txt | 83 + docs/licenses/miniz.txt | 22 + docs/licenses/nativefiledialog-extended.txt | 16 + docs/protocol.md | 72 + docs/release/0.1/LIESMICH.txt | 44 + docs/release/0.1/RELEASE_NOTES.md | 32 + src/app/action_transaction.hpp | 36 + src/app/audio.hpp | 75 + src/app/career_session.cpp | 8375 +++++++++++++++++ src/app/career_session.hpp | 1085 +++ src/app/controller.cpp | 2351 +++++ src/app/controller.hpp | 100 + src/app/desktop_actions.cpp | 564 ++ src/app/desktop_actions.hpp | 200 + src/app/live_matchday_events.hpp | 47 + src/app/main.cpp | 3969 ++++++++ src/app/window_actions.cpp | 509 + src/app/window_actions.hpp | 122 + src/audio/CMakeLists.txt | 26 + src/audio/container.cpp | 190 + src/audio/container.hpp | 48 + src/audio/mixer.cpp | 129 + src/audio/mixer.hpp | 38 + src/audio/music_fallback.cpp | 91 + src/audio/music_fallback.hpp | 14 + src/audio/original.cpp | 468 + src/audio/original.hpp | 66 + src/audio/original_validation.cpp | 378 + src/audio/playback.cpp | 318 + src/audio/playback.hpp | 100 + src/audio/semantic_cues.cpp | 78 + src/audio/semantic_cues.hpp | 23 + src/audio/sound_driver.cpp | 373 + src/audio/third_party/nuked-opl3/LICENSE | 504 + src/audio/third_party/nuked-opl3/README.md | 8 + src/audio/third_party/nuked-opl3/opl3.c | 1517 +++ src/audio/third_party/nuked-opl3/opl3.h | 175 + src/audio/validation.cpp | 354 + src/cli/console/console.cpp | 737 ++ src/cli/console/console.hpp | 327 + src/cli/console/detail.hpp | 96 + src/cli/console/parser.cpp | 166 + src/cli/console/parser.hpp | 57 + src/cli/console/windows_balance.cpp | 91 + src/cli/console/windows_club.cpp | 334 + src/cli/console/windows_desk.cpp | 470 + src/cli/console/windows_environment.cpp | 57 + src/cli/console/windows_friendly.cpp | 137 + src/cli/console/windows_info.cpp | 220 + src/cli/console/windows_match.cpp | 901 ++ src/cli/console/windows_money.cpp | 544 ++ src/cli/console/windows_office.cpp | 346 + src/cli/console/windows_reschedule.cpp | 100 + src/cli/console/windows_squad.cpp | 429 + src/cli/console/windows_start.cpp | 517 + src/cli/console/windows_state.cpp | 306 + src/cli/console/windows_tables.cpp | 194 + src/cli/console/windows_transfer.cpp | 488 + src/cli/json.cpp | 198 + src/cli/json.hpp | 46 + src/cli/main.cpp | 769 ++ src/cli/protocol.cpp | 744 ++ src/cli/protocol.hpp | 32 + src/cli/seat_hub.cpp | 287 + src/cli/seat_hub.hpp | 84 + src/formats/binary.cpp | 32 + src/formats/binary.hpp | 26 + src/formats/executable_layout.hpp | 1967 ++++ src/formats/fbm.cpp | 53 + src/formats/fbm.hpp | 29 + src/formats/font.cpp | 58 + src/formats/font.hpp | 32 + src/formats/le.cpp | 140 + src/formats/le.hpp | 64 + src/formats/m3d.cpp | 72 + src/formats/m3d.hpp | 78 + src/formats/palette.cpp | 29 + src/formats/palette.hpp | 25 + src/formats/rule_base.cpp | 44 + src/formats/rule_base.hpp | 17 + src/formats/savestate.cpp | 202 + src/formats/savestate.hpp | 78 + src/formats/textd.cpp | 26 + src/formats/textd.hpp | 29 + src/formats/vga.cpp | 45 + src/formats/vga.hpp | 27 + src/game/balance_plan.cpp | 371 + src/game/balance_plan.hpp | 91 + src/game/bank_credit.cpp | 257 + src/game/bank_credit.hpp | 70 + src/game/career.cpp | 689 ++ src/game/career.hpp | 156 + src/game/club_info.cpp | 89 + src/game/club_info.hpp | 16 + src/game/club_player_detail.cpp | 220 + src/game/club_player_detail.hpp | 92 + src/game/cup.cpp | 782 ++ src/game/cup.hpp | 91 + src/game/desk.cpp | 129 + src/game/desk.hpp | 29 + src/game/desk_actions.cpp | 2248 +++++ src/game/desk_actions.hpp | 616 ++ src/game/driver.cpp | 279 + src/game/driver.hpp | 131 + src/game/environment.cpp | 103 + src/game/environment.hpp | 47 + src/game/highscore.cpp | 211 + src/game/highscore.hpp | 61 + src/game/human_buyer_sale.hpp | 125 + src/game/league_pairings.cpp | 547 ++ src/game/league_pairings.hpp | 119 + src/game/lineup.cpp | 866 ++ src/game/lineup.hpp | 116 + src/game/match.cpp | 166 + src/game/match.hpp | 132 + src/game/match_engine.cpp | 1286 +++ src/game/match_engine.hpp | 270 + src/game/matchday.cpp | 815 ++ src/game/matchday.hpp | 102 + src/game/matchday_setup.cpp | 1227 +++ src/game/matchday_setup.hpp | 155 + src/game/memory.hpp | 82 + src/game/messages.cpp | 153 + src/game/messages.hpp | 70 + src/game/month.cpp | 1007 ++ src/game/month.hpp | 83 + src/game/national.cpp | 234 + src/game/national.hpp | 65 + src/game/other_games.cpp | 395 + src/game/other_games.hpp | 121 + src/game/pending_offer.hpp | 117 + src/game/poach.cpp | 177 + src/game/poach.hpp | 66 + src/game/prediction.cpp | 205 + src/game/prediction.hpp | 54 + src/game/presentation.hpp | 70 + src/game/random.hpp | 63 + src/game/rating.cpp | 240 + src/game/rating.hpp | 106 + src/game/reality_ball.cpp | 223 + src/game/reality_ball.hpp | 46 + src/game/reality_duel.cpp | 97 + src/game/reality_duel.hpp | 42 + src/game/reality_match.cpp | 103 + src/game/reality_match.hpp | 38 + src/game/reality_motion.cpp | 168 + src/game/reality_motion.hpp | 87 + src/game/reality_movement.cpp | 166 + src/game/reality_movement.hpp | 32 + src/game/reality_reporter.cpp | 165 + src/game/reality_reporter.hpp | 44 + src/game/reality_scene.cpp | 179 + src/game/reality_scene.hpp | 59 + src/game/reality_setup.cpp | 190 + src/game/reality_setup.hpp | 37 + src/game/reality_space.cpp | 167 + src/game/reality_space.hpp | 31 + src/game/reschedule.cpp | 243 + src/game/reschedule.hpp | 79 + src/game/save.cpp | 199 + src/game/save.hpp | 38 + src/game/schedule.cpp | 157 + src/game/schedule.hpp | 138 + src/game/season.cpp | 1689 ++++ src/game/season.hpp | 196 + src/game/source_tip.cpp | 39 + src/game/source_tip.hpp | 18 + src/game/sportschau_awards.cpp | 98 + src/game/sportschau_presentation.hpp | 218 + src/game/sportschau_rating.cpp | 113 + src/game/sportschau_replay.cpp | 80 + src/game/stadium_blocks.cpp | 167 + src/game/stadium_blocks.hpp | 72 + src/game/state.cpp | 232 + src/game/state.hpp | 279 + src/game/table.cpp | 128 + src/game/table.hpp | 57 + src/game/table_forecast.cpp | 72 + src/game/table_forecast.hpp | 31 + src/game/top_scorers.cpp | 134 + src/game/top_scorers.hpp | 48 + src/game/trace.hpp | 13 + src/game/transfer_allocator.hpp | 10 + src/game/transfer_bid.hpp | 38 + src/game/turn.cpp | 222 + src/game/turn.hpp | 103 + src/game/turn_driver.cpp | 593 ++ src/game/turn_driver.hpp | 164 + src/game/week.cpp | 394 + src/game/week.hpp | 77 + src/game/weekly.cpp | 2985 ++++++ src/game/weekly.hpp | 163 + src/launch/archive.cpp | 261 + src/launch/archive.hpp | 63 + src/launch/file_dialog.cpp | 24 + src/launch/file_dialog.hpp | 17 + src/launch/fltd.cpp | 159 + src/launch/fltd.hpp | 35 + src/launch/fltd_map.inc | 355 + src/launch/game_data.cpp | 470 + src/launch/game_data.hpp | 67 + src/main.cpp | 122 + src/ui/CMakeLists.txt | 241 + src/ui/achievements.cpp | 261 + src/ui/achievements.hpp | 74 + src/ui/achievements_tests.cpp | 156 + src/ui/advertising.cpp | 1166 +++ src/ui/advertising.hpp | 167 + src/ui/advertising_tests.cpp | 474 + src/ui/alltime_table.cpp | 59 + src/ui/alltime_table.hpp | 49 + src/ui/alltime_table_tests.cpp | 49 + src/ui/analytics.cpp | 302 + src/ui/analytics.hpp | 78 + src/ui/analytics_tests.cpp | 88 + src/ui/balance_plan.cpp | 203 + src/ui/balance_plan.hpp | 103 + src/ui/balance_plan_tests.cpp | 84 + src/ui/bank.cpp | 1393 +++ src/ui/bank.hpp | 182 + src/ui/bank_tests.cpp | 326 + src/ui/calendar.cpp | 279 + src/ui/calendar.hpp | 58 + src/ui/calendar_state.cpp | 136 + src/ui/calendar_state.hpp | 57 + src/ui/club_info.cpp | 395 + src/ui/club_info.hpp | 103 + src/ui/club_player_detail.cpp | 404 + src/ui/club_player_detail.hpp | 92 + src/ui/contracts.cpp | 795 ++ src/ui/contracts.hpp | 155 + src/ui/contracts_tests.cpp | 162 + src/ui/cup_draw.cpp | 476 + src/ui/cup_draw.hpp | 122 + src/ui/desk_drawers.cpp | 312 + src/ui/desk_drawers.hpp | 47 + src/ui/desk_records.cpp | 183 + src/ui/desk_records.hpp | 61 + src/ui/desk_state.cpp | 752 ++ src/ui/desk_state.hpp | 130 + src/ui/desktop.cpp | 729 ++ src/ui/desktop.hpp | 85 + src/ui/desktop_tests.cpp | 1369 +++ src/ui/environment.cpp | 304 + src/ui/environment.hpp | 83 + src/ui/environment_tests.cpp | 234 + src/ui/finance_totals.cpp | 118 + src/ui/finance_totals.hpp | 39 + src/ui/finance_totals_tests.cpp | 50 + src/ui/flow.cpp | 1041 ++ src/ui/flow.hpp | 524 ++ src/ui/friendly_match.cpp | 505 + src/ui/friendly_match.hpp | 176 + src/ui/friendly_match_tests.cpp | 379 + src/ui/game_end.cpp | 346 + src/ui/game_end.hpp | 134 + src/ui/game_end_alternate.cpp | 194 + src/ui/game_end_alternate.hpp | 75 + src/ui/game_end_tax_animation.cpp | 117 + src/ui/game_end_tax_animation.hpp | 57 + src/ui/game_end_tests.cpp | 163 + src/ui/incoming_transfer.cpp | 606 ++ src/ui/incoming_transfer.hpp | 177 + src/ui/incoming_transfer_tests.cpp | 317 + src/ui/indoor_standings.cpp | 136 + src/ui/indoor_standings.hpp | 52 + src/ui/league_family_request.hpp | 57 + src/ui/league_pairings.cpp | 424 + src/ui/league_pairings.hpp | 86 + src/ui/league_table.cpp | 778 ++ src/ui/league_table.hpp | 142 + src/ui/league_table_range_dialog.cpp | 434 + src/ui/league_table_range_dialog.hpp | 157 + src/ui/league_table_tests.cpp | 441 + src/ui/lineup.cpp | 316 + src/ui/lineup.hpp | 88 + src/ui/lineup_tests.cpp | 234 + src/ui/live_intervention.cpp | 378 + src/ui/live_intervention.hpp | 91 + src/ui/live_intervention_tests.cpp | 126 + src/ui/live_matchday.cpp | 692 ++ src/ui/live_matchday.hpp | 120 + src/ui/live_reality.cpp | 57 + src/ui/live_reality.hpp | 21 + src/ui/live_set_piece.cpp | 290 + src/ui/live_set_piece.hpp | 24 + src/ui/mailbox_screen.cpp | 215 + src/ui/mailbox_screen.hpp | 53 + src/ui/mailbox_screen_tests.cpp | 191 + src/ui/mailbox_state.cpp | 70 + src/ui/mailbox_state.hpp | 60 + src/ui/mailbox_state_tests.cpp | 100 + src/ui/main.cpp | 234 + src/ui/manager.cpp | 404 + src/ui/manager.hpp | 100 + src/ui/manager_tests.cpp | 109 + src/ui/matchday_results.cpp | 152 + src/ui/matchday_results.hpp | 63 + src/ui/matchday_results_screen.cpp | 117 + src/ui/matchday_results_screen.hpp | 35 + src/ui/matchday_results_tests.cpp | 356 + src/ui/minute_statistics.cpp | 133 + src/ui/minute_statistics.hpp | 52 + src/ui/minute_statistics_tests.cpp | 47 + src/ui/national_friendly_ui.cpp | 194 + src/ui/national_friendly_ui.hpp | 95 + src/ui/opportunities.cpp | 341 + src/ui/opportunities.hpp | 118 + src/ui/opportunities_tests.cpp | 188 + src/ui/other_games.cpp | 544 ++ src/ui/other_games.hpp | 55 + src/ui/other_games_state.cpp | 395 + src/ui/other_games_state.hpp | 92 + src/ui/outgoing_transfer.cpp | 638 ++ src/ui/outgoing_transfer.hpp | 136 + src/ui/outgoing_transfer_tests.cpp | 332 + src/ui/pending_offer.cpp | 285 + src/ui/pending_offer.hpp | 41 + src/ui/pitch.cpp | 912 ++ src/ui/pitch.hpp | 148 + src/ui/pitch_tests.cpp | 493 + src/ui/player_card.cpp | 402 + src/ui/player_card.hpp | 72 + src/ui/player_card_tests.cpp | 142 + src/ui/preparation.cpp | 144 + src/ui/preparation.hpp | 41 + src/ui/preparation_flow.cpp | 2575 +++++ src/ui/preparation_tests.cpp | 777 ++ src/ui/process_timer.cpp | 44 + src/ui/process_timer.hpp | 33 + src/ui/reality_reporter.cpp | 126 + src/ui/reality_reporter.hpp | 38 + src/ui/save_load.cpp | 414 + src/ui/save_load.hpp | 90 + src/ui/season_entrants.cpp | 190 + src/ui/season_entrants.hpp | 57 + src/ui/season_entrants_tests.cpp | 97 + src/ui/season_promotion.cpp | 198 + src/ui/season_promotion.hpp | 63 + src/ui/series_records.cpp | 212 + src/ui/series_records.hpp | 55 + src/ui/series_records_tests.cpp | 102 + src/ui/settings.cpp | 538 ++ src/ui/settings.hpp | 133 + src/ui/settings_tests.cpp | 409 + src/ui/setup.cpp | 179 + src/ui/setup.hpp | 60 + src/ui/source_hold.hpp | 15 + src/ui/source_notice_test_helpers.hpp | 12 + src/ui/sportschau.cpp | 600 ++ src/ui/sportschau.hpp | 135 + src/ui/sprite_font.cpp | 73 + src/ui/sprite_font.hpp | 28 + src/ui/sprite_font_tests.cpp | 106 + src/ui/stadium.cpp | 2085 ++++ src/ui/stadium.hpp | 258 + src/ui/statistics_rankings.cpp | 269 + src/ui/statistics_rankings.hpp | 79 + src/ui/statistics_rankings_tests.cpp | 111 + src/ui/strengths.cpp | 162 + src/ui/strengths.hpp | 57 + src/ui/strengths_state.cpp | 277 + src/ui/strengths_state.hpp | 101 + src/ui/tactics.cpp | 245 + src/ui/tactics.hpp | 65 + src/ui/tactics_tests.cpp | 109 + src/ui/team_statistics.cpp | 493 + src/ui/team_statistics.hpp | 99 + src/ui/tests.cpp | 95 + src/ui/top_scorers.cpp | 272 + src/ui/top_scorers.hpp | 52 + src/ui/top_scorers_state.cpp | 44 + src/ui/top_scorers_state.hpp | 61 + src/ui/top_scorers_tests.cpp | 90 + src/ui/toto.cpp | 328 + src/ui/toto.hpp | 101 + src/ui/training.cpp | 371 + src/ui/training.hpp | 82 + src/ui/training_camp.cpp | 411 + src/ui/training_camp.hpp | 103 + src/ui/training_camp_tests.cpp | 230 + src/ui/training_tests.cpp | 163 + src/ui/transfer_history.cpp | 149 + src/ui/transfer_history.hpp | 68 + src/ui/transfer_history_tests.cpp | 62 + src/ui/transfer_market.cpp | 790 ++ src/ui/transfer_market.hpp | 156 + src/ui/transfer_market_tests.cpp | 92 + src/ui/world_cup_statistics.cpp | 240 + src/ui/world_cup_statistics.hpp | 66 + src/ui/world_cup_statistics_tests.cpp | 65 + src/version.hpp | 11 + tests/README.md | 29 + tests/app_controller_tests.cpp | 7560 +++++++++++++++ tests/autosave_tests.cpp | 136 + tests/balance_plan_app_tests.cpp | 228 + tests/balance_plan_tests.cpp | 106 + tests/bank_app_tests.cpp | 3897 ++++++++ tests/bank_lender_app_tests.cpp | 243 + tests/bank_lender_ui_tests.cpp | 518 + tests/blockdump.cpp | 40 + tests/capture_check.cpp | 463 + tests/capture_io.hpp | 120 + tests/career_initial_offers_tests.cpp | 48 + tests/cli_console_tests.cpp | 1705 ++++ tests/cli_protocol_tests.cpp | 464 + tests/cli_soak.cpp | 529 ++ tests/club_info_category_tests.cpp | 25 + tests/club_info_tests.cpp | 32 + tests/club_info_ui_tests.cpp | 124 + tests/club_player_detail_tests.cpp | 297 + tests/club_player_detail_ui_tests.cpp | 243 + tests/cmake/repo_hygiene.cmake | 19 + tests/competition_winner_tests.cpp | 56 + tests/credit_interest_weekly_tests.cpp | 74 + tests/cup_calendar_boundary_tests.cpp | 161 + tests/cup_cursor_tests.cpp | 66 + tests/cup_draw_ui_tests.cpp | 187 + tests/cup_followup_tests.cpp | 173 + tests/cup_script_oracle.cpp | 20 + tests/cup_seeded_followup_tests.cpp | 129 + tests/desk_check.cpp | 150 + tests/desktop_data_tests.cpp | 206 + tests/driver_barrier_tests.cpp | 276 + tests/e13_turn_driver_tests.cpp | 567 ++ tests/environment_tests.cpp | 91 + tests/fixture_table_tests.cpp | 110 + tests/fixture_tables.hpp | 26 + tests/format_tests.cpp | 301 + tests/game_end_alternate_tests.cpp | 122 + tests/game_end_app_tests.cpp | 72 + tests/game_end_cli_tests.cpp | 86 + tests/game_end_tax_animation_tests.cpp | 135 + tests/highscore_tests.cpp | 206 + tests/human_buyer_market_app_tests.cpp | 683 ++ tests/human_buyer_market_tests.cpp | 1351 +++ tests/human_buyer_pending_app_tests.cpp | 141 + tests/human_buyer_pending_offer_tests.cpp | 948 ++ tests/indoor_masters_transition_tests.cpp | 192 + tests/init_check.cpp | 392 + tests/json_unit_tests.cpp | 24 + tests/kickoff_check.cpp | 171 + tests/launch_check.cpp | 26 + tests/launch_tests.cpp | 186 + tests/launch_unit_tests.cpp | 44 + tests/league_pairings_data_tests.cpp | 111 + tests/league_pairings_tests.cpp | 1262 +++ tests/league_table_controls_app_tests.cpp | 549 ++ tests/league_table_controls_flow_tests.cpp | 543 ++ tests/league_views_data_tests.cpp | 139 + tests/lineup_assistant_detail_tests.cpp | 184 + tests/live_matchday_events_tests.cpp | 98 + tests/loaded_manager_loop_app_tests.cpp | 345 + tests/loaded_manager_loop_tests.cpp | 202 + tests/manager_desks_tests.cpp | 123 + tests/manager_join_app_tests.cpp | 162 + tests/matchday_intro_tests.cpp | 67 + tests/national_coach_desk_app_tests.cpp | 613 ++ tests/national_coach_desk_pending_fixture.hpp | 113 + tests/national_coach_desk_tests.cpp | 660 ++ tests/national_cycle_transition_tests.cpp | 193 + tests/national_friendly_actions_tests.cpp | 270 + tests/national_friendly_ui_tests.cpp | 141 + tests/national_nomination_tests.cpp | 72 + tests/national_pending_match_tests.cpp | 168 + tests/other_games_app_tests.cpp | 1029 ++ tests/other_games_projection_tests.cpp | 433 + tests/other_games_ui_tests.cpp | 616 ++ tests/package_tests.py | 44 + tests/pending_offer_app_tests.cpp | 76 + tests/pending_offer_desk_app_tests.cpp | 267 + tests/pending_offer_desk_tests.cpp | 194 + tests/pending_offer_nested_app_tests.cpp | 188 + tests/pending_offer_tests.cpp | 296 + tests/pending_offer_ui_tests.cpp | 414 + tests/phase_results_career_tests.cpp | 192 + tests/play_check.cpp | 66 + tests/post_check.cpp | 207 + tests/probe.cpp | 61 + tests/process_timer_tests.cpp | 48 + tests/reality_ball_tests.cpp | 93 + tests/reality_career_special_tests.cpp | 129 + tests/reality_deferred_tests.cpp | 86 + tests/reality_duel_tests.cpp | 107 + tests/reality_forced_event_tests.cpp | 142 + tests/reality_matchday_tests.cpp | 97 + tests/reality_motion_tests.cpp | 158 + tests/reality_movement_tests.cpp | 103 + tests/reality_reporter_layout_tests.cpp | 60 + tests/reality_reporter_tests.cpp | 141 + tests/reality_scene_tests.cpp | 99 + tests/reality_setup_tests.cpp | 122 + tests/reality_space_tests.cpp | 98 + tests/reschedule_tests.cpp | 104 + tests/runtime_fixture_tables.hpp | 14 + tests/save_check.cpp | 77 + tests/save_close_fault_tests.cpp | 20 + tests/season_cup_draw_app_tests.cpp | 222 + tests/season_cup_draw_tests.cpp | 140 + tests/season_end_desk_tests.cpp | 83 + tests/season_promotion_app_tests.cpp | 71 + tests/season_promotion_fixture_support.hpp | 44 + tests/season_promotion_tests.cpp | 146 + tests/season_sim.cpp | 358 + tests/season_tax_tests.cpp | 124 + tests/season_transition_tests.cpp | 397 + tests/shared_desktop_actions_tests.cpp | 505 + tests/skip_test.cpp | 7 + tests/sound_settings_app_tests.cpp | 182 + tests/sportschau_app_tests.cpp | 948 ++ tests/sportschau_eleven_tests.cpp | 84 + tests/sportschau_rating_tests.cpp | 127 + tests/sportschau_scene_tests.cpp | 90 + tests/sportschau_teaminfo_tests.cpp | 85 + tests/sportschau_ui_tests.cpp | 536 ++ tests/squad_dump.cpp | 77 + tests/stadium_block_app_tests.cpp | 1181 +++ tests/stadium_block_expansion_tests.cpp | 477 + tests/stadium_block_ui_tests.cpp | 1204 +++ tests/stand_block_actions_tests.cpp | 422 + tests/statistics_case2_app_tests.cpp | 443 + tests/table_print.cpp | 49 + tests/tax_animation_unit_tests.cpp | 35 + tests/team_statistics_source_oracle_tests.cpp | 181 + tests/team_statistics_tests.cpp | 129 + tests/test_inputs.hpp | 35 + tests/textfind.cpp | 20 + tests/top_scorers_app_tests.cpp | 540 ++ tests/toto_actions_tests.cpp | 54 + tests/training_camp_actions_tests.cpp | 126 + tests/training_camp_app_tests.cpp | 164 + tests/training_dispatch_app_tests.cpp | 221 + tests/transfer_bid_qualification_tests.cpp | 342 + tests/transfer_market_preview_app_tests.cpp | 365 + tests/transfer_market_preview_tests.cpp | 145 + tests/transfer_offer_class_app_tests.cpp | 136 + tests/transfer_offer_editor_tests.cpp | 176 + tests/transfer_offer_player_info_tests.cpp | 247 + tests/transfer_offer_team_info_tests.cpp | 290 + tests/ui_season_promotion_tests.cpp | 104 + tests/week_check.cpp | 2470 +++++ tests/weekly_human_buyer_loan_tests.cpp | 194 + tests/youth_academy_tests.cpp | 95 + tools/agentic_qa/advance.sh | 29 + tools/agentic_qa/send.sh | 8 + tools/cli_concept/check_concept.py | 64 + tools/package/make_package.py | 70 + tools/package/make_source_package.py | 123 + tools/package/make_windows_package.sh | 6 + tools/public_release/check_public_tree.py | 286 + tools/public_release/collect_differences.py | 70 + tools/public_release/collect_layout.py | 65 + tools/public_release/test_public_tree.py | 129 + tools/soak/console_longrun.sh | 61 + 613 files changed, 168029 insertions(+) create mode 100644 .gitattributes create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 ACKNOWLEDGEMENTS.md create mode 100644 AGENTS.md create mode 100644 CMakeLists.txt create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 docs/BUILDING.md create mode 100644 docs/BUILD_PLATFORMS.md create mode 100644 docs/CLI_CONCEPT/01-grundlagen.md create mode 100644 docs/CLI_CONCEPT/02-fenster.md create mode 100644 docs/CLI_CONCEPT/03-start.md create mode 100644 docs/CLI_CONCEPT/04-schreibtisch.md create mode 100644 docs/CLI_CONCEPT/05-information.md create mode 100644 docs/CLI_CONCEPT/06-verein.md create mode 100644 docs/CLI_CONCEPT/07-spieltag.md create mode 100644 docs/CLI_CONCEPT/08-einstellungen.md create mode 100644 docs/CLI_CONCEPT/09-texte.md create mode 100644 docs/CLI_CONCEPT/10-agenten-und-tests.md create mode 100644 docs/CLI_CONCEPT/12-beispiele.md create mode 100644 docs/CLI_CONCEPT/15-frontends.md create mode 100644 docs/CLI_CONCEPT/README.md create mode 100644 docs/CLI_CONCEPT/commands.csv create mode 100644 docs/COMPATIBILITY.md create mode 100644 docs/CONSOLE_CLIENTS.md create mode 100644 docs/DIFFERENCES.md create mode 100644 docs/RNG.md create mode 100644 docs/ROADMAP.md create mode 100644 docs/architecture.md create mode 100644 docs/formats/COL.md create mode 100644 docs/formats/CONFIG.md create mode 100644 docs/formats/EIN.md create mode 100644 docs/formats/EXECUTABLE_LAYOUT.md create mode 100644 docs/formats/FBM.md create mode 100644 docs/formats/FNT.md create mode 100644 docs/formats/LE.md create mode 100644 docs/formats/M3D.md create mode 100644 docs/formats/M3DAT.md create mode 100644 docs/formats/M3MEN.md create mode 100644 docs/formats/README.md create mode 100644 docs/formats/SOUND.md create mode 100644 docs/formats/STATE.md create mode 100644 docs/formats/TEXTD.md create mode 100644 docs/formats/VGA.md create mode 100644 docs/formats/WAPPEN.md create mode 100644 docs/licenses/LGPL-2.1.txt create mode 100644 docs/licenses/LZMA-SDK.txt create mode 100644 docs/licenses/Nuked-OPL3-notices.txt create mode 100644 docs/licenses/README.md create mode 100644 docs/licenses/SDL2-HIDAPI-BSD.txt create mode 100644 docs/licenses/SDL2-HIDAPI-options.txt create mode 100644 docs/licenses/SDL2-HIDAPI-original.txt create mode 100644 docs/licenses/SDL2-yuv2rgb.txt create mode 100644 docs/licenses/SDL2.txt create mode 100644 docs/licenses/miniz-source-notices.txt create mode 100644 docs/licenses/miniz.txt create mode 100644 docs/licenses/nativefiledialog-extended.txt create mode 100644 docs/protocol.md create mode 100644 docs/release/0.1/LIESMICH.txt create mode 100644 docs/release/0.1/RELEASE_NOTES.md create mode 100644 src/app/action_transaction.hpp create mode 100644 src/app/audio.hpp create mode 100644 src/app/career_session.cpp create mode 100644 src/app/career_session.hpp create mode 100644 src/app/controller.cpp create mode 100644 src/app/controller.hpp create mode 100644 src/app/desktop_actions.cpp create mode 100644 src/app/desktop_actions.hpp create mode 100644 src/app/live_matchday_events.hpp create mode 100644 src/app/main.cpp create mode 100644 src/app/window_actions.cpp create mode 100644 src/app/window_actions.hpp create mode 100644 src/audio/CMakeLists.txt create mode 100644 src/audio/container.cpp create mode 100644 src/audio/container.hpp create mode 100644 src/audio/mixer.cpp create mode 100644 src/audio/mixer.hpp create mode 100644 src/audio/music_fallback.cpp create mode 100644 src/audio/music_fallback.hpp create mode 100644 src/audio/original.cpp create mode 100644 src/audio/original.hpp create mode 100644 src/audio/original_validation.cpp create mode 100644 src/audio/playback.cpp create mode 100644 src/audio/playback.hpp create mode 100644 src/audio/semantic_cues.cpp create mode 100644 src/audio/semantic_cues.hpp create mode 100644 src/audio/sound_driver.cpp create mode 100644 src/audio/third_party/nuked-opl3/LICENSE create mode 100644 src/audio/third_party/nuked-opl3/README.md create mode 100644 src/audio/third_party/nuked-opl3/opl3.c create mode 100644 src/audio/third_party/nuked-opl3/opl3.h create mode 100644 src/audio/validation.cpp create mode 100644 src/cli/console/console.cpp create mode 100644 src/cli/console/console.hpp create mode 100644 src/cli/console/detail.hpp create mode 100644 src/cli/console/parser.cpp create mode 100644 src/cli/console/parser.hpp create mode 100644 src/cli/console/windows_balance.cpp create mode 100644 src/cli/console/windows_club.cpp create mode 100644 src/cli/console/windows_desk.cpp create mode 100644 src/cli/console/windows_environment.cpp create mode 100644 src/cli/console/windows_friendly.cpp create mode 100644 src/cli/console/windows_info.cpp create mode 100644 src/cli/console/windows_match.cpp create mode 100644 src/cli/console/windows_money.cpp create mode 100644 src/cli/console/windows_office.cpp create mode 100644 src/cli/console/windows_reschedule.cpp create mode 100644 src/cli/console/windows_squad.cpp create mode 100644 src/cli/console/windows_start.cpp create mode 100644 src/cli/console/windows_state.cpp create mode 100644 src/cli/console/windows_tables.cpp create mode 100644 src/cli/console/windows_transfer.cpp create mode 100644 src/cli/json.cpp create mode 100644 src/cli/json.hpp create mode 100644 src/cli/main.cpp create mode 100644 src/cli/protocol.cpp create mode 100644 src/cli/protocol.hpp create mode 100644 src/cli/seat_hub.cpp create mode 100644 src/cli/seat_hub.hpp create mode 100644 src/formats/binary.cpp create mode 100644 src/formats/binary.hpp create mode 100644 src/formats/executable_layout.hpp create mode 100644 src/formats/fbm.cpp create mode 100644 src/formats/fbm.hpp create mode 100644 src/formats/font.cpp create mode 100644 src/formats/font.hpp create mode 100644 src/formats/le.cpp create mode 100644 src/formats/le.hpp create mode 100644 src/formats/m3d.cpp create mode 100644 src/formats/m3d.hpp create mode 100644 src/formats/palette.cpp create mode 100644 src/formats/palette.hpp create mode 100644 src/formats/rule_base.cpp create mode 100644 src/formats/rule_base.hpp create mode 100644 src/formats/savestate.cpp create mode 100644 src/formats/savestate.hpp create mode 100644 src/formats/textd.cpp create mode 100644 src/formats/textd.hpp create mode 100644 src/formats/vga.cpp create mode 100644 src/formats/vga.hpp create mode 100644 src/game/balance_plan.cpp create mode 100644 src/game/balance_plan.hpp create mode 100644 src/game/bank_credit.cpp create mode 100644 src/game/bank_credit.hpp create mode 100644 src/game/career.cpp create mode 100644 src/game/career.hpp create mode 100644 src/game/club_info.cpp create mode 100644 src/game/club_info.hpp create mode 100644 src/game/club_player_detail.cpp create mode 100644 src/game/club_player_detail.hpp create mode 100644 src/game/cup.cpp create mode 100644 src/game/cup.hpp create mode 100644 src/game/desk.cpp create mode 100644 src/game/desk.hpp create mode 100644 src/game/desk_actions.cpp create mode 100644 src/game/desk_actions.hpp create mode 100644 src/game/driver.cpp create mode 100644 src/game/driver.hpp create mode 100644 src/game/environment.cpp create mode 100644 src/game/environment.hpp create mode 100644 src/game/highscore.cpp create mode 100644 src/game/highscore.hpp create mode 100644 src/game/human_buyer_sale.hpp create mode 100644 src/game/league_pairings.cpp create mode 100644 src/game/league_pairings.hpp create mode 100644 src/game/lineup.cpp create mode 100644 src/game/lineup.hpp create mode 100644 src/game/match.cpp create mode 100644 src/game/match.hpp create mode 100644 src/game/match_engine.cpp create mode 100644 src/game/match_engine.hpp create mode 100644 src/game/matchday.cpp create mode 100644 src/game/matchday.hpp create mode 100644 src/game/matchday_setup.cpp create mode 100644 src/game/matchday_setup.hpp create mode 100644 src/game/memory.hpp create mode 100644 src/game/messages.cpp create mode 100644 src/game/messages.hpp create mode 100644 src/game/month.cpp create mode 100644 src/game/month.hpp create mode 100644 src/game/national.cpp create mode 100644 src/game/national.hpp create mode 100644 src/game/other_games.cpp create mode 100644 src/game/other_games.hpp create mode 100644 src/game/pending_offer.hpp create mode 100644 src/game/poach.cpp create mode 100644 src/game/poach.hpp create mode 100644 src/game/prediction.cpp create mode 100644 src/game/prediction.hpp create mode 100644 src/game/presentation.hpp create mode 100644 src/game/random.hpp create mode 100644 src/game/rating.cpp create mode 100644 src/game/rating.hpp create mode 100644 src/game/reality_ball.cpp create mode 100644 src/game/reality_ball.hpp create mode 100644 src/game/reality_duel.cpp create mode 100644 src/game/reality_duel.hpp create mode 100644 src/game/reality_match.cpp create mode 100644 src/game/reality_match.hpp create mode 100644 src/game/reality_motion.cpp create mode 100644 src/game/reality_motion.hpp create mode 100644 src/game/reality_movement.cpp create mode 100644 src/game/reality_movement.hpp create mode 100644 src/game/reality_reporter.cpp create mode 100644 src/game/reality_reporter.hpp create mode 100644 src/game/reality_scene.cpp create mode 100644 src/game/reality_scene.hpp create mode 100644 src/game/reality_setup.cpp create mode 100644 src/game/reality_setup.hpp create mode 100644 src/game/reality_space.cpp create mode 100644 src/game/reality_space.hpp create mode 100644 src/game/reschedule.cpp create mode 100644 src/game/reschedule.hpp create mode 100644 src/game/save.cpp create mode 100644 src/game/save.hpp create mode 100644 src/game/schedule.cpp create mode 100644 src/game/schedule.hpp create mode 100644 src/game/season.cpp create mode 100644 src/game/season.hpp create mode 100644 src/game/source_tip.cpp create mode 100644 src/game/source_tip.hpp create mode 100644 src/game/sportschau_awards.cpp create mode 100644 src/game/sportschau_presentation.hpp create mode 100644 src/game/sportschau_rating.cpp create mode 100644 src/game/sportschau_replay.cpp create mode 100644 src/game/stadium_blocks.cpp create mode 100644 src/game/stadium_blocks.hpp create mode 100644 src/game/state.cpp create mode 100644 src/game/state.hpp create mode 100644 src/game/table.cpp create mode 100644 src/game/table.hpp create mode 100644 src/game/table_forecast.cpp create mode 100644 src/game/table_forecast.hpp create mode 100644 src/game/top_scorers.cpp create mode 100644 src/game/top_scorers.hpp create mode 100644 src/game/trace.hpp create mode 100644 src/game/transfer_allocator.hpp create mode 100644 src/game/transfer_bid.hpp create mode 100644 src/game/turn.cpp create mode 100644 src/game/turn.hpp create mode 100644 src/game/turn_driver.cpp create mode 100644 src/game/turn_driver.hpp create mode 100644 src/game/week.cpp create mode 100644 src/game/week.hpp create mode 100644 src/game/weekly.cpp create mode 100644 src/game/weekly.hpp create mode 100644 src/launch/archive.cpp create mode 100644 src/launch/archive.hpp create mode 100644 src/launch/file_dialog.cpp create mode 100644 src/launch/file_dialog.hpp create mode 100644 src/launch/fltd.cpp create mode 100644 src/launch/fltd.hpp create mode 100644 src/launch/fltd_map.inc create mode 100644 src/launch/game_data.cpp create mode 100644 src/launch/game_data.hpp create mode 100644 src/main.cpp create mode 100644 src/ui/CMakeLists.txt create mode 100644 src/ui/achievements.cpp create mode 100644 src/ui/achievements.hpp create mode 100644 src/ui/achievements_tests.cpp create mode 100644 src/ui/advertising.cpp create mode 100644 src/ui/advertising.hpp create mode 100644 src/ui/advertising_tests.cpp create mode 100644 src/ui/alltime_table.cpp create mode 100644 src/ui/alltime_table.hpp create mode 100644 src/ui/alltime_table_tests.cpp create mode 100644 src/ui/analytics.cpp create mode 100644 src/ui/analytics.hpp create mode 100644 src/ui/analytics_tests.cpp create mode 100644 src/ui/balance_plan.cpp create mode 100644 src/ui/balance_plan.hpp create mode 100644 src/ui/balance_plan_tests.cpp create mode 100644 src/ui/bank.cpp create mode 100644 src/ui/bank.hpp create mode 100644 src/ui/bank_tests.cpp create mode 100644 src/ui/calendar.cpp create mode 100644 src/ui/calendar.hpp create mode 100644 src/ui/calendar_state.cpp create mode 100644 src/ui/calendar_state.hpp create mode 100644 src/ui/club_info.cpp create mode 100644 src/ui/club_info.hpp create mode 100644 src/ui/club_player_detail.cpp create mode 100644 src/ui/club_player_detail.hpp create mode 100644 src/ui/contracts.cpp create mode 100644 src/ui/contracts.hpp create mode 100644 src/ui/contracts_tests.cpp create mode 100644 src/ui/cup_draw.cpp create mode 100644 src/ui/cup_draw.hpp create mode 100644 src/ui/desk_drawers.cpp create mode 100644 src/ui/desk_drawers.hpp create mode 100644 src/ui/desk_records.cpp create mode 100644 src/ui/desk_records.hpp create mode 100644 src/ui/desk_state.cpp create mode 100644 src/ui/desk_state.hpp create mode 100644 src/ui/desktop.cpp create mode 100644 src/ui/desktop.hpp create mode 100644 src/ui/desktop_tests.cpp create mode 100644 src/ui/environment.cpp create mode 100644 src/ui/environment.hpp create mode 100644 src/ui/environment_tests.cpp create mode 100644 src/ui/finance_totals.cpp create mode 100644 src/ui/finance_totals.hpp create mode 100644 src/ui/finance_totals_tests.cpp create mode 100644 src/ui/flow.cpp create mode 100644 src/ui/flow.hpp create mode 100644 src/ui/friendly_match.cpp create mode 100644 src/ui/friendly_match.hpp create mode 100644 src/ui/friendly_match_tests.cpp create mode 100644 src/ui/game_end.cpp create mode 100644 src/ui/game_end.hpp create mode 100644 src/ui/game_end_alternate.cpp create mode 100644 src/ui/game_end_alternate.hpp create mode 100644 src/ui/game_end_tax_animation.cpp create mode 100644 src/ui/game_end_tax_animation.hpp create mode 100644 src/ui/game_end_tests.cpp create mode 100644 src/ui/incoming_transfer.cpp create mode 100644 src/ui/incoming_transfer.hpp create mode 100644 src/ui/incoming_transfer_tests.cpp create mode 100644 src/ui/indoor_standings.cpp create mode 100644 src/ui/indoor_standings.hpp create mode 100644 src/ui/league_family_request.hpp create mode 100644 src/ui/league_pairings.cpp create mode 100644 src/ui/league_pairings.hpp create mode 100644 src/ui/league_table.cpp create mode 100644 src/ui/league_table.hpp create mode 100644 src/ui/league_table_range_dialog.cpp create mode 100644 src/ui/league_table_range_dialog.hpp create mode 100644 src/ui/league_table_tests.cpp create mode 100644 src/ui/lineup.cpp create mode 100644 src/ui/lineup.hpp create mode 100644 src/ui/lineup_tests.cpp create mode 100644 src/ui/live_intervention.cpp create mode 100644 src/ui/live_intervention.hpp create mode 100644 src/ui/live_intervention_tests.cpp create mode 100644 src/ui/live_matchday.cpp create mode 100644 src/ui/live_matchday.hpp create mode 100644 src/ui/live_reality.cpp create mode 100644 src/ui/live_reality.hpp create mode 100644 src/ui/live_set_piece.cpp create mode 100644 src/ui/live_set_piece.hpp create mode 100644 src/ui/mailbox_screen.cpp create mode 100644 src/ui/mailbox_screen.hpp create mode 100644 src/ui/mailbox_screen_tests.cpp create mode 100644 src/ui/mailbox_state.cpp create mode 100644 src/ui/mailbox_state.hpp create mode 100644 src/ui/mailbox_state_tests.cpp create mode 100644 src/ui/main.cpp create mode 100644 src/ui/manager.cpp create mode 100644 src/ui/manager.hpp create mode 100644 src/ui/manager_tests.cpp create mode 100644 src/ui/matchday_results.cpp create mode 100644 src/ui/matchday_results.hpp create mode 100644 src/ui/matchday_results_screen.cpp create mode 100644 src/ui/matchday_results_screen.hpp create mode 100644 src/ui/matchday_results_tests.cpp create mode 100644 src/ui/minute_statistics.cpp create mode 100644 src/ui/minute_statistics.hpp create mode 100644 src/ui/minute_statistics_tests.cpp create mode 100644 src/ui/national_friendly_ui.cpp create mode 100644 src/ui/national_friendly_ui.hpp create mode 100644 src/ui/opportunities.cpp create mode 100644 src/ui/opportunities.hpp create mode 100644 src/ui/opportunities_tests.cpp create mode 100644 src/ui/other_games.cpp create mode 100644 src/ui/other_games.hpp create mode 100644 src/ui/other_games_state.cpp create mode 100644 src/ui/other_games_state.hpp create mode 100644 src/ui/outgoing_transfer.cpp create mode 100644 src/ui/outgoing_transfer.hpp create mode 100644 src/ui/outgoing_transfer_tests.cpp create mode 100644 src/ui/pending_offer.cpp create mode 100644 src/ui/pending_offer.hpp create mode 100644 src/ui/pitch.cpp create mode 100644 src/ui/pitch.hpp create mode 100644 src/ui/pitch_tests.cpp create mode 100644 src/ui/player_card.cpp create mode 100644 src/ui/player_card.hpp create mode 100644 src/ui/player_card_tests.cpp create mode 100644 src/ui/preparation.cpp create mode 100644 src/ui/preparation.hpp create mode 100644 src/ui/preparation_flow.cpp create mode 100644 src/ui/preparation_tests.cpp create mode 100644 src/ui/process_timer.cpp create mode 100644 src/ui/process_timer.hpp create mode 100644 src/ui/reality_reporter.cpp create mode 100644 src/ui/reality_reporter.hpp create mode 100644 src/ui/save_load.cpp create mode 100644 src/ui/save_load.hpp create mode 100644 src/ui/season_entrants.cpp create mode 100644 src/ui/season_entrants.hpp create mode 100644 src/ui/season_entrants_tests.cpp create mode 100644 src/ui/season_promotion.cpp create mode 100644 src/ui/season_promotion.hpp create mode 100644 src/ui/series_records.cpp create mode 100644 src/ui/series_records.hpp create mode 100644 src/ui/series_records_tests.cpp create mode 100644 src/ui/settings.cpp create mode 100644 src/ui/settings.hpp create mode 100644 src/ui/settings_tests.cpp create mode 100644 src/ui/setup.cpp create mode 100644 src/ui/setup.hpp create mode 100644 src/ui/source_hold.hpp create mode 100644 src/ui/source_notice_test_helpers.hpp create mode 100644 src/ui/sportschau.cpp create mode 100644 src/ui/sportschau.hpp create mode 100644 src/ui/sprite_font.cpp create mode 100644 src/ui/sprite_font.hpp create mode 100644 src/ui/sprite_font_tests.cpp create mode 100644 src/ui/stadium.cpp create mode 100644 src/ui/stadium.hpp create mode 100644 src/ui/statistics_rankings.cpp create mode 100644 src/ui/statistics_rankings.hpp create mode 100644 src/ui/statistics_rankings_tests.cpp create mode 100644 src/ui/strengths.cpp create mode 100644 src/ui/strengths.hpp create mode 100644 src/ui/strengths_state.cpp create mode 100644 src/ui/strengths_state.hpp create mode 100644 src/ui/tactics.cpp create mode 100644 src/ui/tactics.hpp create mode 100644 src/ui/tactics_tests.cpp create mode 100644 src/ui/team_statistics.cpp create mode 100644 src/ui/team_statistics.hpp create mode 100644 src/ui/tests.cpp create mode 100644 src/ui/top_scorers.cpp create mode 100644 src/ui/top_scorers.hpp create mode 100644 src/ui/top_scorers_state.cpp create mode 100644 src/ui/top_scorers_state.hpp create mode 100644 src/ui/top_scorers_tests.cpp create mode 100644 src/ui/toto.cpp create mode 100644 src/ui/toto.hpp create mode 100644 src/ui/training.cpp create mode 100644 src/ui/training.hpp create mode 100644 src/ui/training_camp.cpp create mode 100644 src/ui/training_camp.hpp create mode 100644 src/ui/training_camp_tests.cpp create mode 100644 src/ui/training_tests.cpp create mode 100644 src/ui/transfer_history.cpp create mode 100644 src/ui/transfer_history.hpp create mode 100644 src/ui/transfer_history_tests.cpp create mode 100644 src/ui/transfer_market.cpp create mode 100644 src/ui/transfer_market.hpp create mode 100644 src/ui/transfer_market_tests.cpp create mode 100644 src/ui/world_cup_statistics.cpp create mode 100644 src/ui/world_cup_statistics.hpp create mode 100644 src/ui/world_cup_statistics_tests.cpp create mode 100644 src/version.hpp create mode 100644 tests/README.md create mode 100644 tests/app_controller_tests.cpp create mode 100644 tests/autosave_tests.cpp create mode 100644 tests/balance_plan_app_tests.cpp create mode 100644 tests/balance_plan_tests.cpp create mode 100644 tests/bank_app_tests.cpp create mode 100644 tests/bank_lender_app_tests.cpp create mode 100644 tests/bank_lender_ui_tests.cpp create mode 100644 tests/blockdump.cpp create mode 100644 tests/capture_check.cpp create mode 100644 tests/capture_io.hpp create mode 100644 tests/career_initial_offers_tests.cpp create mode 100644 tests/cli_console_tests.cpp create mode 100644 tests/cli_protocol_tests.cpp create mode 100644 tests/cli_soak.cpp create mode 100644 tests/club_info_category_tests.cpp create mode 100644 tests/club_info_tests.cpp create mode 100644 tests/club_info_ui_tests.cpp create mode 100644 tests/club_player_detail_tests.cpp create mode 100644 tests/club_player_detail_ui_tests.cpp create mode 100644 tests/cmake/repo_hygiene.cmake create mode 100644 tests/competition_winner_tests.cpp create mode 100644 tests/credit_interest_weekly_tests.cpp create mode 100644 tests/cup_calendar_boundary_tests.cpp create mode 100644 tests/cup_cursor_tests.cpp create mode 100644 tests/cup_draw_ui_tests.cpp create mode 100644 tests/cup_followup_tests.cpp create mode 100644 tests/cup_script_oracle.cpp create mode 100644 tests/cup_seeded_followup_tests.cpp create mode 100644 tests/desk_check.cpp create mode 100644 tests/desktop_data_tests.cpp create mode 100644 tests/driver_barrier_tests.cpp create mode 100644 tests/e13_turn_driver_tests.cpp create mode 100644 tests/environment_tests.cpp create mode 100644 tests/fixture_table_tests.cpp create mode 100644 tests/fixture_tables.hpp create mode 100644 tests/format_tests.cpp create mode 100644 tests/game_end_alternate_tests.cpp create mode 100644 tests/game_end_app_tests.cpp create mode 100644 tests/game_end_cli_tests.cpp create mode 100644 tests/game_end_tax_animation_tests.cpp create mode 100644 tests/highscore_tests.cpp create mode 100644 tests/human_buyer_market_app_tests.cpp create mode 100644 tests/human_buyer_market_tests.cpp create mode 100644 tests/human_buyer_pending_app_tests.cpp create mode 100644 tests/human_buyer_pending_offer_tests.cpp create mode 100644 tests/indoor_masters_transition_tests.cpp create mode 100644 tests/init_check.cpp create mode 100644 tests/json_unit_tests.cpp create mode 100644 tests/kickoff_check.cpp create mode 100644 tests/launch_check.cpp create mode 100644 tests/launch_tests.cpp create mode 100644 tests/launch_unit_tests.cpp create mode 100644 tests/league_pairings_data_tests.cpp create mode 100644 tests/league_pairings_tests.cpp create mode 100644 tests/league_table_controls_app_tests.cpp create mode 100644 tests/league_table_controls_flow_tests.cpp create mode 100644 tests/league_views_data_tests.cpp create mode 100644 tests/lineup_assistant_detail_tests.cpp create mode 100644 tests/live_matchday_events_tests.cpp create mode 100644 tests/loaded_manager_loop_app_tests.cpp create mode 100644 tests/loaded_manager_loop_tests.cpp create mode 100644 tests/manager_desks_tests.cpp create mode 100644 tests/manager_join_app_tests.cpp create mode 100644 tests/matchday_intro_tests.cpp create mode 100644 tests/national_coach_desk_app_tests.cpp create mode 100644 tests/national_coach_desk_pending_fixture.hpp create mode 100644 tests/national_coach_desk_tests.cpp create mode 100644 tests/national_cycle_transition_tests.cpp create mode 100644 tests/national_friendly_actions_tests.cpp create mode 100644 tests/national_friendly_ui_tests.cpp create mode 100644 tests/national_nomination_tests.cpp create mode 100644 tests/national_pending_match_tests.cpp create mode 100644 tests/other_games_app_tests.cpp create mode 100644 tests/other_games_projection_tests.cpp create mode 100644 tests/other_games_ui_tests.cpp create mode 100644 tests/package_tests.py create mode 100644 tests/pending_offer_app_tests.cpp create mode 100644 tests/pending_offer_desk_app_tests.cpp create mode 100644 tests/pending_offer_desk_tests.cpp create mode 100644 tests/pending_offer_nested_app_tests.cpp create mode 100644 tests/pending_offer_tests.cpp create mode 100644 tests/pending_offer_ui_tests.cpp create mode 100644 tests/phase_results_career_tests.cpp create mode 100644 tests/play_check.cpp create mode 100644 tests/post_check.cpp create mode 100644 tests/probe.cpp create mode 100644 tests/process_timer_tests.cpp create mode 100644 tests/reality_ball_tests.cpp create mode 100644 tests/reality_career_special_tests.cpp create mode 100644 tests/reality_deferred_tests.cpp create mode 100644 tests/reality_duel_tests.cpp create mode 100644 tests/reality_forced_event_tests.cpp create mode 100644 tests/reality_matchday_tests.cpp create mode 100644 tests/reality_motion_tests.cpp create mode 100644 tests/reality_movement_tests.cpp create mode 100644 tests/reality_reporter_layout_tests.cpp create mode 100644 tests/reality_reporter_tests.cpp create mode 100644 tests/reality_scene_tests.cpp create mode 100644 tests/reality_setup_tests.cpp create mode 100644 tests/reality_space_tests.cpp create mode 100644 tests/reschedule_tests.cpp create mode 100644 tests/runtime_fixture_tables.hpp create mode 100644 tests/save_check.cpp create mode 100644 tests/save_close_fault_tests.cpp create mode 100644 tests/season_cup_draw_app_tests.cpp create mode 100644 tests/season_cup_draw_tests.cpp create mode 100644 tests/season_end_desk_tests.cpp create mode 100644 tests/season_promotion_app_tests.cpp create mode 100644 tests/season_promotion_fixture_support.hpp create mode 100644 tests/season_promotion_tests.cpp create mode 100644 tests/season_sim.cpp create mode 100644 tests/season_tax_tests.cpp create mode 100644 tests/season_transition_tests.cpp create mode 100644 tests/shared_desktop_actions_tests.cpp create mode 100644 tests/skip_test.cpp create mode 100644 tests/sound_settings_app_tests.cpp create mode 100644 tests/sportschau_app_tests.cpp create mode 100644 tests/sportschau_eleven_tests.cpp create mode 100644 tests/sportschau_rating_tests.cpp create mode 100644 tests/sportschau_scene_tests.cpp create mode 100644 tests/sportschau_teaminfo_tests.cpp create mode 100644 tests/sportschau_ui_tests.cpp create mode 100644 tests/squad_dump.cpp create mode 100644 tests/stadium_block_app_tests.cpp create mode 100644 tests/stadium_block_expansion_tests.cpp create mode 100644 tests/stadium_block_ui_tests.cpp create mode 100644 tests/stand_block_actions_tests.cpp create mode 100644 tests/statistics_case2_app_tests.cpp create mode 100644 tests/table_print.cpp create mode 100644 tests/tax_animation_unit_tests.cpp create mode 100644 tests/team_statistics_source_oracle_tests.cpp create mode 100644 tests/team_statistics_tests.cpp create mode 100644 tests/test_inputs.hpp create mode 100644 tests/textfind.cpp create mode 100644 tests/top_scorers_app_tests.cpp create mode 100644 tests/toto_actions_tests.cpp create mode 100644 tests/training_camp_actions_tests.cpp create mode 100644 tests/training_camp_app_tests.cpp create mode 100644 tests/training_dispatch_app_tests.cpp create mode 100644 tests/transfer_bid_qualification_tests.cpp create mode 100644 tests/transfer_market_preview_app_tests.cpp create mode 100644 tests/transfer_market_preview_tests.cpp create mode 100644 tests/transfer_offer_class_app_tests.cpp create mode 100644 tests/transfer_offer_editor_tests.cpp create mode 100644 tests/transfer_offer_player_info_tests.cpp create mode 100644 tests/transfer_offer_team_info_tests.cpp create mode 100644 tests/ui_season_promotion_tests.cpp create mode 100644 tests/week_check.cpp create mode 100644 tests/weekly_human_buyer_loan_tests.cpp create mode 100644 tests/youth_academy_tests.cpp create mode 100644 tools/agentic_qa/advance.sh create mode 100644 tools/agentic_qa/send.sh create mode 100644 tools/cli_concept/check_concept.py create mode 100644 tools/package/make_package.py create mode 100644 tools/package/make_source_package.py create mode 100644 tools/package/make_windows_package.sh create mode 100644 tools/public_release/check_public_tree.py create mode 100644 tools/public_release/collect_differences.py create mode 100644 tools/public_release/collect_layout.py create mode 100644 tools/public_release/test_public_tree.py create mode 100644 tools/soak/console_longrun.sh diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cc23192 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.bat text eol=crlf diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..b32be23 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: GPL-3.0-only +name: Bug report +description: Report a reproducible OpenBMH problem. +body: + - type: markdown + attributes: + value: "Do not attach original game files, saves, screenshots, recordings or logs containing game text or personal information. Describe the problem in your own words." + - type: input + id: version + attributes: + label: OpenBMH version or commit + validations: + required: true + - type: input + id: platform + attributes: + label: Operating system and architecture + validations: + required: true + - type: input + id: edition + attributes: + label: Game edition and version + description: "Edition name only; do not upload its files." + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: "Include relevant settings or console commands, with private paths removed." + validations: + required: true + - type: textarea + id: behavior + attributes: + label: Expected and actual behavior + validations: + required: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d782334 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,93 @@ +# SPDX-License-Identifier: GPL-3.0-only +name: Build without game data + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-24.04 + platform: linux-x64 + - runner: windows-2022 + platform: windows-x64 + - runner: macos-14 + platform: macos-arm64 + runs-on: ${{ matrix.runner }} + timeout-minutes: 90 + env: + SDL_VIDEODRIVER: dummy + SDL_AUDIODRIVER: dummy + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + fetch-depth: 0 + - name: Install Linux build dependencies + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y build-essential git cmake ninja-build pkg-config libgtk-3-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev libasound2-dev libpulse-dev libgl1-mesa-dev libudev-dev + - name: Verify source export + run: python3 tools/public_release/check_public_tree.py --root . --history + - name: Set up MSVC x64 + if: runner.os == 'Windows' + uses: ilammy/msvc-dev-cmd@a102174a2b586eec2ea151a69e6fd14404a8ce7c # v1.13.0 + with: + arch: x64 + - name: Configure Windows x64 + if: runner.os == 'Windows' + run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBMH_DATA= -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + - name: Configure Linux + if: runner.os == 'Linux' + run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBMH_DATA= -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DSDL_ALSA=ON -DSDL_PULSEAUDIO=ON -DSDL_X11=ON + - name: Verify Linux audio and video backends + if: runner.os == 'Linux' + shell: python + run: | + import pathlib, re + required = ['SDL_AUDIO_DRIVER_ALSA', 'SDL_AUDIO_DRIVER_PULSEAUDIO', 'SDL_VIDEO_DRIVER_X11'] + headers = list(pathlib.Path('build/_deps/sdl2-build').rglob('SDL_config.h')) + assert any(all(re.search(r'^#define\s+' + macro + r'\s+1\s*$', p.read_text(), re.M) for macro in required) for p in headers), 'ALSA/PulseAudio/X11 were not configured into SDL' + - name: Configure macOS arm64 + if: runner.os == 'macOS' + run: | + test "$(uname -m)" = arm64 + cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 -DBMH_DATA= -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + - name: Build every target + run: cmake --build build --config Release --parallel 2 + - name: Run synthetic tests and report data tests as skipped + run: ctest --test-dir build -C Release --output-on-failure --output-junit test-results.xml + - name: Package products and licenses + run: python3 tools/package/make_package.py --build build --out dist --platform ${{ matrix.platform }} + - name: Package corresponding source and pinned dependencies + if: runner.os == 'Linux' + run: python3 tools/package/make_source_package.py --source . --build build --out source-dist + - name: Upload corresponding source + if: runner.os == 'Linux' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: OpenBMH-source + path: source-dist/*.zip + if-no-files-found: error + - name: Upload package + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: OpenBMH-${{ matrix.platform }} + path: dist/*.zip + if-no-files-found: error + - name: Upload test report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: tests-${{ matrix.platform }} + path: build/test-results.xml + if-no-files-found: warn diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..6c9ff24 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: GPL-3.0-only +name: Prepare release packages + +on: + push: + tags: ['v*'] + +permissions: + contents: read + +jobs: + build: + uses: ./.github/workflows/ci.yml + draft: + needs: build + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + fetch-depth: 0 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: OpenBMH-* + path: dist + merge-multiple: true + - name: Create draft for review + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + for package in dist/*.zip; do + case "$(basename "$package")" in + OpenBMH-${RELEASE_TAG#v}-*.zip) ;; + *) echo "Release tag and package version differ" >&2; exit 1 ;; + esac + done + gh release create "$RELEASE_TAG" dist/*.zip --draft --verify-tag --title "OpenBMH $RELEASE_TAG" --notes-file docs/release/0.1/RELEASE_NOTES.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ef7bed4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# Game installations, saves, captures and local reference data stay external. +/game-data/ +/reference-data/ +/local-data/ +*.FBM +*.fbm +*.VGA +*.vga +*.BLK +*.blk +*.COL +*.col +*.LBM +*.lbm +*.FNT +*.fnt +*.WAP +*.wap +*.wav +*.avi + +# Build output and platform tooling. +/build*/ +/out/ +/dist/ +/_deps/ +/.cache/ +/.vs/ +*.exe +*.EXE +*.dll +*.dylib +*.so +*.o +*.obj +*.a +*.lib +*.pdb +*.zip +*.7z +*.dmg +__pycache__/ +.DS_Store diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md new file mode 100644 index 0000000..252b4c1 --- /dev/null +++ b/ACKNOWLEDGEMENTS.md @@ -0,0 +1,11 @@ +# Acknowledgements + +OpenBMH recognises the programmers, artists, musicians, designers and other contributors who created *Bundesliga Manager Hattrick* and *Football Limited*. Their work is the reason this reconstruction exists. The credits in the original games remain the authoritative record of their contributors. + +The *Bundesliga Manager Hattrick* credits name Werner Krahe and Jens Onnen among the original contributors. We thank them and the wider teams behind both games. + +Thanks also to the player and fan-edition communities for preserving knowledge of these games, documenting their behaviour and keeping interest in football management games alive. + +The project benefits from the work of the SDL, miniz, LZMA SDK, nativefiledialog-extended and Nuked OPL3 contributors, and from development tools including Ghidra, DOSBox, CMake and Ninja. Dependency copyrights and license terms are recorded in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). + +Acknowledgement does not imply sponsorship, affiliation or endorsement. Original games and third-party projects retain their own rights and identities. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6eb79d9 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,18 @@ +# Working on OpenBMH + +Start with [README.md](README.md), [CONTRIBUTING.md](CONTRIBUTING.md) and [docs/architecture.md](docs/architecture.md). Use [docs/CONSOLE_CLIENTS.md](docs/CONSOLE_CLIENTS.md) when writing clients that operate the game. + +## Boundaries + +- This repository distributes implementation and documentation, not original game content. Do not add original executables, saves, graphics, audio, manuals, text inventories or decompiled output. +- Use synthetic fixtures for public tests. Read a locally supplied game installation only through documented configuration such as `BMH_DATA`; do not bake a developer's filesystem path into code or docs. +- Work within the requested scope. Check existing changes and coordinate shared-file edits. Do not overwrite another contributor's work. +- Do not publish releases, push branches or contact external services unless the task authorises it. + +## Code and tests + +Keep rules in `src/game`, file readers in `src/formats` and session ownership/rollback in `src/app`. Reuse shared actions from graphical and console frontends. Preserve deterministic random streams, save layout and revision/manager checks. Errors need explicit outcomes; do not invent a gameplay fallback for an unsupported path. + +Use semantic identifiers and English comments. Document deliberate compatibility changes. Run checks appropriate to the actual change and report their outcome and limits; do not claim unexecuted platform or runtime tests. Keep generated builds outside tracked source files. + +OpenBMH-owned changes use GPL-3.0-only. Third-party notices and full license texts must remain intact, including attribution within upstream license files. Report licensing questions to the maintainers instead of rewriting vendor notices. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d5e4093 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,1090 @@ +# SPDX-License-Identifier: GPL-3.0-only +cmake_minimum_required(VERSION 3.24) +project(OpenBMH VERSION 0.1.0 LANGUAGES CXX C) +# the one place of the version: --version of both programs and the window title (src/version.hpp) +add_compile_definitions(OPENBMH_VERSION="${PROJECT_VERSION}") + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(BMH_DATA "" CACHE PATH "Optional directory containing externally supplied game data") +set(BMH_REFERENCE "" CACHE PATH "Optional directory containing externally supplied reference inputs") +set(BMH_TEST_INPUTS "" CACHE PATH "Optional directory containing external integration-test inputs") +if(BMH_DATA AND NOT IS_DIRECTORY "${BMH_DATA}") + message(FATAL_ERROR "BMH_DATA was set but is not an existing directory: ${BMH_DATA}") +endif() +if(BMH_DATA) + file(GLOB data_entries "${BMH_DATA}/*") + set(has_game_executable FALSE) + foreach(entry IN LISTS data_entries) + get_filename_component(filename "${entry}" NAME) + string(TOLOWER "${filename}" filename) + if(filename STREQUAL "bmh.exe" OR filename STREQUAL "fltd.exe") + set(has_game_executable TRUE) + endif() + endforeach() + if(NOT has_game_executable) + message(FATAL_ERROR "BMH_DATA does not contain a game executable: ${BMH_DATA}") + endif() +endif() +add_executable(openbmh_test_skip tests/skip_test.cpp) + +# Keep data-dependent tests visible without distributing their inputs. Missing +# optional inputs are reported as skipped, never as successful assertions. +function(bmh_add_data_test) + cmake_parse_arguments(T "NO_GAME_DATA" "NAME;DATA_DIR" "COMMAND;REQUIRED_OPTIONS;REQUIRED_FILES" ${ARGN}) + if("DATA_DIR" IN_LIST T_KEYWORDS_MISSING_VALUES) + set(T_DATA_DIR "") + elseif(NOT DEFINED T_DATA_DIR) + set(T_DATA_DIR "${BMH_DATA}") + endif() + set(reason "") + set(external_text_tests season_transition_tests environment_tests cli_console_tests + ui_desktop_tests ui_lineup_tests format_tests app_controller_tests bank_app_tests + cli_soak ui_cup_draw_tests league_pairings_tests ui_pending_offer_tests + reality_reporter_layout_tests season_cup_draw_app_tests + ui_team_statistics_source_oracle_tests transfer_bid_qualification_tests + ui_achievements_tests ui_analytics_tests ui_opportunities_tests + ui_outgoing_transfer_tests ui_season_entrants_tests ui_statistics_rankings_tests) + if(T_NAME IN_LIST external_text_tests) + list(APPEND T_REQUIRED_OPTIONS BMH_TEST_INPUTS) + list(APPEND T_REQUIRED_FILES expected-text.tsv) + endif() + if(T_NAME STREQUAL "format_tests" AND BMH_REFERENCE) + list(APPEND T_REQUIRED_OPTIONS BMH_REFERENCE) + list(APPEND T_REQUIRED_FILES format-matches.tsv format-team-values.tsv) + endif() + if(T_NO_GAME_DATA) + # This test needs only its explicit reference file, not an installation. + elseif(NOT T_DATA_DIR) + set(reason "External game data not configured") + elseif(NOT IS_DIRECTORY "${T_DATA_DIR}") + message(FATAL_ERROR "Invalid game data directory for ${T_NAME}: ${T_DATA_DIR}") + endif() + foreach(option IN LISTS T_REQUIRED_OPTIONS) + if(NOT "${${option}}" OR NOT EXISTS "${${option}}") + set(reason "External test input not supplied: ${option}") + endif() + endforeach() + foreach(file IN LISTS T_REQUIRED_FILES) + if(NOT BMH_TEST_INPUTS OR NOT EXISTS "${BMH_TEST_INPUTS}/${file}") + set(reason "External integration input missing: ${file}") + endif() + endforeach() + if(reason) + add_test(NAME ${T_NAME} COMMAND openbmh_test_skip "${reason}") + else() + add_test(NAME ${T_NAME} COMMAND ${T_COMMAND}) + if(BMH_TEST_INPUTS) + set_property(TEST ${T_NAME} APPEND PROPERTY ENVIRONMENT "OPENBMH_TEST_INPUTS=${BMH_TEST_INPUTS}") + endif() + endif() + set_tests_properties(${T_NAME} PROPERTIES SKIP_RETURN_CODE 77 LABELS "external-data") +endfunction() + +find_package(Python3 COMPONENTS Interpreter QUIET) + +# Windows gives a thread 1 MB of stack (Linux 8 MB). Release builds inline the many test +# functions of an app test into main(), whose frame then holds several CareerSession +# objects and GameState checkpoints at once - over 1 MB, a stack overflow (0xC00000FD) at +# entry. 16 MB for every program built here, as on the other platforms. +if(MSVC) + add_link_options(/STACK:16777216) +endif() + +option(BMH_USE_SYSTEM_SDL2 "Use an installed SDL2 instead of fetching the pinned release" OFF) +if(BMH_USE_SYSTEM_SDL2) + find_package(SDL2 REQUIRED CONFIG) + set(BMH_SDL_TARGET SDL2::SDL2) +else() +include(FetchContent) +set(SDL_SHARED OFF CACHE BOOL "" FORCE) +set(SDL_STATIC ON CACHE BOOL "" FORCE) +set(SDL_TEST OFF CACHE BOOL "" FORCE) +FetchContent_Declare(SDL2 + GIT_REPOSITORY https://github.com/libsdl-org/SDL.git + GIT_TAG release-2.32.10 + GIT_SHALLOW TRUE) +FetchContent_MakeAvailable(SDL2) +set(BMH_SDL_TARGET SDL2::SDL2-static) +endif() + +# SDL2 renames main when SDL.h is included. Link SDL2main before SDL2 for +# every executable that consumes SDL, when the selected SDL package provides it. +if(TARGET SDL2::SDL2main) + list(PREPEND BMH_SDL_TARGET SDL2::SDL2main) +endif() + +# App sources share objects only within identical compile environments. +# MSVC consumers currently differ in target/source /utf-8 flags; keep that path. +set(BMH_APP_SESSION_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/app/career_session.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/app/window_actions.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/app/desktop_actions.cpp") +set(BMH_APP_SESSION_SDL_SOURCE "${BMH_APP_SESSION_SOURCE}") +set(BMH_APP_CONTROLLER_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/app/controller.cpp") +if(NOT MSVC) + add_library(bmh_app_session OBJECT src/app/career_session.cpp src/app/window_actions.cpp src/app/desktop_actions.cpp) + 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) + 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}) + set(BMH_APP_SESSION_SOURCE "$") + set(BMH_APP_SESSION_SDL_SOURCE "$") + set(BMH_APP_CONTROLLER_SOURCE "$") +endif() + +# (before the first subdirectory: tests added there are only registered once testing is on) +enable_testing() +if(Python3_Interpreter_FOUND) + add_test(NAME public_source_guard COMMAND ${Python3_EXECUTABLE} + "${CMAKE_SOURCE_DIR}/tools/public_release/check_public_tree.py" --root "${CMAKE_SOURCE_DIR}") + add_test(NAME public_source_guard_tests COMMAND ${Python3_EXECUTABLE} + "${CMAKE_SOURCE_DIR}/tools/public_release/test_public_tree.py") + add_test(NAME package_allowlist_tests COMMAND ${Python3_EXECUTABLE} + "${CMAKE_SOURCE_DIR}/tests/package_tests.py") + add_test(NAME cli_concept_tests COMMAND ${Python3_EXECUTABLE} + "${CMAKE_SOURCE_DIR}/tools/cli_concept/check_concept.py" --root "${CMAKE_SOURCE_DIR}") + add_test(NAME documented_differences_tests COMMAND ${Python3_EXECUTABLE} + "${CMAKE_SOURCE_DIR}/tools/public_release/collect_differences.py" --root "${CMAKE_SOURCE_DIR}" --check) +endif() +add_subdirectory(src/audio) + +add_executable(season_end_desk_tests tests/season_end_desk_tests.cpp ${BMH_APP_SESSION_SOURCE}) +add_executable(national_pending_match_tests tests/national_pending_match_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(national_pending_match_tests PRIVATE bmhui) +set(BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_1 "" CACHE PATH "External input 1 for national_pending_match_tests; not distributed") +set(BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_2 "" CACHE PATH "External input 2 for national_pending_match_tests; not distributed") +bmh_add_data_test(NAME national_pending_match_tests REQUIRED_OPTIONS BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_1 BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_2 COMMAND national_pending_match_tests "${BMH_DATA}" + "${BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_1}" + "${BMH_TEST_NATIONAL_PENDING_MATCH_TESTS_INPUT_2}") +target_link_libraries(season_end_desk_tests PRIVATE bmhui) +set(BMH_TEST_SEASON_END_DESK_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_end_desk_tests; not distributed") +bmh_add_data_test(NAME season_end_desk_tests REQUIRED_OPTIONS BMH_TEST_SEASON_END_DESK_TESTS_INPUT_1 COMMAND season_end_desk_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_END_DESK_TESTS_INPUT_1}") + +add_executable(season_transition_tests tests/season_transition_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(season_transition_tests PRIVATE bmhui) +set(BMH_TEST_SEASON_TRANSITION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_transition_tests; not distributed") +bmh_add_data_test(NAME season_transition_tests REQUIRED_OPTIONS BMH_TEST_SEASON_TRANSITION_TESTS_INPUT_1 COMMAND season_transition_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_TRANSITION_TESTS_INPUT_1}") + +add_executable(indoor_masters_transition_tests tests/indoor_masters_transition_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(indoor_masters_transition_tests PRIVATE bmhui) +set(BMH_TEST_INDOOR_MASTERS_TRANSITION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for indoor_masters_transition_tests; not distributed") +bmh_add_data_test(NAME indoor_masters_transition_tests REQUIRED_OPTIONS BMH_TEST_INDOOR_MASTERS_TRANSITION_TESTS_INPUT_1 COMMAND indoor_masters_transition_tests "${BMH_DATA}" + "${BMH_TEST_INDOOR_MASTERS_TRANSITION_TESTS_INPUT_1}") + +add_executable(national_cycle_transition_tests tests/national_cycle_transition_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(national_cycle_transition_tests PRIVATE bmhui) +set(BMH_TEST_NATIONAL_CYCLE_TRANSITION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for national_cycle_transition_tests; not distributed") +bmh_add_data_test(NAME national_cycle_transition_tests REQUIRED_OPTIONS BMH_TEST_NATIONAL_CYCLE_TRANSITION_TESTS_INPUT_1 COMMAND national_cycle_transition_tests "${BMH_DATA}" + "${BMH_TEST_NATIONAL_CYCLE_TRANSITION_TESTS_INPUT_1}") + +add_executable(season_tax_tests tests/season_tax_tests.cpp) +target_link_libraries(season_tax_tests PRIVATE bmhcore) +set(BMH_TEST_SEASON_TAX_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_tax_tests; not distributed") +bmh_add_data_test(NAME season_tax_tests REQUIRED_OPTIONS BMH_TEST_SEASON_TAX_TESTS_INPUT_1 COMMAND season_tax_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_TAX_TESTS_INPUT_1}") + +add_executable(highscore_tests tests/highscore_tests.cpp) +target_link_libraries(highscore_tests PRIVATE bmhcore) +set(BMH_TEST_HIGHSCORE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for highscore_tests; not distributed") +bmh_add_data_test(NAME highscore_tests REQUIRED_OPTIONS BMH_TEST_HIGHSCORE_TESTS_INPUT_1 COMMAND highscore_tests "${BMH_DATA}" + "${BMH_TEST_HIGHSCORE_TESTS_INPUT_1}") + +# Engine core: file formats and game logic, no platform dependencies +add_library(bmhcore STATIC + src/formats/binary.cpp + src/formats/palette.cpp + src/formats/vga.cpp + src/formats/font.cpp + src/formats/textd.cpp + src/formats/fbm.cpp + src/formats/le.cpp + src/formats/rule_base.cpp + src/formats/m3d.cpp + src/formats/savestate.cpp + src/game/schedule.cpp + src/game/league_pairings.cpp + src/game/source_tip.cpp + src/game/table_forecast.cpp + src/game/state.cpp + src/game/rating.cpp + src/game/match.cpp + src/game/match_engine.cpp + src/game/reality_motion.cpp + src/game/reality_setup.cpp + src/game/reality_space.cpp + src/game/reality_movement.cpp + src/game/reality_match.cpp + src/game/reality_scene.cpp + src/game/reality_ball.cpp + src/game/reality_duel.cpp + src/game/reality_reporter.cpp + src/game/matchday.cpp + src/game/sportschau_replay.cpp + src/game/sportschau_rating.cpp + src/game/sportschau_awards.cpp + src/game/matchday_setup.cpp + src/game/prediction.cpp + src/game/month.cpp + src/game/desk.cpp + src/game/cup.cpp + src/game/club_info.cpp + src/game/club_player_detail.cpp + src/game/driver.cpp + src/game/season.cpp + src/game/highscore.cpp + src/game/weekly.cpp + src/game/messages.cpp + src/game/table.cpp + src/game/week.cpp + src/game/lineup.cpp + src/game/national.cpp + src/game/desk_actions.cpp + src/game/reschedule.cpp + src/game/balance_plan.cpp + src/game/top_scorers.cpp + src/game/other_games.cpp + src/game/stadium_blocks.cpp + src/game/poach.cpp + src/game/environment.cpp + src/game/bank_credit.cpp + src/game/career.cpp + src/game/save.cpp + src/game/turn.cpp + src/game/turn_driver.cpp +) +target_include_directories(bmhcore PUBLIC src) + +if(MSVC) + target_compile_options(bmhcore PRIVATE /W4 /utf-8) +else() + target_compile_options(bmhcore PRIVATE -Wall -Wextra) +endif() + +add_executable(openbmh src/main.cpp) +target_link_libraries(openbmh PRIVATE bmhcore ${BMH_SDL_TARGET}) +if(MSVC) + target_compile_options(openbmh PRIVATE /utf-8) +endif() + +# --- Game data launcher (src/launch): find, unpack and check the original game data --------- +# ZIP: miniz (MIT), 7z: the C decoder of the LZMA SDK (public domain), file dialog: +# nativefiledialog-extended (zlib). All pinned; fetched like SDL2. +include(FetchContent) +FetchContent_Declare(miniz + URL https://github.com/richgel999/miniz/releases/download/3.0.2/miniz-3.0.2.zip + URL_HASH SHA256=ada38db0b703a56d3dd6d57bf84a9c5d664921d870d8fea4db153979fb5332c5) +FetchContent_Declare(lzma_sdk + GIT_REPOSITORY https://github.com/ip7z/7zip.git + GIT_TAG 24.09 + GIT_SHALLOW TRUE + SOURCE_SUBDIR no-cmake) # (sources only: the repository has no CMake build) +set(NFD_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(NFD_INSTALL OFF CACHE BOOL "" FORCE) +FetchContent_Declare(nfd + GIT_REPOSITORY https://github.com/btzy/nativefiledialog-extended.git + GIT_TAG v1.2.1 + GIT_SHALLOW TRUE) +FetchContent_MakeAvailable(miniz lzma_sdk nfd) + +add_library(bmh_miniz STATIC ${miniz_SOURCE_DIR}/miniz.c) +target_include_directories(bmh_miniz PUBLIC ${miniz_SOURCE_DIR}) +set(BMH_LZMA_C ${lzma_sdk_SOURCE_DIR}/C) +add_library(bmh_7z STATIC + ${BMH_LZMA_C}/7zAlloc.c ${BMH_LZMA_C}/7zArcIn.c ${BMH_LZMA_C}/7zBuf.c ${BMH_LZMA_C}/7zCrc.c + ${BMH_LZMA_C}/7zCrcOpt.c ${BMH_LZMA_C}/7zDec.c ${BMH_LZMA_C}/7zStream.c ${BMH_LZMA_C}/Bcj2.c + ${BMH_LZMA_C}/Bra.c ${BMH_LZMA_C}/Bra86.c ${BMH_LZMA_C}/BraIA64.c ${BMH_LZMA_C}/CpuArch.c + ${BMH_LZMA_C}/Delta.c ${BMH_LZMA_C}/Lzma2Dec.c ${BMH_LZMA_C}/LzmaDec.c ${BMH_LZMA_C}/Ppmd7.c + ${BMH_LZMA_C}/Ppmd7Dec.c) +target_include_directories(bmh_7z PUBLIC ${BMH_LZMA_C}) +target_compile_definitions(bmh_7z PUBLIC Z7_PPMD_SUPPORT Z7_EXTRACT_ONLY) + +add_library(bmhlaunch STATIC src/launch/archive.cpp src/launch/game_data.cpp src/launch/fltd.cpp) +target_include_directories(bmhlaunch PUBLIC src) +target_link_libraries(bmhlaunch PUBLIC bmhcore PRIVATE bmh_miniz bmh_7z) +if(WIN32) + target_link_libraries(bmhlaunch PRIVATE shell32) # CommandLineToArgvW +endif() +add_library(bmhlaunch_dialog STATIC src/launch/file_dialog.cpp) +target_link_libraries(bmhlaunch_dialog PUBLIC bmhlaunch PRIVATE nfd::nfd) +if(MSVC) + target_compile_options(bmhlaunch PRIVATE /W4 /utf-8) + target_compile_options(bmhlaunch_dialog PRIVATE /utf-8) +endif() + +add_subdirectory(src/ui) +add_executable(driver_barrier_tests tests/driver_barrier_tests.cpp) +target_link_libraries(driver_barrier_tests PRIVATE bmhcore) +add_test(NAME driver_barrier_tests COMMAND driver_barrier_tests) +add_executable(format_tests tests/format_tests.cpp) +target_link_libraries(format_tests PRIVATE bmhcore) +if(MSVC) + target_compile_options(format_tests PRIVATE /utf-8) +endif() +add_test(NAME format_unit_tests COMMAND format_tests) +bmh_add_data_test(NAME format_tests REQUIRED_OPTIONS BMH_TEST_INPUTS + REQUIRED_FILES expected-text.tsv format-players.tsv format-start.fbm + COMMAND format_tests "${BMH_DATA}" "${BMH_REFERENCE}") + +add_executable(stand_block_actions_tests tests/stand_block_actions_tests.cpp) +target_link_libraries(stand_block_actions_tests PRIVATE bmhcore) +add_test(NAME stand_block_actions_tests COMMAND stand_block_actions_tests) + +add_executable(toto_actions_tests tests/toto_actions_tests.cpp) +target_link_libraries(toto_actions_tests PRIVATE bmhcore) +add_test(NAME toto_actions_tests COMMAND toto_actions_tests) + +add_executable(e13_turn_driver_tests tests/e13_turn_driver_tests.cpp) +target_link_libraries(e13_turn_driver_tests PRIVATE bmhcore) +set(BMH_TEST_E13_TURN_DRIVER_TESTS_INPUT_1 "" CACHE PATH "External input 1 for e13_turn_driver_tests; not distributed") +bmh_add_data_test(NAME e13_turn_driver_tests REQUIRED_OPTIONS BMH_TEST_E13_TURN_DRIVER_TESTS_INPUT_1 COMMAND e13_turn_driver_tests "${BMH_DATA}" + "${BMH_TEST_E13_TURN_DRIVER_TESTS_INPUT_1}") + +add_executable(balance_plan_tests tests/balance_plan_tests.cpp) +target_link_libraries(balance_plan_tests PRIVATE bmhcore) +set(BMH_TEST_BALANCE_PLAN_TESTS_INPUT_1 "" CACHE PATH "External input 1 for balance_plan_tests; not distributed") +bmh_add_data_test(NAME balance_plan_tests REQUIRED_OPTIONS BMH_TEST_BALANCE_PLAN_TESTS_INPUT_1 COMMAND balance_plan_tests "${BMH_DATA}" + "${BMH_TEST_BALANCE_PLAN_TESTS_INPUT_1}") + +add_executable(training_camp_actions_tests tests/training_camp_actions_tests.cpp) +target_link_libraries(training_camp_actions_tests PRIVATE bmhcore) +add_test(NAME training_camp_actions_tests COMMAND training_camp_actions_tests) + +add_executable(lineup_assistant_detail_tests tests/lineup_assistant_detail_tests.cpp) +target_link_libraries(lineup_assistant_detail_tests PRIVATE bmhcore) +add_test(NAME lineup_assistant_detail_tests COMMAND lineup_assistant_detail_tests) + +add_executable(reschedule_tests tests/reschedule_tests.cpp) +target_link_libraries(reschedule_tests PRIVATE bmhcore) +set(BMH_TEST_RESCHEDULE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for reschedule_tests; not distributed") +bmh_add_data_test(NAME reschedule_tests REQUIRED_OPTIONS BMH_TEST_RESCHEDULE_TESTS_INPUT_1 COMMAND reschedule_tests "${BMH_DATA}" + "${BMH_TEST_RESCHEDULE_TESTS_INPUT_1}") + +add_executable(environment_tests tests/environment_tests.cpp) +target_link_libraries(environment_tests PRIVATE bmhcore) +set(BMH_TEST_ENVIRONMENT_TESTS_INPUT_1 "" CACHE PATH "External input 1 for environment_tests; not distributed") +bmh_add_data_test(NAME environment_tests REQUIRED_OPTIONS BMH_TEST_ENVIRONMENT_TESTS_INPUT_1 COMMAND environment_tests "${BMH_DATA}" + "${BMH_TEST_ENVIRONMENT_TESTS_INPUT_1}") + +add_executable(youth_academy_tests tests/youth_academy_tests.cpp) +target_link_libraries(youth_academy_tests PRIVATE bmhcore) +set(BMH_TEST_YOUTH_ACADEMY_TESTS_INPUT_1 "" CACHE PATH "External input 1 for youth_academy_tests; not distributed") +bmh_add_data_test(NAME youth_academy_tests REQUIRED_OPTIONS BMH_TEST_YOUTH_ACADEMY_TESTS_INPUT_1 COMMAND youth_academy_tests "${BMH_DATA}" + "${BMH_TEST_YOUTH_ACADEMY_TESTS_INPUT_1}") + +# Development helper: prints computed values of a savegame for comparison with the original +add_executable(probe tests/probe.cpp) +target_link_libraries(probe PRIVATE bmhcore) +if(MSVC) + target_compile_options(probe PRIVATE /utf-8) +endif() + +# Development helper: compares the ported engine with a matchday recorded from the original +add_executable(capture_check tests/capture_check.cpp) +target_link_libraries(capture_check PRIVATE bmhcore) +if(MSVC) + target_compile_options(capture_check PRIVATE /utf-8) +endif() + +# Development helper: compares the ported matchday processing with post-match snapshots +add_executable(post_check tests/post_check.cpp) +target_link_libraries(post_check PRIVATE bmhcore) +if(MSVC) + target_compile_options(post_check PRIVATE /utf-8) +endif() + +# Development helper: hex dump of one savegame block +add_executable(blockdump tests/blockdump.cpp) +target_link_libraries(blockdump PRIVATE bmhcore) +# Development helper: prints a club's squad from a savegame (player, age, words) +add_executable(squad_dump tests/squad_dump.cpp) +target_link_libraries(squad_dump PRIVATE bmhcore) + +# Development helper: replays a recorded turn (matchday + week) section by section +add_executable(week_check tests/week_check.cpp) +target_link_libraries(week_check PRIVATE bmhcore) +if(MSVC) + target_compile_options(week_check PRIVATE /utf-8) +endif() + +# Development helper: the kick-off of a matchday with a human team, from the pre-match desk +add_executable(kickoff_check tests/kickoff_check.cpp) +target_link_libraries(kickoff_check PRIVATE bmhcore) + +# Development helper: league table computed from a savegame +add_executable(table_print tests/table_print.cpp) +target_link_libraries(table_print PRIVATE bmhcore) +if(MSVC) + target_compile_options(table_print PRIVATE /utf-8) +endif() + +add_executable(textfind tests/textfind.cpp) +target_link_libraries(textfind PRIVATE bmhcore) +if(MSVC) + target_compile_options(textfind PRIVATE /utf-8) +endif() + +# Development helper: replays desk actions (training camp, ...) between two post snapshots +add_executable(desk_check tests/desk_check.cpp) +target_link_libraries(desk_check PRIVATE bmhcore) + +# Development helper: the start of a new career against ref/2p/init_capture.jsonl +add_executable(init_check tests/init_check.cpp) +target_link_libraries(init_check PRIVATE bmhcore) + +# The playable program: the shared UI library connected to the engine by src/app. +add_executable(openbmh_play + src/app/main.cpp + ${BMH_APP_CONTROLLER_SOURCE} + ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(openbmh_play PRIVATE bmhui bmhlaunch_dialog openbmh_audio ${BMH_SDL_TARGET}) +# a game without a console window on double-click (SDL2main provides WinMain); started from a +# console it attaches to that one for --version, --help and start errors (src/app/main.cpp) +set_target_properties(openbmh_play PROPERTIES WIN32_EXECUTABLE TRUE) +if(MSVC) + target_compile_options(openbmh_play PRIVATE /utf-8) + # App sources also compile in headless tests/helpers without target /utf-8. + set_source_files_properties(src/app/career_session.cpp src/app/window_actions.cpp + src/app/desktop_actions.cpp PROPERTIES COMPILE_OPTIONS /utf-8) +endif() + +# Development helper: drives the career session like the UI, without a window +add_executable(play_check tests/play_check.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(play_check PRIVATE bmhui) +if(MSVC) + target_compile_options(play_check PRIVATE /utf-8) +endif() + +add_executable(training_camp_app_tests tests/training_camp_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(training_camp_app_tests PRIVATE bmhui) +bmh_add_data_test(NAME training_camp_app_tests COMMAND training_camp_app_tests "${BMH_DATA}") +add_executable(bank_app_tests tests/bank_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(bank_app_tests PRIVATE bmhui) +bmh_add_data_test(NAME bank_app_tests REQUIRED_OPTIONS BMH_TEST_INPUTS REQUIRED_FILES bank-deadline.fbm bank-timer.fbm bank-cup.fbm COMMAND bank_app_tests "${BMH_DATA}") + +add_executable(shared_desktop_actions_tests tests/shared_desktop_actions_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(shared_desktop_actions_tests PRIVATE bmhui) +set(BMH_TEST_SHARED_DESKTOP_ACTIONS_TESTS_INPUT_1 "" CACHE PATH "External input 1 for shared_desktop_actions_tests; not distributed") +bmh_add_data_test(NAME shared_desktop_actions_tests REQUIRED_OPTIONS BMH_TEST_SHARED_DESKTOP_ACTIONS_TESTS_INPUT_1 COMMAND shared_desktop_actions_tests "${BMH_DATA}" + "${BMH_TEST_SHARED_DESKTOP_ACTIONS_TESTS_INPUT_1}") + +add_executable(credit_interest_weekly_tests tests/credit_interest_weekly_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(credit_interest_weekly_tests PRIVATE bmhui) +bmh_add_data_test(NAME credit_interest_weekly_tests COMMAND credit_interest_weekly_tests "${BMH_DATA}") + +add_executable(app_controller_tests tests/app_controller_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(app_controller_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +if(MSVC) + target_compile_options(app_controller_tests PRIVATE /utf-8) +endif() +bmh_add_data_test(NAME app_controller_tests COMMAND app_controller_tests "${BMH_DATA}") +set(BMH_TEST_APP_DELAY_SETTINGS_TESTS_INPUT_1 "" CACHE PATH "External input 1 for app_delay_settings_tests; not distributed") +bmh_add_data_test(NAME app_delay_settings_tests REQUIRED_OPTIONS BMH_TEST_APP_DELAY_SETTINGS_TESTS_INPUT_1 COMMAND app_controller_tests "${BMH_DATA}" + --delay-settings-only "${BMH_TEST_APP_DELAY_SETTINGS_TESTS_INPUT_1}") + +add_executable(sound_settings_app_tests tests/sound_settings_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(sound_settings_app_tests PRIVATE bmhui) +set(BMH_TEST_SOUND_SETTINGS_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sound_settings_app_tests; not distributed") +bmh_add_data_test(NAME sound_settings_app_tests REQUIRED_OPTIONS BMH_TEST_SOUND_SETTINGS_APP_TESTS_INPUT_1 COMMAND sound_settings_app_tests "${BMH_DATA}" + "${BMH_TEST_SOUND_SETTINGS_APP_TESTS_INPUT_1}") + +add_executable(statistics_case2_app_tests tests/statistics_case2_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(statistics_case2_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_STATISTICS_CASE2_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for statistics_case2_app_tests; not distributed") +bmh_add_data_test(NAME statistics_case2_app_tests REQUIRED_OPTIONS BMH_TEST_STATISTICS_CASE2_APP_TESTS_INPUT_1 COMMAND statistics_case2_app_tests "${BMH_DATA}" + "${BMH_TEST_STATISTICS_CASE2_APP_TESTS_INPUT_1}") + +add_executable(national_friendly_actions_tests tests/national_friendly_actions_tests.cpp) +target_link_libraries(national_friendly_actions_tests PRIVATE bmhcore) +add_test(NAME national_friendly_actions_tests COMMAND national_friendly_actions_tests) + +add_executable(manager_join_app_tests tests/manager_join_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(manager_join_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +if(MSVC) + target_compile_options(manager_join_app_tests PRIVATE /utf-8) +endif() +set(BMH_TEST_MANAGER_JOIN_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for manager_join_app_tests; not distributed") +bmh_add_data_test(NAME manager_join_app_tests REQUIRED_OPTIONS BMH_TEST_MANAGER_JOIN_APP_TESTS_INPUT_1 COMMAND manager_join_app_tests "${BMH_DATA}" + "${BMH_TEST_MANAGER_JOIN_APP_TESTS_INPUT_1}") + +add_executable(live_matchday_events_tests tests/live_matchday_events_tests.cpp) +target_include_directories(live_matchday_events_tests PRIVATE src) +target_link_libraries(live_matchday_events_tests PRIVATE ${BMH_SDL_TARGET}) +add_test(NAME live_matchday_events_tests COMMAND live_matchday_events_tests) + +add_executable(reality_motion_tests tests/reality_motion_tests.cpp) +target_link_libraries(reality_motion_tests PRIVATE bmhui) +bmh_add_data_test(NAME reality_motion_tests COMMAND reality_motion_tests "${BMH_DATA}") + +add_executable(reality_setup_tests tests/reality_setup_tests.cpp) +target_link_libraries(reality_setup_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_setup_tests COMMAND reality_setup_tests "${BMH_DATA}") + +add_executable(reality_space_tests tests/reality_space_tests.cpp) +target_link_libraries(reality_space_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_space_tests COMMAND reality_space_tests "${BMH_DATA}") + +add_executable(reality_movement_tests tests/reality_movement_tests.cpp) +target_link_libraries(reality_movement_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_movement_tests COMMAND reality_movement_tests "${BMH_DATA}") + +add_executable(reality_ball_tests tests/reality_ball_tests.cpp) +target_link_libraries(reality_ball_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_ball_tests COMMAND reality_ball_tests "${BMH_DATA}") + +add_executable(reality_duel_tests tests/reality_duel_tests.cpp) +target_link_libraries(reality_duel_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_duel_tests COMMAND reality_duel_tests "${BMH_DATA}") + +add_executable(reality_forced_event_tests tests/reality_forced_event_tests.cpp) +target_link_libraries(reality_forced_event_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_forced_event_tests COMMAND reality_forced_event_tests "${BMH_DATA}") + +add_executable(reality_reporter_tests tests/reality_reporter_tests.cpp) +target_link_libraries(reality_reporter_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_reporter_tests COMMAND reality_reporter_tests "${BMH_DATA}") + +add_executable(reality_matchday_tests tests/reality_matchday_tests.cpp) +target_link_libraries(reality_matchday_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_matchday_tests COMMAND reality_matchday_tests "${BMH_DATA}") + +add_executable(reality_career_special_tests tests/reality_career_special_tests.cpp ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(reality_career_special_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_REALITY_CAREER_SPECIAL_TESTS_INPUT_1 "" CACHE PATH "External input 1 for reality_career_special_tests; not distributed") +bmh_add_data_test(NAME reality_career_special_tests REQUIRED_OPTIONS BMH_TEST_REALITY_CAREER_SPECIAL_TESTS_INPUT_1 COMMAND reality_career_special_tests "${BMH_DATA}" + "${BMH_TEST_REALITY_CAREER_SPECIAL_TESTS_INPUT_1}") + +add_executable(reality_deferred_tests tests/reality_deferred_tests.cpp) +target_link_libraries(reality_deferred_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_deferred_tests COMMAND reality_deferred_tests "${BMH_DATA}") + +add_executable(phase_results_career_tests tests/phase_results_career_tests.cpp ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(phase_results_career_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +bmh_add_data_test(NAME phase_results_career_tests COMMAND phase_results_career_tests "${BMH_DATA}") + +add_executable(reality_scene_tests tests/reality_scene_tests.cpp) +target_link_libraries(reality_scene_tests PRIVATE bmhcore) +bmh_add_data_test(NAME reality_scene_tests COMMAND reality_scene_tests "${BMH_DATA}") + +add_executable(reality_reporter_layout_tests tests/reality_reporter_layout_tests.cpp) +target_link_libraries(reality_reporter_layout_tests PRIVATE bmhui) +bmh_add_data_test(NAME reality_reporter_layout_tests COMMAND reality_reporter_layout_tests "${BMH_DATA}") + +add_executable(training_dispatch_app_tests tests/training_dispatch_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(training_dispatch_app_tests PRIVATE bmhui) +if(MSVC) + target_compile_options(training_dispatch_app_tests PRIVATE /utf-8) +endif() +bmh_add_data_test(NAME training_dispatch_app_tests COMMAND training_dispatch_app_tests "${BMH_DATA}") + +# Development helper: savegames loaded and written again must be identical +add_executable(save_check tests/save_check.cpp) +target_link_libraries(save_check PRIVATE bmhcore) +if(UNIX) + add_executable(save_close_fault_tests tests/save_close_fault_tests.cpp) + target_link_libraries(save_close_fault_tests PRIVATE bmhcore) + set(BMH_TEST_SAVE_CLOSE_FAULT_TESTS_INPUT_1 "" CACHE PATH "External input 1 for save_close_fault_tests; not distributed") + bmh_add_data_test(NAME save_close_fault_tests NO_GAME_DATA REQUIRED_OPTIONS BMH_TEST_SAVE_CLOSE_FAULT_TESTS_INPUT_1 COMMAND save_close_fault_tests + "${BMH_TEST_SAVE_CLOSE_FAULT_TESTS_INPUT_1}") +endif() + +# Plausibility run: a new career played headless through the turn driver (E7) +add_executable(season_sim tests/season_sim.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(season_sim PRIVATE bmhui) +if(MSVC) + target_compile_options(season_sim PRIVATE /utf-8) +endif() + +# Headless terminal/protocol client; owns no game logic and has no SDL dependency. +add_executable(openbmh_cli + src/cli/main.cpp + src/cli/protocol.cpp + src/cli/console/console.cpp + src/cli/console/parser.cpp + src/cli/console/windows_start.cpp + src/cli/console/windows_desk.cpp + src/cli/console/windows_tables.cpp + src/cli/console/windows_club.cpp + src/cli/console/windows_money.cpp + src/cli/console/windows_office.cpp + src/cli/console/windows_squad.cpp + src/cli/console/windows_transfer.cpp + src/cli/console/windows_info.cpp + src/cli/console/windows_match.cpp + src/cli/console/windows_friendly.cpp + src/cli/console/windows_reschedule.cpp + src/cli/console/windows_balance.cpp + src/cli/console/windows_environment.cpp + src/cli/console/windows_state.cpp + src/cli/seat_hub.cpp + src/cli/json.cpp + ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(openbmh_cli PRIVATE bmhui bmhlaunch) +if(WIN32) + target_link_libraries(openbmh_cli PRIVATE ws2_32) # --listen (Winsock) +endif() +if(MSVC) + target_compile_options(openbmh_cli PRIVATE /utf-8) +endif() + +add_executable(cli_protocol_tests tests/cli_protocol_tests.cpp src/cli/protocol.cpp src/cli/json.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(cli_protocol_tests PRIVATE bmhui) +if(MSVC) + target_compile_options(cli_protocol_tests PRIVATE /utf-8) +endif() +bmh_add_data_test(NAME cli_protocol_tests COMMAND cli_protocol_tests "${BMH_DATA}") + +# Console language of openbmh_cli (docs/CLI_CONCEPT): parser, golden transcripts, JSON, +# replay and the registry check against commands.csv +add_executable(cli_console_tests tests/cli_console_tests.cpp src/cli/console/console.cpp src/cli/console/parser.cpp + src/cli/console/windows_start.cpp src/cli/console/windows_desk.cpp src/cli/console/windows_tables.cpp src/cli/console/windows_club.cpp src/cli/console/windows_money.cpp src/cli/console/windows_office.cpp src/cli/console/windows_squad.cpp src/cli/console/windows_transfer.cpp src/cli/console/windows_info.cpp src/cli/console/windows_match.cpp src/cli/console/windows_friendly.cpp src/cli/console/windows_reschedule.cpp src/cli/console/windows_balance.cpp src/cli/console/windows_environment.cpp src/cli/console/windows_state.cpp src/cli/json.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(cli_console_tests PRIVATE bmhui) +add_test(NAME cli_parser_unit_tests COMMAND cli_console_tests --parser-only) +if(MSVC) + target_compile_options(cli_console_tests PRIVATE /utf-8) +endif() +set(BMH_TEST_CLI_CONSOLE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for cli_console_tests; not distributed") +set(BMH_TEST_CLI_TRANSCRIPTS "" CACHE PATH "External console transcript expectations") +bmh_add_data_test(NAME cli_console_tests REQUIRED_OPTIONS BMH_TEST_INPUTS BMH_TEST_CLI_TRANSCRIPTS BMH_TEST_CLI_CONSOLE_TESTS_INPUT_1 REQUIRED_FILES loan-return.fbm human-transfer.fbm COMMAND cli_console_tests "${BMH_DATA}" "${BMH_TEST_CLI_TRANSCRIPTS}" + "${BMH_TEST_CLI_CONSOLE_TESTS_INPUT_1}" + "${CMAKE_CURRENT_SOURCE_DIR}/docs/CLI_CONCEPT/commands.csv") +# Soak test: random console play over several seasons with invariant checks (tests/cli_soak.cpp). +# CTest runs one short season with two managers; longer runs: cli_soak . +add_executable(cli_soak tests/cli_soak.cpp src/cli/console/console.cpp src/cli/console/parser.cpp + src/cli/console/windows_start.cpp src/cli/console/windows_desk.cpp src/cli/console/windows_tables.cpp src/cli/console/windows_club.cpp src/cli/console/windows_money.cpp src/cli/console/windows_office.cpp src/cli/console/windows_squad.cpp src/cli/console/windows_transfer.cpp src/cli/console/windows_info.cpp src/cli/console/windows_match.cpp src/cli/console/windows_friendly.cpp src/cli/console/windows_reschedule.cpp src/cli/console/windows_balance.cpp src/cli/console/windows_environment.cpp src/cli/console/windows_state.cpp src/cli/json.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(cli_soak PRIVATE bmhui) +if(MSVC) + target_compile_options(cli_soak PRIVATE /utf-8) +endif() +bmh_add_data_test(NAME cli_soak COMMAND cli_soak "${BMH_DATA}" "${CMAKE_CURRENT_BINARY_DIR}/soak" 1 2 7) + +# Repository hygiene: no container login banner in committed files +add_test(NAME repo_hygiene COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_SOURCE_DIR} -P ${CMAKE_SOURCE_DIR}/tests/cmake/repo_hygiene.cmake) + +add_executable(game_end_app_tests tests/game_end_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(game_end_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +if(MSVC) + target_compile_options(game_end_app_tests PRIVATE /utf-8) +endif() +set(BMH_TEST_GAME_END_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for game_end_app_tests; not distributed") +bmh_add_data_test(NAME game_end_app_tests REQUIRED_OPTIONS BMH_TEST_GAME_END_APP_TESTS_INPUT_1 COMMAND game_end_app_tests "${BMH_DATA}" + "${BMH_TEST_GAME_END_APP_TESTS_INPUT_1}") + +add_executable(game_end_cli_tests tests/game_end_cli_tests.cpp src/cli/protocol.cpp src/cli/json.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(game_end_cli_tests PRIVATE bmhui) +if(MSVC) + target_compile_options(game_end_cli_tests PRIVATE /utf-8) +endif() +set(BMH_TEST_GAME_END_CLI_TESTS_INPUT_1 "" CACHE PATH "External input 1 for game_end_cli_tests; not distributed") +bmh_add_data_test(NAME game_end_cli_tests REQUIRED_OPTIONS BMH_TEST_GAME_END_CLI_TESTS_INPUT_1 COMMAND game_end_cli_tests "${BMH_DATA}" + "${BMH_TEST_GAME_END_CLI_TESTS_INPUT_1}") + +add_executable(season_promotion_app_tests tests/season_promotion_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(season_promotion_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_SEASON_PROMOTION_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_promotion_app_tests; not distributed") +bmh_add_data_test(NAME season_promotion_app_tests REQUIRED_OPTIONS BMH_TEST_SEASON_PROMOTION_APP_TESTS_INPUT_1 COMMAND season_promotion_app_tests "${BMH_DATA}" "${BMH_TEST_SEASON_PROMOTION_APP_TESTS_INPUT_1}") + +add_executable(season_promotion_tests tests/season_promotion_tests.cpp) +target_link_libraries(season_promotion_tests PRIVATE bmhcore) +set(BMH_TEST_SEASON_PROMOTION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_promotion_tests; not distributed") +bmh_add_data_test(NAME season_promotion_tests REQUIRED_OPTIONS BMH_TEST_SEASON_PROMOTION_TESTS_INPUT_1 COMMAND season_promotion_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_PROMOTION_TESTS_INPUT_1}" 589388519 665367) +add_executable(ui_season_promotion_tests tests/ui_season_promotion_tests.cpp) +target_link_libraries(ui_season_promotion_tests PRIVATE bmhui) +set(BMH_TEST_UI_SEASON_PROMOTION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_season_promotion_tests; not distributed") +bmh_add_data_test(NAME ui_season_promotion_tests REQUIRED_OPTIONS BMH_TEST_UI_SEASON_PROMOTION_TESTS_INPUT_1 COMMAND ui_season_promotion_tests "${BMH_DATA}" + "${BMH_TEST_UI_SEASON_PROMOTION_TESTS_INPUT_1}") + +add_executable(national_nomination_tests tests/national_nomination_tests.cpp) +target_link_libraries(national_nomination_tests PRIVATE bmhcore) +set(BMH_TEST_NATIONAL_NOMINATION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for national_nomination_tests; not distributed") +bmh_add_data_test(NAME national_nomination_tests REQUIRED_OPTIONS BMH_TEST_NATIONAL_NOMINATION_TESTS_INPUT_1 COMMAND national_nomination_tests "${BMH_DATA}" + "${BMH_TEST_NATIONAL_NOMINATION_TESTS_INPUT_1}") + +add_executable(season_cup_draw_app_tests tests/season_cup_draw_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(season_cup_draw_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_SEASON_CUP_DRAW_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_cup_draw_app_tests; not distributed") +bmh_add_data_test(NAME season_cup_draw_app_tests REQUIRED_OPTIONS BMH_TEST_SEASON_CUP_DRAW_APP_TESTS_INPUT_1 COMMAND season_cup_draw_app_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_CUP_DRAW_APP_TESTS_INPUT_1}") + +add_executable(season_cup_draw_tests tests/season_cup_draw_tests.cpp) +target_link_libraries(season_cup_draw_tests PRIVATE bmhcore) +set(BMH_TEST_SEASON_CUP_DRAW_TESTS_INPUT_1 "" CACHE PATH "External input 1 for season_cup_draw_tests; not distributed") +bmh_add_data_test(NAME season_cup_draw_tests REQUIRED_OPTIONS BMH_TEST_SEASON_CUP_DRAW_TESTS_INPUT_1 COMMAND season_cup_draw_tests "${BMH_DATA}" + "${BMH_TEST_SEASON_CUP_DRAW_TESTS_INPUT_1}" 589388519 665367) + +add_executable(cup_followup_tests tests/cup_followup_tests.cpp) +target_link_libraries(cup_followup_tests PRIVATE bmhcore) +add_executable(cup_seeded_followup_tests tests/cup_seeded_followup_tests.cpp) +target_link_libraries(cup_seeded_followup_tests PRIVATE bmhcore) +add_test(NAME cup_seeded_followup_tests COMMAND cup_seeded_followup_tests) + +add_executable(cup_calendar_boundary_tests tests/cup_calendar_boundary_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(cup_calendar_boundary_tests PRIVATE bmhui) +set(BMH_TEST_CUP_CALENDAR_BOUNDARY_TESTS_INPUT_1 "" CACHE PATH "External input 1 for cup_calendar_boundary_tests; not distributed") +bmh_add_data_test(NAME cup_calendar_boundary_tests REQUIRED_OPTIONS BMH_TEST_CUP_CALENDAR_BOUNDARY_TESTS_INPUT_1 COMMAND cup_calendar_boundary_tests "${BMH_DATA}" + "${BMH_TEST_CUP_CALENDAR_BOUNDARY_TESTS_INPUT_1}") +set(BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for cup_followup_tests; not distributed") +set(BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_2 "" CACHE PATH "External input 2 for cup_followup_tests; not distributed") +bmh_add_data_test(NAME cup_followup_tests REQUIRED_OPTIONS BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_1 BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_2 COMMAND cup_followup_tests "${BMH_DATA}" + "${BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_1}" + "${BMH_TEST_CUP_FOLLOWUP_TESTS_INPUT_2}") + +add_executable(club_info_tests tests/club_info_tests.cpp) +target_link_libraries(club_info_tests PRIVATE bmhcore) +add_test(NAME club_info_tests COMMAND club_info_tests) + +add_executable(cup_cursor_tests tests/cup_cursor_tests.cpp) +target_link_libraries(cup_cursor_tests PRIVATE bmhcore) +set(BMH_TEST_CUP_CURSOR_TESTS_INPUT_1 "" CACHE PATH "External input 1 for cup_cursor_tests; not distributed") +bmh_add_data_test(NAME cup_cursor_tests REQUIRED_OPTIONS BMH_TEST_CUP_CURSOR_TESTS_INPUT_1 COMMAND cup_cursor_tests "${BMH_DATA}" + "${BMH_TEST_CUP_CURSOR_TESTS_INPUT_1}") +add_executable(club_info_category_tests tests/club_info_category_tests.cpp) +target_link_libraries(club_info_category_tests PRIVATE bmhcore) +add_test(NAME club_info_category_tests COMMAND club_info_category_tests) + +add_executable(club_player_detail_tests tests/club_player_detail_tests.cpp) +target_link_libraries(club_player_detail_tests PRIVATE bmhcore) +bmh_add_data_test(NAME club_player_detail_tests COMMAND club_player_detail_tests "${BMH_DATA}") +add_executable(ui_cup_draw_tests tests/cup_draw_ui_tests.cpp) +target_link_libraries(ui_cup_draw_tests PRIVATE bmhui) +set(BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_cup_draw_tests; not distributed") +set(BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_2 "" CACHE PATH "External input 2 for ui_cup_draw_tests; not distributed") +bmh_add_data_test(NAME ui_cup_draw_tests REQUIRED_OPTIONS BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_1 BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_2 COMMAND ui_cup_draw_tests "${BMH_DATA}" + "${BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_1}" + "${BMH_TEST_UI_CUP_DRAW_TESTS_INPUT_2}") + +add_executable(cup_script_oracle tests/cup_script_oracle.cpp) +target_link_libraries(cup_script_oracle PRIVATE bmhui) +bmh_add_data_test(NAME cup_script_oracle COMMAND cup_script_oracle "${BMH_DATA}") + +add_executable(career_initial_offers_tests tests/career_initial_offers_tests.cpp) +target_link_libraries(career_initial_offers_tests PRIVATE bmhcore) +bmh_add_data_test(NAME career_initial_offers_tests COMMAND career_initial_offers_tests "${BMH_DATA}") + +add_executable(pending_offer_tests tests/pending_offer_tests.cpp) +target_link_libraries(pending_offer_tests PRIVATE bmhcore) +set(BMH_TEST_PENDING_OFFER_TESTS_INPUT_1 "" CACHE PATH "External input 1 for pending_offer_tests; not distributed") +bmh_add_data_test(NAME pending_offer_tests REQUIRED_OPTIONS BMH_TEST_PENDING_OFFER_TESTS_INPUT_1 COMMAND pending_offer_tests "${BMH_DATA}" + "${BMH_TEST_PENDING_OFFER_TESTS_INPUT_1}") + +add_executable(pending_offer_app_tests tests/pending_offer_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(pending_offer_app_tests PRIVATE bmhui) +set(BMH_TEST_PENDING_OFFER_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for pending_offer_app_tests; not distributed") +bmh_add_data_test(NAME pending_offer_app_tests REQUIRED_OPTIONS BMH_TEST_PENDING_OFFER_APP_TESTS_INPUT_1 COMMAND pending_offer_app_tests "${BMH_DATA}" + "${BMH_TEST_PENDING_OFFER_APP_TESTS_INPUT_1}") + +add_executable(pending_offer_nested_app_tests tests/pending_offer_nested_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(pending_offer_nested_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for pending_offer_nested_app_tests; not distributed") +set(BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_2 "" CACHE PATH "External input 2 for pending_offer_nested_app_tests; not distributed") +bmh_add_data_test(NAME pending_offer_nested_app_tests REQUIRED_OPTIONS BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_1 BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_2 COMMAND pending_offer_nested_app_tests "${BMH_DATA}" + "${BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_1}" + "${BMH_TEST_PENDING_OFFER_NESTED_APP_TESTS_INPUT_2}") + +add_executable(pending_offer_desk_tests tests/pending_offer_desk_tests.cpp) +target_link_libraries(pending_offer_desk_tests PRIVATE bmhcore) +set(BMH_TEST_PENDING_OFFER_DESK_TESTS_INPUT_1 "" CACHE PATH "External input 1 for pending_offer_desk_tests; not distributed") +bmh_add_data_test(NAME pending_offer_desk_tests REQUIRED_OPTIONS BMH_TEST_PENDING_OFFER_DESK_TESTS_INPUT_1 COMMAND pending_offer_desk_tests "${BMH_DATA}" + "${BMH_TEST_PENDING_OFFER_DESK_TESTS_INPUT_1}") + +add_executable(human_buyer_pending_offer_tests tests/human_buyer_pending_offer_tests.cpp) +target_link_libraries(human_buyer_pending_offer_tests PRIVATE bmhcore) +set(BMH_TEST_HUMAN_BUYER_PENDING_OFFER_TESTS_INPUT_1 "" CACHE PATH "External input 1 for human_buyer_pending_offer_tests; not distributed") +bmh_add_data_test(NAME human_buyer_pending_offer_tests REQUIRED_OPTIONS BMH_TEST_HUMAN_BUYER_PENDING_OFFER_TESTS_INPUT_1 COMMAND human_buyer_pending_offer_tests "${BMH_DATA}" + "${BMH_TEST_HUMAN_BUYER_PENDING_OFFER_TESTS_INPUT_1}") + +add_executable(human_buyer_pending_app_tests tests/human_buyer_pending_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(human_buyer_pending_app_tests PRIVATE bmhui) +set(BMH_TEST_HUMAN_BUYER_PENDING_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for human_buyer_pending_app_tests; not distributed") +bmh_add_data_test(NAME human_buyer_pending_app_tests REQUIRED_OPTIONS BMH_TEST_HUMAN_BUYER_PENDING_APP_TESTS_INPUT_1 COMMAND human_buyer_pending_app_tests "${BMH_DATA}" + "${BMH_TEST_HUMAN_BUYER_PENDING_APP_TESTS_INPUT_1}") + +add_executable(human_buyer_market_tests tests/human_buyer_market_tests.cpp) +target_link_libraries(human_buyer_market_tests PRIVATE bmhcore) +set(BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_1 "" CACHE PATH "External input 1 for human_buyer_market_tests; not distributed") +set(BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_2 "" CACHE PATH "External input 2 for human_buyer_market_tests; not distributed") +set(BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_3 "" CACHE PATH "External input 3 for human_buyer_market_tests; not distributed") +bmh_add_data_test(NAME human_buyer_market_tests REQUIRED_OPTIONS BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_1 BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_2 BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_3 COMMAND human_buyer_market_tests "${BMH_DATA}" + "${BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_1}" + "${BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_2}" + "${BMH_TEST_HUMAN_BUYER_MARKET_TESTS_INPUT_3}") + +add_executable(weekly_human_buyer_loan_tests tests/weekly_human_buyer_loan_tests.cpp) +target_link_libraries(weekly_human_buyer_loan_tests PRIVATE bmhcore) +set(BMH_TEST_WEEKLY_HUMAN_BUYER_LOAN_TESTS_INPUT_1 "" CACHE PATH "External input 1 for weekly_human_buyer_loan_tests; not distributed") +bmh_add_data_test(NAME weekly_human_buyer_loan_tests REQUIRED_OPTIONS BMH_TEST_WEEKLY_HUMAN_BUYER_LOAN_TESTS_INPUT_1 COMMAND weekly_human_buyer_loan_tests "${BMH_DATA}" + "${BMH_TEST_WEEKLY_HUMAN_BUYER_LOAN_TESTS_INPUT_1}") + +add_executable(transfer_bid_qualification_tests tests/transfer_bid_qualification_tests.cpp) +target_link_libraries(transfer_bid_qualification_tests PRIVATE bmhcore) +set(BMH_TEST_TRANSFER_BID_QUALIFICATION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_bid_qualification_tests; not distributed") +bmh_add_data_test(NAME transfer_bid_qualification_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_BID_QUALIFICATION_TESTS_INPUT_1 COMMAND transfer_bid_qualification_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_BID_QUALIFICATION_TESTS_INPUT_1}") + +add_executable(transfer_market_preview_tests tests/transfer_market_preview_tests.cpp) +target_link_libraries(transfer_market_preview_tests PRIVATE bmhcore) +set(BMH_TEST_TRANSFER_MARKET_PREVIEW_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_market_preview_tests; not distributed") +bmh_add_data_test(NAME transfer_market_preview_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_MARKET_PREVIEW_TESTS_INPUT_1 COMMAND transfer_market_preview_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_MARKET_PREVIEW_TESTS_INPUT_1}") + +add_executable(transfer_offer_editor_tests tests/transfer_offer_editor_tests.cpp) +target_link_libraries(transfer_offer_editor_tests PRIVATE bmhcore) +set(BMH_TEST_TRANSFER_OFFER_EDITOR_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_offer_editor_tests; not distributed") +bmh_add_data_test(NAME transfer_offer_editor_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_OFFER_EDITOR_TESTS_INPUT_1 COMMAND transfer_offer_editor_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_OFFER_EDITOR_TESTS_INPUT_1}") + +add_executable(transfer_market_preview_app_tests tests/transfer_market_preview_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(transfer_market_preview_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_market_preview_app_tests; not distributed") +set(BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_2 "" CACHE PATH "External input 2 for transfer_market_preview_app_tests; not distributed") +set(BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_3 "" CACHE PATH "External input 3 for transfer_market_preview_app_tests; not distributed") +bmh_add_data_test(NAME transfer_market_preview_app_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_1 BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_2 BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_3 COMMAND transfer_market_preview_app_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_1}" + "${BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_2}" + "${BMH_TEST_TRANSFER_MARKET_PREVIEW_APP_TESTS_INPUT_3}") + +add_executable(transfer_offer_class_app_tests tests/transfer_offer_class_app_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(transfer_offer_class_app_tests PRIVATE bmhui) +set(BMH_TEST_TRANSFER_OFFER_CLASS_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_offer_class_app_tests; not distributed") +bmh_add_data_test(NAME transfer_offer_class_app_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_OFFER_CLASS_APP_TESTS_INPUT_1 COMMAND transfer_offer_class_app_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_OFFER_CLASS_APP_TESTS_INPUT_1}") + +add_executable(human_buyer_market_app_tests tests/human_buyer_market_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(human_buyer_market_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_HUMAN_BUYER_MARKET_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for human_buyer_market_app_tests; not distributed") +bmh_add_data_test(NAME human_buyer_market_app_tests REQUIRED_OPTIONS BMH_TEST_HUMAN_BUYER_MARKET_APP_TESTS_INPUT_1 COMMAND human_buyer_market_app_tests "${BMH_DATA}" + "${BMH_TEST_HUMAN_BUYER_MARKET_APP_TESTS_INPUT_1}") + +add_executable(pending_offer_desk_app_tests tests/pending_offer_desk_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(pending_offer_desk_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_PENDING_OFFER_DESK_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for pending_offer_desk_app_tests; not distributed") +bmh_add_data_test(NAME pending_offer_desk_app_tests REQUIRED_OPTIONS BMH_TEST_PENDING_OFFER_DESK_APP_TESTS_INPUT_1 COMMAND pending_offer_desk_app_tests "${BMH_DATA}" + "${BMH_TEST_PENDING_OFFER_DESK_APP_TESTS_INPUT_1}") + +add_executable(loaded_manager_loop_tests tests/loaded_manager_loop_tests.cpp) +target_link_libraries(loaded_manager_loop_tests PRIVATE bmhcore) +set(BMH_TEST_LOADED_MANAGER_LOOP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for loaded_manager_loop_tests; not distributed") +bmh_add_data_test(NAME loaded_manager_loop_tests REQUIRED_OPTIONS BMH_TEST_LOADED_MANAGER_LOOP_TESTS_INPUT_1 COMMAND loaded_manager_loop_tests "${BMH_DATA}" + "${BMH_TEST_LOADED_MANAGER_LOOP_TESTS_INPUT_1}") + +add_executable(loaded_manager_loop_app_tests tests/loaded_manager_loop_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(loaded_manager_loop_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_LOADED_MANAGER_LOOP_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for loaded_manager_loop_app_tests; not distributed") +bmh_add_data_test(NAME loaded_manager_loop_app_tests REQUIRED_OPTIONS BMH_TEST_LOADED_MANAGER_LOOP_APP_TESTS_INPUT_1 COMMAND loaded_manager_loop_app_tests "${BMH_DATA}" + "${BMH_TEST_LOADED_MANAGER_LOOP_APP_TESTS_INPUT_1}") + +add_executable(national_coach_desk_app_tests tests/national_coach_desk_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(national_coach_desk_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for national_coach_desk_app_tests; not distributed") +set(BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_2 "" CACHE PATH "External input 2 for national_coach_desk_app_tests; not distributed") +bmh_add_data_test(NAME national_coach_desk_app_tests REQUIRED_OPTIONS BMH_TEST_INPUTS BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_1 BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_2 REQUIRED_FILES national-pending.fbm COMMAND national_coach_desk_app_tests "${BMH_DATA}" + "${BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_1}" + "${BMH_TEST_NATIONAL_COACH_DESK_APP_TESTS_INPUT_2}") + +add_executable(national_coach_desk_tests tests/national_coach_desk_tests.cpp) +target_link_libraries(national_coach_desk_tests PRIVATE bmhcore) +set(BMH_TEST_NATIONAL_COACH_DESK_TESTS_INPUT_1 "" CACHE PATH "External input 1 for national_coach_desk_tests; not distributed") +bmh_add_data_test(NAME national_coach_desk_tests REQUIRED_OPTIONS BMH_TEST_NATIONAL_COACH_DESK_TESTS_INPUT_1 COMMAND national_coach_desk_tests "${BMH_DATA}" + "${BMH_TEST_NATIONAL_COACH_DESK_TESTS_INPUT_1}") + +add_executable(transfer_offer_team_info_tests tests/transfer_offer_team_info_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(transfer_offer_team_info_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_TRANSFER_OFFER_TEAM_INFO_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_offer_team_info_tests; not distributed") +bmh_add_data_test(NAME transfer_offer_team_info_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_OFFER_TEAM_INFO_TESTS_INPUT_1 COMMAND transfer_offer_team_info_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_OFFER_TEAM_INFO_TESTS_INPUT_1}") + +add_executable(transfer_offer_player_info_tests tests/transfer_offer_player_info_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(transfer_offer_player_info_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_TRANSFER_OFFER_PLAYER_INFO_TESTS_INPUT_1 "" CACHE PATH "External input 1 for transfer_offer_player_info_tests; not distributed") +bmh_add_data_test(NAME transfer_offer_player_info_tests REQUIRED_OPTIONS BMH_TEST_TRANSFER_OFFER_PLAYER_INFO_TESTS_INPUT_1 COMMAND transfer_offer_player_info_tests "${BMH_DATA}" + "${BMH_TEST_TRANSFER_OFFER_PLAYER_INFO_TESTS_INPUT_1}") + +add_executable(league_pairings_tests tests/league_pairings_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(league_pairings_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_LEAGUE_PAIRINGS_TESTS_INPUT_1 "" CACHE PATH "External input 1 for league_pairings_tests; not distributed") +bmh_add_data_test(NAME league_pairings_tests REQUIRED_OPTIONS BMH_TEST_LEAGUE_PAIRINGS_TESTS_INPUT_1 COMMAND league_pairings_tests "${BMH_DATA}" + "${BMH_TEST_LEAGUE_PAIRINGS_TESTS_INPUT_1}") + +add_executable(league_pairings_data_tests tests/league_pairings_data_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(league_pairings_data_tests PRIVATE bmhui) +bmh_add_data_test(NAME league_pairings_data_tests COMMAND league_pairings_data_tests "${BMH_DATA}") + +add_executable(desktop_data_tests tests/desktop_data_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(desktop_data_tests PRIVATE bmhui) +bmh_add_data_test(NAME desktop_data_tests COMMAND desktop_data_tests "${BMH_DATA}") + +add_executable(league_views_data_tests tests/league_views_data_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(league_views_data_tests PRIVATE bmhui) +bmh_add_data_test(NAME league_views_data_tests COMMAND league_views_data_tests "${BMH_DATA}") + +# FLTD is translated by launch_check/the launcher first. Do not point these +# tests at the raw DOS directory: the shared UI consumes the prepared image. +set(BMH_ENGLISH_DATA "" CACHE PATH "Prepared Football Limited game-data directory") + bmh_add_data_test(NAME english_pairings_data_tests DATA_DIR "${BMH_ENGLISH_DATA}" COMMAND league_pairings_data_tests "${BMH_ENGLISH_DATA}") + bmh_add_data_test(NAME english_desktop_data_tests DATA_DIR "${BMH_ENGLISH_DATA}" COMMAND desktop_data_tests "${BMH_ENGLISH_DATA}" --english) + bmh_add_data_test(NAME english_league_views_data_tests DATA_DIR "${BMH_ENGLISH_DATA}" COMMAND league_views_data_tests "${BMH_ENGLISH_DATA}") + bmh_add_data_test(NAME english_training_camp_ui_tests REQUIRED_OPTIONS BMH_TEST_INPUTS REQUIRED_FILES camp-label-colors.bin DATA_DIR "${BMH_ENGLISH_DATA}" COMMAND ui_training_camp_tests "${BMH_ENGLISH_DATA}") + bmh_add_data_test(NAME english_training_camp_content_tests DATA_DIR "${BMH_ENGLISH_DATA}" COMMAND training_camp_app_tests "${BMH_ENGLISH_DATA}" --content-only) + +add_executable(league_table_controls_app_tests tests/league_table_controls_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(league_table_controls_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +# This scenario binds the captured German manager/league/date in WEEK196. +set(BMH_TEST_LEAGUE_TABLE_CONTROLS_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for league_table_controls_app_tests; not distributed") +bmh_add_data_test(NAME league_table_controls_app_tests REQUIRED_OPTIONS BMH_TEST_LEAGUE_TABLE_CONTROLS_APP_TESTS_INPUT_1 COMMAND league_table_controls_app_tests "${BMH_DATA}" + "${BMH_TEST_LEAGUE_TABLE_CONTROLS_APP_TESTS_INPUT_1}") + +add_executable(manager_desks_tests tests/manager_desks_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(manager_desks_tests PRIVATE bmhui) +set(BMH_TEST_MANAGER_DESKS_TESTS_INPUT_1 "" CACHE PATH "External input 1 for manager_desks_tests; not distributed") +bmh_add_data_test(NAME manager_desks_tests REQUIRED_OPTIONS BMH_TEST_MANAGER_DESKS_TESTS_INPUT_1 COMMAND manager_desks_tests "${BMH_DATA}" + "${BMH_TEST_MANAGER_DESKS_TESTS_INPUT_1}") + +add_executable(league_table_controls_flow_tests tests/league_table_controls_flow_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(league_table_controls_flow_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_LEAGUE_TABLE_CONTROLS_FLOW_TESTS_INPUT_1 "" CACHE PATH "External input 1 for league_table_controls_flow_tests; not distributed") +bmh_add_data_test(NAME league_table_controls_flow_tests REQUIRED_OPTIONS BMH_TEST_LEAGUE_TABLE_CONTROLS_FLOW_TESTS_INPUT_1 COMMAND league_table_controls_flow_tests "${BMH_DATA}" + "${BMH_TEST_LEAGUE_TABLE_CONTROLS_FLOW_TESTS_INPUT_1}") + +add_executable(balance_plan_app_tests tests/balance_plan_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(balance_plan_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_BALANCE_PLAN_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for balance_plan_app_tests; not distributed") +bmh_add_data_test(NAME balance_plan_app_tests REQUIRED_OPTIONS BMH_TEST_BALANCE_PLAN_APP_TESTS_INPUT_1 COMMAND balance_plan_app_tests "${BMH_DATA}" + "${BMH_TEST_BALANCE_PLAN_APP_TESTS_INPUT_1}") + +add_executable(top_scorers_app_tests tests/top_scorers_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(top_scorers_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +bmh_add_data_test(NAME top_scorers_app_tests COMMAND top_scorers_app_tests "${BMH_DATA}") + +add_executable(other_games_projection_tests tests/other_games_projection_tests.cpp) +target_link_libraries(other_games_projection_tests PRIVATE bmhcore) +add_test(NAME other_games_projection_tests COMMAND other_games_projection_tests) + +add_executable(other_games_app_tests tests/other_games_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(other_games_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +bmh_add_data_test(NAME other_games_app_tests COMMAND other_games_app_tests "${BMH_DATA}") + +add_executable(other_games_ui_tests tests/other_games_ui_tests.cpp) +target_link_libraries(other_games_ui_tests PRIVATE bmhui) +bmh_add_data_test(NAME other_games_ui_tests COMMAND other_games_ui_tests "${BMH_DATA}") + +add_executable(process_timer_tests tests/process_timer_tests.cpp) +target_link_libraries(process_timer_tests PRIVATE bmhui) +bmh_add_data_test(NAME process_timer_tests COMMAND process_timer_tests "${BMH_DATA}") + +add_executable(stadium_block_expansion_tests tests/stadium_block_expansion_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(stadium_block_expansion_tests PRIVATE bmhui) +set(BMH_TEST_STADIUM_BLOCK_EXPANSION_TESTS_INPUT_1 "" CACHE PATH "External input 1 for stadium_block_expansion_tests; not distributed") +bmh_add_data_test(NAME stadium_block_expansion_tests REQUIRED_OPTIONS BMH_TEST_STADIUM_BLOCK_EXPANSION_TESTS_INPUT_1 COMMAND stadium_block_expansion_tests "${BMH_DATA}" "${BMH_TEST_STADIUM_BLOCK_EXPANSION_TESTS_INPUT_1}") + +add_executable(stadium_block_ui_tests tests/stadium_block_ui_tests.cpp) +target_link_libraries(stadium_block_ui_tests PRIVATE bmhui) +bmh_add_data_test(NAME stadium_block_ui_tests COMMAND stadium_block_ui_tests "${BMH_DATA}") + +add_executable(stadium_block_app_tests tests/stadium_block_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(stadium_block_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +bmh_add_data_test(NAME stadium_block_app_tests REQUIRED_OPTIONS BMH_TEST_INPUTS REQUIRED_FILES stadium.fbm COMMAND stadium_block_app_tests "${BMH_DATA}") + +# Launcher: check the game data like the program start (tests/launch_check.cpp is a helper, +# tests/launch_tests.cpp the CTest with generated archives). +add_executable(launch_check tests/launch_check.cpp) +target_link_libraries(launch_check PRIVATE bmhlaunch) +add_executable(launch_tests tests/launch_tests.cpp) +target_link_libraries(launch_tests PRIVATE bmhlaunch bmh_miniz) +bmh_add_data_test(NAME launch_tests COMMAND launch_tests "${BMH_DATA}") + +add_executable(bank_lender_ui_tests tests/bank_lender_ui_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(bank_lender_ui_tests PRIVATE bmhui) +bmh_add_data_test(NAME bank_lender_ui_tests COMMAND bank_lender_ui_tests "${BMH_DATA}") + +add_executable(bank_lender_app_tests tests/bank_lender_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +target_link_libraries(bank_lender_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +bmh_add_data_test(NAME bank_lender_app_tests COMMAND bank_lender_app_tests "${BMH_DATA}") + +add_executable(sportschau_app_tests tests/sportschau_app_tests.cpp ${BMH_APP_CONTROLLER_SOURCE} ${BMH_APP_SESSION_SDL_SOURCE}) +add_executable(sportschau_scene_tests tests/sportschau_scene_tests.cpp ${BMH_APP_SESSION_SOURCE}) +add_executable(sportschau_rating_tests tests/sportschau_rating_tests.cpp ${BMH_APP_SESSION_SOURCE}) +add_executable(sportschau_eleven_tests tests/sportschau_eleven_tests.cpp ${BMH_APP_SESSION_SOURCE}) +add_executable(competition_winner_tests tests/competition_winner_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(competition_winner_tests PRIVATE bmhui) +set(BMH_TEST_COMPETITION_WINNER_TESTS_INPUT_1 "" CACHE PATH "External input 1 for competition_winner_tests; not distributed") +bmh_add_data_test(NAME competition_winner_tests REQUIRED_OPTIONS BMH_TEST_COMPETITION_WINNER_TESTS_INPUT_1 COMMAND competition_winner_tests "${BMH_DATA}" + "${BMH_TEST_COMPETITION_WINNER_TESTS_INPUT_1}") +add_executable(matchday_intro_tests tests/matchday_intro_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(matchday_intro_tests PRIVATE bmhui) +set(BMH_TEST_MATCHDAY_INTRO_TESTS_INPUT_1 "" CACHE PATH "External input 1 for matchday_intro_tests; not distributed") +bmh_add_data_test(NAME matchday_intro_tests REQUIRED_OPTIONS BMH_TEST_MATCHDAY_INTRO_TESTS_INPUT_1 COMMAND matchday_intro_tests "${BMH_DATA}" + "${BMH_TEST_MATCHDAY_INTRO_TESTS_INPUT_1}") +add_executable(sportschau_teaminfo_tests tests/sportschau_teaminfo_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(sportschau_teaminfo_tests PRIVATE bmhui) +set(BMH_TEST_SPORTSCHAU_TEAMINFO_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sportschau_teaminfo_tests; not distributed") +bmh_add_data_test(NAME sportschau_teaminfo_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU_TEAMINFO_TESTS_INPUT_1 COMMAND sportschau_teaminfo_tests "${BMH_DATA}" + "${BMH_TEST_SPORTSCHAU_TEAMINFO_TESTS_INPUT_1}") +target_link_libraries(sportschau_eleven_tests PRIVATE bmhui) +set(BMH_TEST_SPORTSCHAU_ELEVEN_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sportschau_eleven_tests; not distributed") +bmh_add_data_test(NAME sportschau_eleven_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU_ELEVEN_TESTS_INPUT_1 COMMAND sportschau_eleven_tests "${BMH_DATA}" + "${BMH_TEST_SPORTSCHAU_ELEVEN_TESTS_INPUT_1}") +target_link_libraries(sportschau_rating_tests PRIVATE bmhui) +set(BMH_TEST_SPORTSCHAU_RATING_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sportschau_rating_tests; not distributed") +bmh_add_data_test(NAME sportschau_rating_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU_RATING_TESTS_INPUT_1 COMMAND sportschau_rating_tests "${BMH_DATA}" + "${BMH_TEST_SPORTSCHAU_RATING_TESTS_INPUT_1}") +target_link_libraries(sportschau_scene_tests PRIVATE bmhui) +set(BMH_TEST_SPORTSCHAU_SCENE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sportschau_scene_tests; not distributed") +bmh_add_data_test(NAME sportschau_scene_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU_SCENE_TESTS_INPUT_1 COMMAND sportschau_scene_tests "${BMH_DATA}" + "${BMH_TEST_SPORTSCHAU_SCENE_TESTS_INPUT_1}") +add_executable(autosave_tests tests/autosave_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(autosave_tests PRIVATE bmhui) +set(BMH_TEST_AUTOSAVE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for autosave_tests; not distributed") +bmh_add_data_test(NAME autosave_tests REQUIRED_OPTIONS BMH_TEST_AUTOSAVE_TESTS_INPUT_1 COMMAND autosave_tests "${BMH_DATA}" + "${BMH_TEST_AUTOSAVE_TESTS_INPUT_1}") +target_link_libraries(sportschau_app_tests PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET}) +set(BMH_TEST_SPORTSCHAU_APP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for sportschau_app_tests; not distributed") +bmh_add_data_test(NAME sportschau_app_tests REQUIRED_OPTIONS BMH_TEST_SPORTSCHAU_APP_TESTS_INPUT_1 COMMAND sportschau_app_tests "${BMH_DATA}" + "${BMH_TEST_SPORTSCHAU_APP_TESTS_INPUT_1}") + +# The runtime component deliberately contains only the two products and notices. +install(TARGETS openbmh_play openbmh_cli RUNTIME DESTINATION . COMPONENT Runtime) +install(FILES README.md LICENSE THIRD_PARTY_NOTICES.md ACKNOWLEDGEMENTS.md CONTRIBUTING.md + DESTINATION . COMPONENT Runtime) +install(DIRECTORY docs/ DESTINATION docs COMPONENT Runtime) +if(MSVC) + set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION .) + set(CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT Runtime) + set(CMAKE_INSTALL_UCRT_LIBRARIES TRUE) + include(InstallRequiredSystemLibraries) +endif() + +add_executable(tax_animation_unit_tests tests/tax_animation_unit_tests.cpp) +target_link_libraries(tax_animation_unit_tests PRIVATE bmhui) +add_test(NAME tax_animation_unit_tests COMMAND tax_animation_unit_tests) +add_executable(json_unit_tests tests/json_unit_tests.cpp src/cli/json.cpp) +target_include_directories(json_unit_tests PRIVATE src) +add_test(NAME json_unit_tests COMMAND json_unit_tests) +add_executable(launch_unit_tests tests/launch_unit_tests.cpp) +target_link_libraries(launch_unit_tests PRIVATE bmhlaunch bmh_miniz) +if(MSVC) + target_compile_options(launch_unit_tests PRIVATE /utf-8) +endif() +add_test(NAME launch_unit_tests COMMAND launch_unit_tests) + +add_executable(fixture_table_tests tests/fixture_table_tests.cpp) +target_link_libraries(fixture_table_tests PRIVATE bmhcore) +add_test(NAME fixture_table_unit_tests COMMAND fixture_table_tests) +bmh_add_data_test(NAME fixture_table_data_tests COMMAND fixture_table_tests "${BMH_DATA}") +bmh_add_data_test(NAME english_fixture_table_data_tests DATA_DIR "${BMH_ENGLISH_DATA}" + COMMAND fixture_table_tests "${BMH_ENGLISH_DATA}") + +# Private build paths are inputs to the source-package tool, never shipped in its manifest. +set(package_dependencies "{}") +foreach(dependency IN ITEMS SDL2 miniz lzma_sdk nfd) + string(REPLACE "\\" "/" dependency_path "${${dependency}_SOURCE_DIR}") + if(dependency STREQUAL "SDL2" AND sdl2_SOURCE_DIR) + set(dependency_path "${sdl2_SOURCE_DIR}") + endif() + string(REPLACE "\"" "\\\"" dependency_path "${dependency_path}") + string(JSON package_dependencies SET "${package_dependencies}" "${dependency}" "\"${dependency_path}\"") +endforeach() +file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/package-dependencies.json" CONTENT "${package_dependencies}\n") diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..650af25 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to OpenBMH + +Use [issues](https://github.com/rezmer/openbmh/issues) for reproducible bugs and proposals. For a bug, include the OpenBMH version, platform, game edition, expected behaviour and the smallest sequence of actions that shows the problem. Remove personal paths and account information from diagnostic text. + +Keep proprietary game files out of public submissions: no executables, databases, manuals, extracted text, artwork, recordings or saved games. Prefer synthetic inputs and a short description. If an investigation requires privately owned data, coordinate an appropriate process with the maintainers instead of attaching it publicly. + +## Changes and review + +Keep patches focused on a concrete problem. Describe the resulting behaviour, relevant compatibility decisions and validation. Discuss architecture changes, balance changes and substantial new features before investing in a large patch. + +- Use C++20 and the conventions of the surrounding code; write new comments in English. +- Keep gameplay in `src/game`, format handling in `src/formats` and shared session transactions in `src/app`. Frontends translate input and display projections. +- Preserve explicit integer widths, signedness, deterministic random consumption and save compatibility. +- Treat malformed input, stale revisions and unsupported modes explicitly. Do not silently substitute guessed gameplay. +- Mark intentional differences with `OpenBMH deviates from the original:` and explain them in [compatibility documentation](docs/COMPATIBILITY.md). +- Use semantic names for concepts. File offsets and compatibility layout constants belong with format documentation; implementation notes should explain the operation rather than cite disassembly labels. + +## Validation + +Follow [BUILDING.md](docs/BUILDING.md), build the affected targets and run the appropriate CTest subset. Prefer tests with synthetic data that can run from a clean checkout. Tests needing a player's game installation must be conditional on `BMH_DATA`; unavailable private fixtures must not become public dependencies. State which checks ran and their limits. A build on one operating system does not establish native behaviour on another. + +For UI changes, exercise input and state transitions as well as rendering. For session actions, cover rejected/stale input and rollback where those risks are relevant. Avoid making tests restate an implementation without checking behaviour. + +## Licensing + +Contributions to OpenBMH's own code and documentation are under **GPL-3.0-only**. Submit only work you have the right to contribute. Keep existing third-party copyright and license notices intact; vendored code retains its upstream license. Do not add proprietary resources to tests or examples. See [LICENSE](LICENSE) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..103c394 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# OpenBMH + +A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* engine. + +OpenBMH is a standalone C++20 engine with an SDL2 interface for *Bundesliga Manager Hattrick* (1994/95) and its English edition, *Football Limited*. The project develops a playable reconstruction alongside a platform for new rules, content and interfaces. Keeping the familiar game enjoyable and making it easier to extend are equally important goals. + +The engine reads a game installation supplied by the player. Game data, artwork, music, manuals and the original executable are not distributed with OpenBMH. Its aim is recognisable behaviour and plausible results; documented compatibility decisions and safety fixes take precedence over reproducing every original fault. + +This is an independent community project, with no affiliation with or endorsement by the original rights holders, the DFL or the Bundesliga. It is an engine implementation, not an official source release or a remaster. + +## Get started + +Check the [releases page](https://github.com/rezmer/openbmh/releases) for available packages and their platform notes. A Windows package uses the name `OpenBMH--windows-x64.zip`. Availability and native validation are stated for each release; source build instructions do not establish platform support on their own. + +1. Have your own supported game installation available. +2. Extract the OpenBMH package into a separate directory, or alongside the game files. +3. Start `openbmh_play` (`openbmh_play.exe` on Windows). Select the game directory or executable when prompted. A ZIP or 7z containing one game installation can also be selected. + +From a terminal: + +```sh +openbmh_play --data "path/to/game" --save-directory "path/to/saves" +openbmh_cli --console --data "path/to/game" --saves "path/to/saves" +``` + +Use a writable save directory and keep backups of existing games. German editions are the primary compatibility target. **Football Limited / English data support is experimental**; original V2.20 save import and some edition-specific behaviour remain limited. See the [0.1 release notes](docs/release/0.1/RELEASE_NOTES.md). + +## Features and direction + +The graphical client and console share career management, matches, transfers, contracts, finances, training, stadium management and save handling. The console supports command batches, structured views and multiple manager clients. Audio is decoded from the user's installation where supported. + +Version 0.1 establishes the playable engine and development interfaces. Later milestones introduce an open data format and typed model, configurable rules, a scalable interface and independently distributable content. These are goals rather than delivery dates; the [roadmap](docs/ROADMAP.md) describes their dependencies. + +## Build from source + +The following recipes target v0.1.0. They require Git, CMake 3.24 or newer and a C++20 compiler. The first configure fetches pinned open-source dependencies. Native build and package results are documented for each release; these instructions do not claim an untested platform result. + +Clone the public repository, then run the commands for your system: + +```sh +git clone https://github.com/rezmer/openbmh.git +cd openbmh +``` + +### Windows + +Install Visual Studio 2022 or its Build Tools with **Desktop development with C++**, a Windows SDK and CMake. From Developer PowerShell, using the Visual Studio generator: + +```powershell +cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 +cmake --build build-windows --config Release +ctest --test-dir build-windows -C Release --output-on-failure +.\build-windows\Release\openbmh_play.exe --data "path/to/game" --save-directory "path/to/saves" +``` + +### Linux + +On Debian or Ubuntu, install the compiler and development libraries. This example uses the default GTK3 file dialog backend: + +```sh +sudo apt install build-essential git cmake ninja-build pkg-config libgtk-3-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev libasound2-dev libpulse-dev libgl1-mesa-dev libudev-dev +cmake -S . -B build-linux -G Ninja -DCMAKE_BUILD_TYPE=Release +cmake --build build-linux +ctest --test-dir build-linux --output-on-failure +./build-linux/openbmh_play --data "path/to/game" --save-directory "path/to/saves" +``` + +Use a newer CMake if your distribution ships a version older than 3.24. A Linux binary can still require system libraries such as GTK3; a ZIP is not a guarantee of portability across distributions. + +### macOS + +Apple's Command Line Tools supply the compiler and SDK; full Xcode is not required. Install CMake and Ninja separately, for example with Homebrew. On Apple Silicon: + +```sh +xcode-select --install +brew install cmake ninja +cmake -S . -B build-macos -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 +cmake --build build-macos +ctest --test-dir build-macos --output-on-failure +./build-macos/openbmh_play --data "path/to/game" --save-directory "path/to/saves" +``` + +On Intel Macs omit the arm64 setting or select `x86_64`. These commands build terminal executables; they do not create a signed application bundle. + +Game-data tests are optional: add `-DBMH_DATA="path/to/game"` when configuring to supply your own installation. The repository includes no original test data. See [BUILDING](docs/BUILDING.md) for test skips, system SDL2 and packaging details. + +## Documentation + +- [Build from source](docs/BUILDING.md) and [platform notes](docs/BUILD_PLATFORMS.md) +- [Architecture](docs/architecture.md), [file formats](docs/formats/README.md) and [random generators](docs/RNG.md) +- [Console reference](docs/CLI_CONCEPT/README.md), [structured protocol](docs/protocol.md) and [client/agent introduction](docs/CONSOLE_CLIENTS.md) +- [Compatibility decisions](docs/COMPATIBILITY.md) + +## Contribute + +Reports with reproducible steps, documentation corrections and focused patches are welcome. Discuss larger design changes in an issue before implementing them. [CONTRIBUTING.md](CONTRIBUTING.md) explains the review and testing conventions. Do not upload original game files, screenshots, recordings, copied text databases or saved games to public issues or pull requests. + +## How the project was developed + +The implementation grew from study of file formats and behaviour of a legally obtained game installation. The public repository contains independently written implementation and format documentation. It does not contain the proprietary implementation or its extracted resources. + +## License and thanks + +OpenBMH's own code and documentation are licensed under **GNU GPL version 3 only**, SPDX **GPL-3.0-only**. [LICENSE](LICENSE) contains the unchanged GPLv3 text; the example wording in its appendix does not change this project's version choice. Game content has separate ownership and is not covered by this license. + +Release source is identified by the matching version tag: [v0.1.0](https://github.com/rezmer/openbmh/tree/v0.1.0) for this version. Binary releases must accompany or offer the corresponding source and build/relinking materials required by the applicable licenses. The tag identifies application source; it does not replace required materials for linked third-party components. + +Bundled components retain their own licenses, including Nuked OPL3 under LGPL-2.1-or-later. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [ACKNOWLEDGEMENTS.md](ACKNOWLEDGEMENTS.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..6014a32 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,21 @@ +# Third-party notices + +OpenBMH's own code and documentation use GPL-3.0-only. This does not replace the licenses of the components below. Their upstream copyright and permission notices remain in the source and in [docs/licenses](docs/licenses/README.md). The original game's executable, data, graphics, text and audio are supplied separately by the player and are not licensed or distributed by this project. + +| Component | Version used by the build | License | Included notice | +|---|---|---|---| +| [SDL2](https://github.com/libsdl-org/SDL/tree/release-2.32.10) | 2.32.10, or an explicitly selected system SDL2 | zlib license | [SDL2.txt](docs/licenses/SDL2.txt) | +| SDL2 HIDAPI code | Included with SDL2 | BSD-3-Clause option; upstream also offers GPL-3.0 and its original license | [license options](docs/licenses/SDL2-HIDAPI-options.txt), [BSD text](docs/licenses/SDL2-HIDAPI-BSD.txt), [original text](docs/licenses/SDL2-HIDAPI-original.txt) | +| SDL2 yuv2rgb code | Included with SDL2 | BSD-3-Clause | [SDL2-yuv2rgb.txt](docs/licenses/SDL2-yuv2rgb.txt) | +| [miniz](https://github.com/richgel999/miniz/releases/tag/3.0.2) | 3.0.2 amalgamation | MIT; embedded public-domain notices remain in its source | [miniz.txt](docs/licenses/miniz.txt), [source notices](docs/licenses/miniz-source-notices.txt) | +| [LZMA SDK decoder files](https://github.com/ip7z/7zip/tree/24.09/C) | Selected C files from 7-Zip 24.09 | Public domain, as marked in the selected files | [LZMA-SDK.txt](docs/licenses/LZMA-SDK.txt) | +| [nativefiledialog-extended](https://github.com/btzy/nativefiledialog-extended/tree/v1.2.1) | 1.2.1 | zlib license | [nativefiledialog-extended.txt](docs/licenses/nativefiledialog-extended.txt) | +| [Nuked OPL3](https://github.com/nukeykt/Nuked-OPL3/tree/765ec962e473aeb767e4cba74ffdc8f588ffbfe8) | Commit `765ec962e473aeb767e4cba74ffdc8f588ffbfe8` | LGPL-2.1-or-later | [LGPL-2.1.txt](docs/licenses/LGPL-2.1.txt), [copyright and source notice](docs/licenses/Nuked-OPL3-notices.txt) | + +The miniz implementation provides a zlib-compatible API; it is not the zlib library. OpenBMH does not directly link a separate zlib dependency. SDL2 and nativefiledialog-extended use the **zlib license**, which is distinct from using zlib code. A system-library build or distributor's package can have additional runtime dependencies; its notices must match the libraries actually included. + +Only the public-domain C decoding subset is taken from the 7-Zip source package. This statement does not describe all of 7-Zip: other parts of that upstream project have different licenses and are not included here. + +Nuked OPL3 is linked into the audio implementation. A binary distribution must retain its LGPL notices and provide the corresponding library source and the materials needed to exercise the LGPL's modification and relinking rights. For a source release, the vendored implementation and its build files are included. Binary distributors must also satisfy the source-distribution obligations of OpenBMH's GPL license. Merely copying license texts does not replace these obligations. + +Native platform libraries, such as GTK on Linux, may be required at runtime even when they are not bundled. Compiler runtime files included with a binary package retain their own terms. See the package's file list and platform notes for the actual distribution. diff --git a/docs/BUILDING.md b/docs/BUILDING.md new file mode 100644 index 0000000..2594a14 --- /dev/null +++ b/docs/BUILDING.md @@ -0,0 +1,52 @@ +# Building OpenBMH + +Requirements: a C++20 compiler, CMake 3.24 or newer, Git and a supported build tool such as Ninja. The CMake project fetches pinned SDL2, miniz, 7-Zip C decoder and nativefiledialog-extended sources. Network access is needed on the first configure unless these dependencies are supplied locally. Nuked OPL3 is included in the source tree. + +```sh +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release +cmake --build build +ctest --test-dir build --output-on-failure +``` + +The public checkout does not include game data. Tests that require a game installation are conditional; configure with `-DBMH_DATA="path/to/game"` to make locally available data eligible. Private saved-game fixtures are not supplied by the project. Read the test output to distinguish executed and skipped checks. + +Main programs are `openbmh_play` (graphical game) and `openbmh_cli` (console and protocol). Single-configuration generators put them in the build directory; multi-configuration generators normally add a configuration directory. On Windows they have the `.exe` suffix. + +## Windows + +Use an MSVC environment with C++20 support and its Windows SDK, or another toolchain explicitly supported by the project's build configuration. From a Developer PowerShell with CMake and Ninja available: + +```powershell +cmake -S . -B build-windows -G Ninja -DCMAKE_BUILD_TYPE=Release +cmake --build build-windows +ctest --test-dir build-windows --output-on-failure +``` + +With a Visual Studio generator, choose one actually provided by your installed CMake and add `--config Release` / `-C Release` to build and test commands. Native file dialogs and runtime-library deployment require the platform SDK and package-specific checks. + +## Linux + +Install a C++20 compiler, Git, CMake, Ninja, pkg-config and the development packages required by SDL2 and the dialog backend. The default Linux dialog backend uses GTK3. For example, Debian-family development packages include `build-essential`, `cmake`, `ninja-build`, `git`, `pkg-config` and `libgtk-3-dev`; SDL2's selected video/audio backends may need additional development libraries. + +The common commands above build the bundled SDL2. To use an installed SDL2 CMake package instead, configure with `-DBMH_USE_SYSTEM_SDL2=ON`. Its version and backend configuration then come from the installed package. + +## macOS + +Apple's **Command Line Tools are sufficient** for the compiler and SDK; the full Xcode application is not a prerequisite for a command-line build. Install the tools with `xcode-select --install`, and install CMake and Ninja separately. On an Apple Silicon machine: + +```sh +cmake -S . -B build-macos -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 +cmake --build build-macos +ctest --test-dir build-macos --output-on-failure +``` + +Use native toolchain/dependency architectures consistently. A terminal executable and a Finder-launchable, signed `.app` package are different deliverables. The commands describe the build procedure, not a claim that a particular Windows or macOS binary has passed native acceptance. + +## Run with your data + +```sh +build/openbmh_play --data "path/to/game" --save-directory "path/to/saves" +build/openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --seed 1 +``` + +For redistribution, include [LICENSE](../LICENSE), [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md), the full texts in [licenses/](licenses/README.md), and the corresponding source and build information required by the applicable licenses. Inspect the actual libraries in each platform package; static SDL2 alone does not establish that every dependency is static. diff --git a/docs/BUILD_PLATFORMS.md b/docs/BUILD_PLATFORMS.md new file mode 100644 index 0000000..6fcc3be --- /dev/null +++ b/docs/BUILD_PLATFORMS.md @@ -0,0 +1,9 @@ +# Platform notes + +[BUILDING.md](BUILDING.md) contains Windows, Linux and macOS build commands. C++20, CMake and platform SDKs are required. macOS command-line builds need Apple's Command Line Tools, not the complete Xcode application. + +A successful cross-build, source review or Linux run does not establish a native Windows/macOS result. Release notes must state which packaged platforms were actually validated. Packaging is separate from compilation: check runtime dependencies, writable save directories, file dialogs, Unicode paths, display scaling and audio on the target platform. + +On macOS an unsigned terminal executable does not automatically provide Finder integration, an application bundle or notarisation. On Windows a statically built SDL2 does not remove the need to check compiler runtimes. System-library builds inherit the versions and backend choices of their installed dependencies. + +All packages require the user's game data. No platform package may include original executables or extracted resources. See [third-party notices](../THIRD_PARTY_NOTICES.md) for distribution material. diff --git a/docs/CLI_CONCEPT/01-grundlagen.md b/docs/CLI_CONCEPT/01-grundlagen.md new file mode 100644 index 0000000..7be1c35 --- /dev/null +++ b/docs/CLI_CONCEPT/01-grundlagen.md @@ -0,0 +1,53 @@ +# Console syntax and responses + +The console runs command blocks against one career session. Start it with `openbmh_cli --console --data "path/to/game" --saves "path/to/saves"`. This language is distinct from the narrower JSON request protocol used without `--console`. + +## Input + +Put one command on each line and finish the block with `go.` on a line of its own. `clear.` discards an unexecuted block. Blank lines and lines beginning with `//` are ignored. Commands execute in order; a failure stops the remaining commands. Earlier successful actions remain committed: a block is not one transaction. + +Command syntax is `[@player] Name(argument, name=value)`. The player prefix uses seats 1–4. Names ignore case, dots and underscores. Arguments can be positional, followed by named arguments; quote strings containing spaces, commas or punctuation. Escape a literal quote or backslash with a backslash. Integer values can use underscores as separators. Boolean values include `true`/`false` and `on`/`off`. Parameter types and accepted enum values are checked before an action is dispatched. + +Use `id:n` for a player ID where accepted, `slot:n` for a current squad position, and `club:n` for a master club reference. Rows and slots are temporary references. Player IDs, master club indices, runtime team IDs and name-pool identity keys are different domains. Obtain the appropriate reference from the current list or state view. + +## Responses + +Text lines carry a leading class: `#` status, `>` command option, `|` table row, `+` success, `!` error, `?` question, `i` information, `~` match event and `c` chat. Status headers are emitted when needed; absence of a new header does not imply that the window or match has ended. Read the final status and all intervening question/error lines. + +`--json` in console mode emits structured line records with `class`, `window`, `player`, `text` and optional `data`. This is the structured representation of console output, not the standalone request protocol. Prefer it over parsing translated prose. Legacy game strings can still expose encoding limitations; retain raw bytes if reporting a decoder problem. + +## Questions and ownership + +A question has an ID, a recipient and listed options. Answer with `Answer(id, option)`, using the actual ID and option from the response. Only its owner can decide it. A question can occur during another manager's turn or while advancing the shared match clock. `GoBack` can select a question's default or cancel an editor; it is not a harmless substitute for an explicit answer. + +`ListOptions` and `Help` describe the current build. Common failures include `E_BAD_ARGUMENT`, `E_NOT_IN_WINDOW`, `E_NOT_YOUR_TURN`, `E_PENDING_QUESTION`, `E_RULE`, `E_MODE_LOCKED`, `E_PHASE_LOCKED`, `E_IO` and `E_ENGINE_GAP`. A recognised name does not guarantee that every mode or path is implemented. Preserve an unexpected error and inspect state before deciding whether to retry. + +The [client introduction](../CONSOLE_CLIENTS.md) covers transport, turn ownership, safe batching and replay. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `*` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListOptions` | [command:string \| all] | commands possible here; ListOptions(all) also shows locked ones | +| `GoBack` | – | right mouse button: one level back, otherwise nothing | +| `Chat` | [to:int], text:string | message to all, or to one player (0 = only the log) | +| `ChatLog` | [count:int=20] | the last chat messages | +| `Answer` | id:int, option:enum | answer the open question | +| `Status` | – | window, player and a short overview | +| `State` | view:enum(Desk,Table,Lineup,Mailbox,Bank,Market,Advertising,Contracts,Stadium,Toto,Training,Camp) | the full projection of a view as structured (JSON) data | +| `Advice` | – | situations that need a decision now: form, squad, contracts, advertising, money | +| `Scoreboard` | – | all human managers: league, place, points, balance, strength of the best eleven | +| `Help` | [command:string] | command reference (all windows) | +| `Quit` | [force:bool=false] | end the session (asks first during a game) | +| `HarnessState` | [path:string] | Harness State. See current Help for behaviour and bounds. | +| `HarnessHash` | – | Harness Hash. See current Help for behaviour and bounds. | +| `HarnessInvariants` | – | Harness Invariants. See current Help for behaviour and bounds. | +| `HarnessAutopilot` | player:int(1..4), policy:enum(Default,Saver,Spender,Random,Off) | Harness Autopilot. See current Help for behaviour and bounds. | +| `HarnessFast` | matchdays:int, [until:enum(Matchday,Season,GameEnd)] | Harness Fast. See current Help for behaviour and bounds. | +| `HarnessCoverage` | – | Harness Coverage. See current Help for behaviour and bounds. | +| `HarnessSeed` | – | Harness Seed. See current Help for behaviour and bounds. | +| `HarnessExpect` | text:string | Harness Expect. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/02-fenster.md b/docs/CLI_CONCEPT/02-fenster.md new file mode 100644 index 0000000..0d29051 --- /dev/null +++ b/docs/CLI_CONCEPT/02-fenster.md @@ -0,0 +1,67 @@ +# Windows and navigation + +A console window is a session context, not a separate game process. `Open(window)` enters an available window from the desktop. Nested editors and information cards return to their parent through `GoBack`. Pending questions and staged engine operations can restrict navigation. + +A dot in a window name denotes a specialised context, for example `Transfer.Negotiate`. It does not imply that a client can open it directly without selecting a player. Global commands use `*` in the catalogue. `ListOptions` is the reliable guide to the current context; an operation allowed on the desktop may be forbidden during a live match or another manager's turn. + +The following identifiers occur in the command catalogue. Some are reserved or only available in particular modes. They are API names, not a guarantee of complete support for every original screen. + +| Window | Reference | +|---|---| +| `NewGame` | [Commands](03-start.md) | +| `NewGame.Select` | [Commands](03-start.md) | +| `NewGame.Select.Confirm` | [Commands](03-start.md) | +| `NewPlayer` | [Commands](03-start.md) | +| `Desktop` | [Commands](04-schreibtisch.md) | +| `Mailbox` | [Commands](04-schreibtisch.md) | +| `Desktop.Drawer` | [Commands](04-schreibtisch.md) | +| `Calendar` | [Commands](04-schreibtisch.md) | +| `LoadGame` | [Commands](04-schreibtisch.md) | +| `SaveGame` | [Commands](04-schreibtisch.md) | +| `NewGame.LoadGame` | [Commands](04-schreibtisch.md) | +| `LeagueTable` | [Commands](05-information.md) | +| `Fixtures` | [Commands](05-information.md) | +| `Strengths` | [Commands](05-information.md) | +| `TeamInfo` | [Commands](05-information.md) | +| `Achievements` | [Commands](05-information.md) | +| `OtherGames` | [Commands](05-information.md) | +| `IndoorTable` | [Commands](05-information.md) | +| `TopScorers` | [Commands](05-information.md) | +| `FairPlay` | [Commands](05-information.md) | +| `HighScore` | [Commands](05-information.md) | +| `Statistics` | [Commands](05-information.md) | +| `Lineup` | [Commands](06-verein.md) | +| `Lineup.Pitch` | [Commands](06-verein.md) | +| `Lineup.Order` | [Commands](06-verein.md) | +| `Lineup.Marking` | [Commands](06-verein.md) | +| `Lineup.SetPieces` | [Commands](06-verein.md) | +| `PlayerCard` | [Commands](06-verein.md) | +| `PlayerCard.Statistics` | [Commands](06-verein.md) | +| `Tactics` | [Commands](06-verein.md) | +| `Training` | [Commands](06-verein.md) | +| `TrainingCamp` | [Commands](06-verein.md) | +| `Transfer` | [Commands](06-verein.md) | +| `Transfer.Negotiate` | [Commands](06-verein.md) | +| `Transfer.Search` | [Commands](06-verein.md) | +| `Transfer.Poach` | [Commands](06-verein.md) | +| `Transfer.Offers` | [Commands](06-verein.md) | +| `Contracts` | [Commands](06-verein.md) | +| `Contracts.Negotiate` | [Commands](06-verein.md) | +| `Bank` | [Commands](06-verein.md) | +| `Bank.Account` | [Commands](06-verein.md) | +| `Bank.Savings` | [Commands](06-verein.md) | +| `Bank.Shares` | [Commands](06-verein.md) | +| `Bank.RealEstate` | [Commands](06-verein.md) | +| `Bank.Credit` | [Commands](06-verein.md) | +| `Stadium` | [Commands](06-verein.md) | +| `Stadium.Periphery` | [Commands](06-verein.md) | +| `Stadium.Data` | [Commands](06-verein.md) | +| `Advertising` | [Commands](06-verein.md) | +| `Environment` | [Commands](06-verein.md) | +| `Balance` | [Commands](06-verein.md) | +| `Toto` | [Commands](06-verein.md) | +| `Friendlies` | [Commands](06-verein.md) | +| `Reschedule` | [Commands](06-verein.md) | +| `Match` | [Commands](07-spieltag.md) | +| `GameEnd` | [Commands](07-spieltag.md) | +| `Settings` | [Commands](08-einstellungen.md) | diff --git a/docs/CLI_CONCEPT/03-start.md b/docs/CLI_CONCEPT/03-start.md new file mode 100644 index 0000000..ed5a2df --- /dev/null +++ b/docs/CLI_CONCEPT/03-start.md @@ -0,0 +1,57 @@ +# Starting or loading a career + +Startup moves from `NewGame` to `NewGame.Select`, then asks each selected manager to confirm their choices. Use `ShowOptions` and `ListTeams` to obtain the current values and master club references. Do not assume that the same numeric club identifies the same content in German and English installations. + +`NewGame` sets the duration, difficulty, manager count, mode and league/world choices. Team selection records a manager name, club, starting league, strength band and portrait. `Confirm` opens a question; answer its actual ID explicitly. With several managers, finish each selection before the first desktop appears. + +`OpenLoadBrowser` / `LoadGame` enter normal save loading. Paths are resolved against the configured save browser. The loader validates format/version compatibility; renaming an unsupported save or altering its header does not make it supported. Adding a manager later uses `NewPlayer` and remains subject to the running career's rules. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `NewGame` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowOptions` | – | show the options with their current values | +| `NewGame` | duration:int(1..5), difficulty:int(1..10), managers:int(1..4), mode:int(1..3), league:bool, world:bool | set all options and continue (= right mouse) | +| `SetDuration` | duration:int(1..5) | 1-4 seasons, 5 = endless | +| `SetDifficulty` | difficulty:int(1..10) | number of balls | +| `SetManagers` | managers:int(1..4) | human managers | +| `SetMode` | mode:int(1..3) | range of desk functions | +| `SetLeagueMode` | on:bool | league mode on/off | +| `SetWorldMode` | on:bool | world cup mode on/off | +| `OpenLoadBrowser` | – | open the load browser | +| `LoadGame` | filename:string | load a saved game | + +### `NewGame.Select` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListTeams` | [league:int \| tab:enum] | clubs of a picker tab (Bundesliga ... AdditionalB) | +| `ListPortraits` | – | the twelve portraits and who took them | +| `ListStrengths` | – | the three club strengths | +| `ShowSelection` | – | the choices of this player | +| `SetManagerName` | name:string(1..20) | the manager's name (1-20 characters) | +| `SetClub` | club:Club | the club: club: from ListTeams or "name" | +| `SetStartLeague` | league:enum(Bundesliga,SecondLeague,RegionalA,RegionalB,Oberliga) | the league to start in | +| `SetStrength` | strength:enum(Upper,Middle,Lower) | the club's strength | +| `SetPortrait` | portrait:int(0..11) | the manager's portrait | +| `SelectTeam` | managerName:string, club:Club, startLeague:enum, strength:enum, portrait:int | set all five and ask for confirmation | +| `Confirm` | – | show the summary and ask "all details correct?" | + +### `NewGame.Select.Confirm` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSummary` | – | the choices of this player | + +### `NewPlayer` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowNewPlayerOptions` | – | Show New Player Options. See current Help for behaviour and bounds. | +| `SetManagers` | managers:int(current..4) | Set Managers. See current Help for behaviour and bounds. | +| `SetDifficulty` | difficulty:int(1..10) | Set Difficulty. See current Help for behaviour and bounds. | +| `Confirm` | – | Confirm. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/04-schreibtisch.md b/docs/CLI_CONCEPT/04-schreibtisch.md new file mode 100644 index 0000000..5e21c8b --- /dev/null +++ b/docs/CLI_CONCEPT/04-schreibtisch.md @@ -0,0 +1,77 @@ +# Desktop, calendar and saved games + +`Desktop` is the management turn. Read `ShowDesk`, `ShowDate`, `ShowFinance`, `ShowOpponent` or `State(Desk)` before making decisions. `Open(window)` navigates to an available management window. Restrictions depend on game mode, manager role, phase and pending questions. + +`Kickoff` hands control to the next manager or starts calendar processing once all required managers have finished. It can produce information, questions, a match window, a season boundary or the next desktop. Put it last in a batch and inspect its complete response. + +`Calendar` reads the current schedule. `Mailbox` lists messages and supports normal keep/delete actions. Message rows are snapshot references; refresh them after a mutation. `LoadGame`, `SaveGame` and `NewGame.LoadGame` share browser commands. Select a file and use the normal `Save` action; resolve overwrite/delete questions explicitly. Save only a committed state accepted by the session. + +Desktop layout commands are listed for discoverability. Some legacy layout operations can return `E_ENGINE_GAP`; appearance in this index is not a claim that every editor function is available. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `Desktop` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowDesk` | – | all displays of the desk | +| `ShowDate` | – | date, weekday, season day, league round | +| `ShowFinance` | – | balance, savings, ticket price | +| `ShowFanStanding` | – | standing with the fans | +| `ShowLamps` | – | the ten warning lamps | +| `ShowLastGames` | – | the last six games | +| `ShowOpponent` | – | the next game and opponent | +| `ShowPositionCurves` | [own\|opponent] | table positions per matchday | +| `ShowAutomation` | – | the five automations | +| `Open` | window:enum \| menu:int | open a window (click on its icon); see the lines below | +| `Key` | letter:enum(A..Z) | a key on the desk (G = Kickoff) | +| `SetTicketPrice` | price:int(8..25) | the ticket price (price scale) | +| `SetAutomation` | feature:enum(Lineup,Substitution,Tactics,Marking,Training), on:bool | switch one of the five automations (Lineup: a saved formation 1-8) | +| `Kickoff` | – | hand over to the next player or start the day | +| `OpenMailbox` | – | open the mailbox (Kicker) | +| `OpenDrawer` | – | open the menu bar | +| `PullPlug` | – | the plug: quit after a question | + +### `Mailbox` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListMessages` | – | the messages of this manager (msg numbers for Keep/Delete) | +| `KeepMessage` | msg:int | keep a message / let it go (at most five) | +| `DeleteMessage` | msg:int | throw a message away | + +### `Desktop.Drawer` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListIcons` | – | List Icons. See current Help for behaviour and bounds. | +| `MoveIcon` | window:enum, x:int, y:int | Move Icon. See current Help for behaviour and bounds. | +| `OpenFolder` | folder:int(1..3) | Open Folder. See current Help for behaviour and bounds. | +| `OpenTrash` | – | Open Trash. See current Help for behaviour and bounds. | +| `StoreIcon` | window:enum, folder:int(1..3) | Store Icon. See current Help for behaviour and bounds. | +| `RetrieveIcon` | window:enum | Retrieve Icon. See current Help for behaviour and bounds. | +| `SaveMenuDesign` | file:string | Save Menu Design. See current Help for behaviour and bounds. | +| `LoadMenuDesign` | file:string | Load Menu Design. See current Help for behaviour and bounds. | +| `SetTransparent` | window:enum, on:bool | Set Transparent. See current Help for behaviour and bounds. | +| `CloseDrawer` | – | Close Drawer. See current Help for behaviour and bounds. | + +### `Calendar` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowCalendar` | [month:int(1..12)] | Show Calendar. See current Help for behaviour and bounds. | + +### `LoadGame|SaveGame|NewGame.LoadGame` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListFiles` | – | List Files. See current Help for behaviour and bounds. | +| `ChangeDirectory` | name:string | Change Directory. See current Help for behaviour and bounds. | +| `ParentDirectory` | – | Parent Directory. See current Help for behaviour and bounds. | +| `SelectFile` | name:string | Select File. See current Help for behaviour and bounds. | +| `FileInfo` | name:string | File Info. See current Help for behaviour and bounds. | +| `Load` | [name:string] | Load. See current Help for behaviour and bounds. | +| `Save` | [name:string], [overwrite:bool=false] | Save. See current Help for behaviour and bounds. | +| `DeleteFile` | name:string | Delete File. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/05-information.md b/docs/CLI_CONCEPT/05-information.md new file mode 100644 index 0000000..6c535f0 --- /dev/null +++ b/docs/CLI_CONCEPT/05-information.md @@ -0,0 +1,139 @@ +# Tables and information windows + +Information windows expose league tables, fixtures, strengths, player cards, honours, other competitions, calendars and statistics. Choose a league or competition using the current view's options; avoid assuming that all editions have the same names or tournament structure. + +A club's master identity and current runtime position differ. Use the identity returned for the intended action rather than reusing a row from another table. Sorting, range and home/away filters affect the current view; they do not rewrite the competition's saved result history. + +`OpenPlayer` and `OpenTeamInfo` can create nested windows. `GoBack` closes the current level, subject to pending questions. Read-only reports can still be unavailable outside their supported mode or phase. Use `State(Table)` when a client needs an owned structured league table. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `LeagueTable` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowTable` | [league:int(0..8)] | the table (without league: the one shown) | +| `SetLeague` | league:int(0..8) | show another league | +| `ToggleEurope` | – | Toggle Europe. See current Help for behaviour and bounds. | +| `SetView` | view:enum(Total,Home,Away) | Set View. See current Help for behaviour and bounds. | +| `SetCriteria` | points:bool, goals:bool, goalsAgainst:bool | Set Criteria. See current Help for behaviour and bounds. | +| `SetRange` | all \| from:int, to:int | Set Range. See current Help for behaviour and bounds. | +| `SetPointsMode` | mode:enum(Normal,English) | Set Points Mode. See current Help for behaviour and bounds. | +| `ComputerTip` | – | Computer Tip. See current Help for behaviour and bounds. | +| `OpenFixtures` | – | the fixtures of this league | +| `OpenStrengths` | – | Open Strengths. See current Help for behaviour and bounds. | +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | + +### `Fixtures` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowFixtures` | [league:int, matchday:int] | the page shown (optionally another league / matchday first) | +| `SetLeague` | league:int(0..8) | another league | +| `SetMatchday` | matchday:int | go to a matchday | +| `NextMatchday` | – | the next matchday (arrow) | +| `PreviousMatchday` | – | the previous matchday (arrow) | +| `FindGame` | home:Club, away:Club | Find Game. See current Help for behaviour and bounds. | +| `GamesOf` | club:Club | Games Of. See current Help for behaviour and bounds. | +| `Page` | n:int | Page. See current Help for behaviour and bounds. | +| `ShowPostponed` | – | the postponed games | +| `ComputerTip` | – | the computer's forecast for this page | +| `OpenTable` | – | the league table | +| `OpenStrengths` | – | Open Strengths. See current Help for behaviour and bounds. | +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | + +### `Strengths` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowStrengths` | [league:int] | Show Strengths. See current Help for behaviour and bounds. | +| `SetLeague` | league:int(0..8) | Set League. See current Help for behaviour and bounds. | +| `SetCriteria` | fitness:bool, skill:bool, form:bool, morale:bool | Set Criteria. See current Help for behaviour and bounds. | +| `SetLines` | goalkeeper:bool, defence:bool, midfield:bool, attack:bool | Set Lines. See current Help for behaviour and bounds. | +| `SetZeroValue` | – | Set Zero Value. See current Help for behaviour and bounds. | +| `SortByAge` | on:bool | Sort By Age. See current Help for behaviour and bounds. | +| `SetPlayerFilter` | filter:enum(All,OnPitchOnly) | Set Player Filter. See current Help for behaviour and bounds. | +| `OpenFixtures` | – | Open Fixtures. See current Help for behaviour and bounds. | +| `OpenTable` | – | Open Table. See current Help for behaviour and bounds. | +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | + +### `TeamInfo` + +| Command | Parameters | Purpose | +|---|---|---| +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | +| `ShowTeamSquad` | [view:enum(A,B)] | the club's squad | +| `ShowTeamStatistics` | [scope:enum(Home,Away,Total)] | Show Team Statistics. See current Help for behaviour and bounds. | +| `SetBroadcast` | club:Club, mode:enum(Dots,Headphones,Camera) | Set Broadcast. See current Help for behaviour and bounds. | +| `ShowPlayer` | player:Player | a player of this club | +| `CloseTeamInfo` | – | back to where it was opened | + +### `Achievements` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowAchievements` | – | Show Achievements. See current Help for behaviour and bounds. | +| `ShowCompetitionSeason` | competition:enum(League,DfbCup,European) | Show Competition Season. See current Help for behaviour and bounds. | + +### `OtherGames` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowCompetition` | [competition:enum, round:enum, matchday:int] | Show Competition. See current Help for behaviour and bounds. | +| `SetCompetition` | competition:enum(DfbCup,UefaCup,ChampionsLeague,CupWinners,World,SuperCup) | Set Competition. See current Help for behaviour and bounds. | +| `SetRound` | round:string | Set Round. See current Help for behaviour and bounds. | +| `NextMatchday` | – | Next Matchday. See current Help for behaviour and bounds. | +| `PreviousMatchday` | – | Previous Matchday. See current Help for behaviour and bounds. | +| `CompleteView` | – | Complete View. See current Help for behaviour and bounds. | +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | + +### `IndoorTable` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowIndoorTable` | – | Show Indoor Table. See current Help for behaviour and bounds. | +| `OpenTeamInfo` | club:Club | Open Team Info. See current Help for behaviour and bounds. | + +### `TopScorers` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowScorers` | [list:enum(Goals,Assists,Score), scope:enum(League,Managers)] | the best ten: goals, assists or both; whole league or managers' clubs | +| `SetList` | list:enum(Goals,Assists,Score) | TORSCHÜTZEN / VORLAGEN / SCORER | +| `SetScope` | scope:enum(League,Managers) | GESAMTE LIGA / NUR MANAGER | + +### `FairPlay` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowFairPlay` | – | Show Fair Play. See current Help for behaviour and bounds. | + +### `HighScore` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowHighScore` | – | the high score list and your current score | + +### `Statistics` + +| Command | Parameters | Purpose | +|---|---|---| +| `OpenView` | view:enum(Opportunities,AllTimeTable,SeriesRecords,Transfers,WorldCup,Winners,Charts,Finances,MinuteStats) | Open View. See current Help for behaviour and bounds. | +| `ShowOpportunities` | [mode:enum(A,B,C,D)] | Show Opportunities. See current Help for behaviour and bounds. | +| `ShowAllTimeTable` | [country:enum(Bundesliga,France,England,Spain,Italy)], [mode:enum(Absolute,Relative)] | Show All Time Table. See current Help for behaviour and bounds. | +| `ShowSeriesRecords` | – | Show Series Records. See current Help for behaviour and bounds. | +| `ShowTransferHistory` | – | Show Transfer History. See current Help for behaviour and bounds. | +| `ShowWorldCupStats` | [nation:string] | Show World Cup Stats. See current Help for behaviour and bounds. | +| `ShowWinners` | [competition:enum(League,DfbCup,ChampionsLeague,CupWinners,WorldCup,EuroCup,IndoorMasters,SuperCup)] | Show Winners. See current Help for behaviour and bounds. | +| `ShowCharts` | kind:enum(TablePosition,GateIncome,Balance,Strength,AdvertisingIncome,Assets), [mode:enum(Absolute,Relative)] | Show Charts. See current Help for behaviour and bounds. | +| `ShowFinances` | – | Show Finances. See current Help for behaviour and bounds. | +| `ShowMinuteStats` | – | Show Minute Stats. See current Help for behaviour and bounds. | + +### `*` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListLeagues` | – | leagues with number and size | +| `ListClubs` | [league:int] | List Clubs. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/06-verein.md b/docs/CLI_CONCEPT/06-verein.md new file mode 100644 index 0000000..9d40675 --- /dev/null +++ b/docs/CLI_CONCEPT/06-verein.md @@ -0,0 +1,351 @@ +# Club management + +Club windows share the same session actions as the graphical client. Read a projection, choose current identifiers, apply an action and inspect its result before using a stale row or price again. + +## Squad, tactics and training + +`Lineup` lists squad members and positions; use explicit player references for moves and orders. The engine checks availability, formation and substitution rules. `Tactics` changes preparation values, while automation flags can delegate selected decisions. `Training` has types, areas, intensity and focus; opening or initialising a plan is an action distinct from merely reading it. A legal starting eleven takes priority over speculative transfers. + +## Transfers and contracts + +`Transfer` provides market filters, players and purchase/loan actions. `HirePlayer` requests an ordinary loan for a supported duration; free agents must be bought rather than borrowed. `Transfer.Negotiate` holds a staged offer: change fields with `SetOffer` or `SetOfferField`, submit with `SubmitOffer`, or cancel through `GoBack`. The engine applies qualification, squad capacity, wages, fees and acceptance rules; an opened editor is not an accepted purchase. + +A loan expiry can suspend calendar processing for a return question addressed to the borrowing manager. The manager chooses the displayed No or Yes option. Yes opens the normal staged buyback negotiation; cancelling that editor follows the ordinary return path. Only the owning manager can edit or close it. Do not start another calendar operation while a modal question or editor owns the suspended operation. + +`Contracts.Negotiate` is a separate contract editor. Player IDs remain distinct from squad positions and temporary offer rows. Refresh demand and offer views after changes; neither a displayed demand nor a pending offer guarantees final acceptance. + +## Finance and facilities + +`Bank`, `Advertising`, `Stadium`, `Toto` and related subwindows expose normal financial actions. Quotes and offer rows belong to their current projection. Advertising slots can be empty, active or require renewal; reading a general budget does not itself secure a sponsor. Training camps use edition-provided resort tables and the displayed currency conversion. Read the actual quote instead of hardcoding a price from another edition. + +Loans, deposits, shares, facilities and campaigns all have rule and budget checks. A cash balance alone does not establish affordability when wages, credit or a pending obligation also matter. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `Lineup` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSquad` | [view:enum(A,B)] | the squad: values, strength, place | +| `SetSquadView` | view:enum(A,B) | DATEN-A / DATEN-B | +| `SwapPlayers` | first:Player, second:Player | exchange two players' places | +| `OpenPlayer` | player:Player | the player card (PlayerCard) | +| `OpenPitch` | – | the pitch (Lineup.Pitch) | +| `OpenTeamList` | – | Open Team List. See current Help for behaviour and bounds. | +| `ShowForeigners` | – | Show Foreigners. See current Help for behaviour and bounds. | + +### `Lineup.Pitch` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowPitch` | – | the eleven with depth/lane, formations, automatic weights | +| `SetFormation` | slot:int(1..8) | one of the eight formations (1-4 given, 5-8 own); the automatic line-up takes over | +| `SaveFormation` | slot:int(5..8) | save the current positions in an own formation slot (long press) | +| `MovePlayer` | player:Player, depth:int, lane:int | place a starter freely (switches the automatic line-up off) | +| `SwapPitch` | first:Player, second:Player | exchange two players on the pitch / bench | +| `SetAutoWeights` | kind:enum(Position,SideAndRole,Fatigue), value:int(0..3) | an automatic line-up weight (the cup is clicked until the value); then SetFormation again | +| `ShowAutoWeights` | – | the three automatic line-up weights | +| `ScrollList` | direction:enum(Up,Down) | Scroll List. See current Help for behaviour and bounds. | +| `SetSquadView` | view:enum(A,B) | DATEN-A / DATEN-B | +| `OpenTeamList` | – | Open Team List. See current Help for behaviour and bounds. | +| `OpenOrder` | – | ORDER: the instructions of the starters (Lineup.Order) | +| `OpenMarking` | – | Open Marking. See current Help for behaviour and bounds. | +| `ShowZoneCoverage` | – | Show Zone Coverage. See current Help for behaviour and bounds. | +| `OpenSetPieces` | – | Open Set Pieces. See current Help for behaviour and bounds. | +| `ShowPairs` | – | the Hall partners stored on the tactics board | +| `PairPlayers` | first:Player, second:Player, depth:int(0..19), lane:int(0..8) | place the first Hall starter beside the second at the explicit target coordinates | + +### `Lineup.Order` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowOrders` | – | offense, running, commitment, fighting of every starter | +| `SetOrder` | player:Player, aspect:enum(Offense,Run,Commitment,Fighting), value:int | one instruction of a starter (as a click in its bar) | + +### `Lineup.Marking` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowOpponentSquad` | – | Show Opponent Squad. See current Help for behaviour and bounds. | +| `SetMarking` | own:Player, opponent:Player | Set Marking. See current Help for behaviour and bounds. | +| `ClearMarking` | opponent:Player | Clear Marking. See current Help for behaviour and bounds. | + +### `Lineup.SetPieces` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSetPieces` | – | Show Set Pieces. See current Help for behaviour and bounds. | +| `SetSetPieceTaker` | kind:enum(FreeKick,Penalty,Corner), player:Player | Set Set Piece Taker. See current Help for behaviour and bounds. | +| `SetSetPieceAuto` | [kind:enum(FreeKick,Penalty,Corner)] | Set Set Piece Auto. See current Help for behaviour and bounds. | + +### `PlayerCard` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowPlayer` | [player:Player] | the card (another player of the squad by name) | +| `OpenPlayer` | player:Player | another player's card | +| `OpenPlayerStatistics` | – | the development charts (own players) | +| `Negotiate` | – | Negotiate. See current Help for behaviour and bounds. | +| `NationalSquadAdd` | – | National Squad Add. See current Help for behaviour and bounds. | +| `NationalSquadRemove` | – | National Squad Remove. See current Help for behaviour and bounds. | + +### `PlayerCard.Statistics` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowPlayerStatistics` | [chart:enum(Value,Form,Strength,Total), mode:enum(Absolute,Relative)] | a development chart as a series | +| `SetChart` | chart:enum(Value,Form,Strength,Total) | SPIELER-WERT / FORM / STÄRKE / GESAMT | +| `SetMode` | mode:enum(Absolute,Relative) | ABS / REL | +| `BackToPlayerInfo` | – | back to the card | + +### `Tactics` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowTactics` | – | the eight settings with value and maximum | +| `SetTactic` | item:int(0..7), value:int | set a value directly (item 0 ends the assistant's D/O control) | +| `CycleTactic` | item:int(0..6) | a click: value + 1, after the maximum 0 | + +### `Training` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowTraining` | – | types, areas, sums, players, automation | +| `SetTrainingType` | type:enum(TOR,ABW,MIT,STU), balls:int(0..3) | balls of a player type (sum <= 8) | +| `SetTrainingArea` | area:enum(Fitness,Skill,Corner,FreeKick,Tackling,Pass,Shot,Speed,Game), balls:int(0..3) | balls of a training area (F+S <= 4, rest <= 18) | +| `SetPlayerIntensity` | player:Player, intensity:int(1..3) | training intensity of a player | +| `CyclePlayerFocus` | player:Player | the player's focus symbol: next focus | +| `SetTrainingAutomation` | index:int(0..4), on:bool | one automation bit (D p. 109) | +| `InitializeTraining` | – | the original initialization (only when needed) | + +### `TrainingCamp` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListResorts` | – | the eight sports schools with stars and price | +| `ShowCamp` | – | sliders, recuperation, visits | +| `SetCampFocus` | fitness:int(0..15), skill:int(0..15), game:int(0..15) | the three sliders; recuperation follows | +| `BookCamp` | resort:int(0..7) | MACH ICH: book the sports school | + +### `Transfer` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowMarket` | [page:int] | the offered players (20 per page) | +| `SetMarketFilter` | positions:list(TOR,ABW,MIT,STU) \| All | ALLE / TOR / ABW / MIT / STU | +| `SetSquadView` | view:enum(Active,Team) | Set Squad View. See current Help for behaviour and bounds. | +| `SetSquadSheet` | sheet:enum(A,B) | Set Squad Sheet. See current Help for behaviour and bounds. | +| `SetMarketVisible` | on:bool | Set Market Visible. See current Help for behaviour and bounds. | +| `ShowPlayer` | player:Player | Show Player. See current Help for behaviour and bounds. | +| `SellPlayer` | player:Player | VER-KAUFEN: put an own player on the list | +| `LoanOutPlayer` | player:Player, months:int(12\|24) | VER-LEIHEN: offer an own player for loan | +| `BuyPlayer` | player:Player | VER-KAUFEN on a market player: the offer editor | +| `HirePlayer` | player:Player, months:int(12\|24) | VER-LEIHEN on a market player: the loan offer | +| `OpenOffers` | player:Player | Open Offers. See current Help for behaviour and bounds. | +| `OpenSearch` | – | Open Search. See current Help for behaviour and bounds. | +| `OpenPoach` | – | ABWERBEN: pick a player of another club (Transfer.Poach) | +| `ShowTransferNews` | [count:int] | Show Transfer News. See current Help for behaviour and bounds. | +| `ShowTeamInfo` | – | Show Team Info. See current Help for behaviour and bounds. | + +### `Transfer.Negotiate` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowNegotiation` | – | demand, quote and your offer | +| `SetOffer` | fee:money, salary:money, years:int(1..4), bonusGoal:int, bonusPoints:int, bonusAppearance:int, bonusChampion:int, bonus2to5:int, bonus6to10:int, bonusAvoidRelegation:int | all ten fields | +| `SetOfferField` | field:enum(Fee,Salary,Years,BonusGoal,BonusPoints,BonusAppearance,BonusChampion,Bonus2to5,Bonus6to10,BonusAvoidRelegation), value:int | change one field (a fresh quote follows) | +| `SubmitOffer` | – | ANGEBOT: hand in the offer | +| `ShowTeamInfo` | – | TEAM-INFO: your club's squad, as the editor shows it | +| `ShowPlayerInfo` | – | SPIELER-INFO: the player's card with his market value | + +### `Transfer.Search` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSearchProfile` | – | Show Search Profile. See current Help for behaviour and bounds. | +| `SuggestProfile` | – | Suggest Profile. See current Help for behaviour and bounds. | +| `SetSearchProfile` | types:list(TOR,ABW,MIT,STU), age:range, strength:range, focus:list(Fitness,Skill,Form), side:enum(Left,Right,Both), style:enum(Defensive,Offensive,Both), price:enum(Min,Normal,Max) | Set Search Profile. See current Help for behaviour and bounds. | +| `StartSearch` | – | Start Search. See current Help for behaviour and bounds. | + +### `Transfer.Poach` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListPoachClubs` | [league:int] | the clubs of a league (default: own) | +| `ListClubPlayers` | club:Club | the players of the club | +| `PoachPlayer` | player:Player | the offer to a player of another club (decided at once) | + +### `Transfer.Offers` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListOffers` | [player:Player] | List Offers. See current Help for behaviour and bounds. | +| `AcceptOffer` | offer:int | Accept Offer. See current Help for behaviour and bounds. | +| `RejectOffer` | offer:int | Reject Offer. See current Help for behaviour and bounds. | +| `NegotiateOffer` | offer:int | Negotiate Offer. See current Help for behaviour and bounds. | +| `ChooseBuyer` | player:Player, offer:int | Choose Buyer. See current Help for behaviour and bounds. | + +### `Contracts` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowContracts` | [sheet:enum(A,B)] | the squad with salaries and contract months | +| `ShowTeamBonuses` | – | the seven team bonuses (percent of the salary) | +| `SetTeamBonus` | kind:enum(Goal,Points,Appearance,Champion,Place2to5,Place6to10,AvoidRelegation), percent:int | a team bonus; it can only be raised | +| `OpenNegotiation` | player:Player | the player's demands (Contracts.Negotiate) | + +### `Contracts.Negotiate` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowDemands` | – | the demands for 1-4 years | +| `SetContractOffer` | years:int(1..4), salary:money | the salary offer (monthly) | +| `SetInsurance` | form:enum(A,B,C,D), months:int | insure the player (no question) | +| `SetPlayerBonus` | kind:enum(Goal,Points,Appearance,Champion,Place2to5,Place6to10,AvoidRelegation), percent:int | a bonus for this player (PRÄMIEN) | +| `MakeOffer` | – | ANGEBOT MACHEN: the player decides | + +### `Bank` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowBank` | – | balance, savings, credit line, season base | +| `OpenAccount` | – | the finance overview (Bank.Account) | +| `OpenSavings` | – | the fixed deposit (Bank.Savings) | +| `OpenCredit` | [lender:enum(Bank,Manager1,Manager2,Manager3,Manager4)] | the credit view (Bank.Credit) | +| `OpenRealEstate` | – | real estate funds (Bank.RealEstate) | +| `OpenShares` | – | the stock market (Bank.Shares) | + +### `Bank.Account` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowFinanceOverview` | – | assets, debts and net worth | +| `ShowAssetProfitLoss` | asset:int(0..11) | profit/loss of a share | + +### `Bank.Savings` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSavings` | – | account and fixed deposit | +| `Deposit` | amount:money(>0) | account -> fixed deposit | +| `Withdraw` | amount:money(>0) | fixed deposit -> account | + +### `Bank.Shares` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListShares` | – | the twelve shares | +| `ShowShare` | asset:int(0..11) | one share with its last 30 prices | +| `ShareAdvice` | asset:int(0..11) | the bank's tip for a share | +| `BuyShares` | asset:int(0..11), count:int(>0) | buy shares | +| `SellShares` | asset:int(0..11), count:int(>0) | sell shares | + +### `Bank.RealEstate` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListRealEstate` | – | the six real estate funds | +| `BuyRealEstate` | type:int(0..5), units:int(>0) | buy units | +| `SellRealEstate` | type:int(0..5), units:int(>0) | sell units | + +### `Bank.Credit` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowCredit` | [lender:enum(Bank,Manager1..4)] | the credit rows with the editable ranges | +| `SetCreditAmount` | amount:money | AUSGEZAHLTER BETRAG: the credit | +| `SetCreditPayment` | monthly:money | the monthly payment: within 20 % of the annuity for a credit from a manager | +| `SetCreditTerm` | months:int | LAUFZEIT in months | +| `RepayCredit` | amount:money \| All | RÜCKZAHLUNG: pay back (All = as much as possible) | +| `ConfirmCredit` | – | book the changes (asks about fees) | +| `CancelCredit` | – | discard the changes | + +### `Stadium` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowStadium` | – | facilities, maintenance and blocks | +| `ShowFutureExpansion` | – | Show Future Expansion. See current Help for behaviour and bounds. | +| `QuoteBlockExpansion` | block:enum(A..H), seats:int, seated:bool, roofed:bool | Quote Block Expansion. See current Help for behaviour and bounds. | +| `ConfirmBlockExpansion` | [tip:bool=false] | Confirm Block Expansion. See current Help for behaviour and bounds. | +| `DeclineBlockExpansion` | – | Decline Block Expansion. See current Help for behaviour and bounds. | +| `BuildFacility` | facility:enum(Floodlights,Scoreboard,PitchHeating,VipLounge) | technical expansion (AUSBAUEN): tier and tip questions | +| `Maintain` | item:enum(Pitch,Comfort,Condition,Safety) | maintenance: tier and tip questions | +| `SetTicketPrice` | price:int(8..25) | the ticket price (as on the desk) | +| `OpenPeriphery` | – | SICHT: PANORAMA (Stadium.Periphery) | +| `OpenData` | – | Open Data. See current Help for behaviour and bounds. | + +### `Stadium.Periphery` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListPeriphery` | – | the 14 objects: built, building, days | +| `QuotePeriphery` | object:int(0..13) | the building firm's current offer (question) | +| `BuildPeriphery` | object:int(0..13), price:money | accept the offer | +| `DeclinePeriphery` | object:int(0..13), price:money | decline the offer | +| `OpenInterior` | – | SICHT: INNEN (back to Stadium) | + +### `Stadium.Data` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowStadiumData` | [chart:enum(Spectators,Admission,StadiumValue,ExtraIncome,Income,Costs), mode:enum(Absolute,Relative)] | Show Stadium Data. See current Help for behaviour and bounds. | + +### `Advertising` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowAdvertising` | – | all boards, shirt, TV and the spending | +| `ListAdOffers` | slot:enum(Board1..Board14,Shirt,Tv) | the offers for a board, the shirt or TV (an expired contract: renewal first) | +| `AcceptAdOffer` | slot:enum, offer:int | ANNEHMEN | +| `DeclineAdOffer` | – | ABBRECHEN | +| `SetSpending` | kind:enum(PublicRelations,FanCare), amount:money | monthly budget for press work or fan care | +| `BuyFanItems` | amount:money | buy fan articles (sold in 6-9 weeks) | + +### `Environment` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowEnvironment` | – | staff levels and the youth academy | +| `SetStaffLevel` | role:enum(AssistantCoach,Doctor,Physio), level:int(0..6) | click a staff tile: level 0..6, 5 000 a month each | +| `SetYouthAcademy` | state:enum(On,Off) | start (July/August) or stop the youth academy | + +### `Balance` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowBalance` | – | all items, the view and the planned profit or loss | +| `SetBalanceView` | view:enum(SoFar,Real,Future) | left button: so far / real / future | +| `SetBalanceItem` | item:enum(IncomeShirt,IncomeBoards,IncomeTv,IncomePeriphery,IncomeRentInterest,IncomeMisc,ExpenseSalaries,ExpenseStadium,ExpenseYouth,ExpenseCoTrainer,ExpenseDoctor,ExpensePhysio,ExpenseTrainingCamp,ExpenseFanCare,ExpensePr,ExpenseInterest,ExpenseMisc,OtherHomeGames,AverageGate,TicketPrice), value:int | change a planned value (views Real and Future) | +| `TakeActuals` | – | "Werte akt.": drop the own changes, back to the game's figures | + +### `Toto` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowToto` | – | the eleven matches with your tips | +| `SetTip` | match:int(1..11), tip:enum(1,0,2) | the tip for one match | +| `SetStake` | amount:money(>=0) | the stake | +| `SubmitToto` | [stake:money, tips:list(11)] | MACH ICH: hand in the coupon | +| `ClearToto` | – | all tips back to 1, stake 0 | + +### `Friendlies` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListFriendlyOpponents` | [league:int(0..8)] | the clubs of a league (default: own) | +| `ProposeFriendly` | club:Club, venue:enum(Home,Away) | the offer: costs and who pays | +| `ListFreeDates` | – | the days the friendly can be played | +| `SetFriendlyDate` | date:date | book the friendly on a free date (YYYY-MM-DD) | + +### `Reschedule` + +| Command | Parameters | Purpose | +|---|---|---| +| `ListRescheduleGames` | – | own home league matches that can be moved | +| `ListRescheduleDates` | game:date | the days the match can be moved to | +| `MoveGame` | game:date, to:date | move the match to a free day | +| `ListMovedGames` | – | moved matches that can still be taken back (new date) | +| `UndoMove` | game:date | take a move back (game = the new date); the match is played on its matchday again | diff --git a/docs/CLI_CONCEPT/07-spieltag.md b/docs/CLI_CONCEPT/07-spieltag.md new file mode 100644 index 0000000..dcb710a --- /dev/null +++ b/docs/CLI_CONCEPT/07-spieltag.md @@ -0,0 +1,57 @@ +# Matches and season boundaries + +The console's stepped clock allows managers to inspect a live match and intervene through the normal tactics and substitution actions. Start with the current status, own pairing and statistics; a global match window can exist on a cup day when a particular manager has no fixture. + +`Step(minutes)` advances a requested interval. `Run(Halftime)` requests the half-time boundary, and `Run(End)` requests completion. These are shared clock commands: with multiple seats, every required seat must submit readiness. Place the clock command last in the block. Read the returned minute and phase before the next request; never ask for half-time after it has already passed. If another seat advances to an intermediate stop, inspect that actual state rather than assuming the previous request's target was reached. + +Only intervene in a match that actually includes the manager's team. A manager without a fixture still participates in the shared clock barrier. Do not manufacture substitutions or tactical mutations merely because another team's match is running. + +Status can report `matchday running, minute N` without a new `# Window: Match` header. Questions can interrupt a clock request and belong to another manager. Follow the question ownership rules in [syntax](01-grundlagen.md) and the [client introduction](../CONSOLE_CLIENTS.md). + +At a season-end desktop, inspect the completed table and financial/squad position before continuing. A historical final table is not itself a new year transition. `State(Desk)` supplies the phase and season index for clients that need to track the boundary. Finite careers can terminate in `GameEnd`; do not keep submitting advance commands after completion. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `Match` + +| Command | Parameters | Purpose | +|---|---|---| +| `Step` | [minutes:int=1] | let the clock run n minutes (default 1) | +| `Run` | [until:enum(Halftime,End)=End] | run to half time or to the end of the day | +| `Pause` | – | Pause. See current Help for behaviour and bounds. | +| `Resume` | – | Resume. See current Help for behaviour and bounds. | +| `ShowMatchStats` | [match:int] | the scoreboard: score, chances, cards, spectators, weather | +| `Watch` | match:int | Watch. See current Help for behaviour and bounds. | +| `Substitute` | out:Player, in:Player | a substitution: a player leaves, a bench player comes on | +| `SetFormation` | slot:int(1..8) | not during a match (move single players with MovePlayer) | +| `MovePlayer` | player:Player, depth:int, lane:int | place a starter on another position for the rest of the match (from minute 3) | +| `SetTactic` | item:int(0..7), value:int | change a tactic setting during the match (item 0 ends the assistant's D/O control) | +| `ShowTactics` | – | the eight tactic settings of your team in this match | +| `SetMarking` | own:Player, opponent:Player | Set Marking. See current Help for behaviour and bounds. | +| `SetOrder` | player:Player, aspect:enum, value:int | Set Order. See current Help for behaviour and bounds. | +| `Open` | window:enum(Lineup,Tactics,Table,Fixtures,Settings) | Open. See current Help for behaviour and bounds. | +| `ShowSquad` | – | your team on the pitch and on the bench | + +### `Desktop|Lineup|Friendlies` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowNationalSquad` | – | Show National Squad. See current Help for behaviour and bounds. | +| `NationalSquadAdd` | player:Player | National Squad Add. See current Help for behaviour and bounds. | +| `NationalSquadRemove` | player:Player | National Squad Remove. See current Help for behaviour and bounds. | + +### `GameEnd` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowHighScore` | – | Show High Score. See current Help for behaviour and bounds. | +| `NewGame` | duration:int(1..5), difficulty:int(1..10), managers:int(1..4), mode:int(1..3), league:bool, world:bool | New Game. See current Help for behaviour and bounds. | +| `LoadGame` | filename:string | Load Game. See current Help for behaviour and bounds. | + +### `Desktop` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSportschau` | [part:enum(Results,TimeBar,BestEleven,MatchdayOverview)] | Show Sportschau. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/08-einstellungen.md b/docs/CLI_CONCEPT/08-einstellungen.md new file mode 100644 index 0000000..dc244ce --- /dev/null +++ b/docs/CLI_CONCEPT/08-einstellungen.md @@ -0,0 +1,24 @@ +# Settings + +`Settings` operates on the career's normal switch settings. Supported boolean switches, numeric values and ranges are defined by the current projection and command help. The [settings format](../formats/EIN.md) includes reserved and multivalued cells; clients should not replace the raw matrix with their own boolean array. + +Frontend capabilities can lock unavailable audio controls. Music preference, effects preference and actual playback-device readiness are different states. Use the projected availability and normal actions. Graphical process options such as `--mute`, `--no-music` or `--volume` are launch options, not new console commands or save fields. + +Availability also depends on mode and manager role. A setting rejected by the engine should remain unchanged; do not bypass the rejection by patching a save. + +## Command index + +This index includes registered and reserved names. `ListOptions` and `Help` from the running build determine current signatures and availability. An indexed command may reject an unsupported context with `E_ENGINE_GAP`. Parameters retain the console notation; `—` means none. + +### `Settings` + +| Command | Parameters | Purpose | +|---|---|---| +| `ShowSettings` | [group:enum(Results,Sound,Game,Limits,MenuEdit,Functions,Sportschau,Display,Values,Delays)] | the switch field A1-T9 | +| `ShowSwitch` | key:string | one switch | +| `SetSwitch` | key:string, value:int | set a switch (on/off or a number) | +| `IncreaseSwitch` | key:string | the plus field (columns 8, 9) | +| `DecreaseSwitch` | key:string | the minus field (columns 8, 9) | +| `LoadSettings` | file:string | Load Settings. See current Help for behaviour and bounds. | +| `SaveSettings` | file:string | Save Settings. See current Help for behaviour and bounds. | +| `ShowReadme` | – | Show Readme. See current Help for behaviour and bounds. | diff --git a/docs/CLI_CONCEPT/09-texte.md b/docs/CLI_CONCEPT/09-texte.md new file mode 100644 index 0000000..3479da1 --- /dev/null +++ b/docs/CLI_CONCEPT/09-texte.md @@ -0,0 +1,9 @@ +# Text, encoding and editions + +The installation supplies game text and names. The command vocabulary stays stable across editions; it is not translated into the selected game's display language. German and English installation data can have different text, league contents, executable layouts and currency presentation. English support remains experimental as described in the [release notes](../release/0.1/RELEASE_NOTES.md). + +Legacy bytes are decoded at the display boundary. Client-facing text is intended to be UTF-8, while save and database offsets refer to legacy byte pools. Avoid using a displayed name as a persistent identifier: names may be edited, ambiguous or rendered differently. Prefer the ID domain required by the current command. + +Structured records separate data from prose. Clients should decide from IDs, enums, numeric fields, question options and error codes rather than searching for a translated sentence. Preserve raw response bytes when investigating an encoding problem, and avoid publishing proprietary text collections or full game logs containing original content. + +[TEXTD](../formats/TEXTD.md) describes the text database's structure. Replacement text requires an independent redistribution license. No extracted text inventory is included in this repository. diff --git a/docs/CLI_CONCEPT/10-agenten-und-tests.md b/docs/CLI_CONCEPT/10-agenten-und-tests.md new file mode 100644 index 0000000..1d2dc1c --- /dev/null +++ b/docs/CLI_CONCEPT/10-agenten-und-tests.md @@ -0,0 +1,9 @@ +# Developing clients and tests + +Start with the [client introduction](../CONSOLE_CLIENTS.md). A client should keep policy separate from transport: the transport submits one block, preserves the whole response and returns ownership, questions, errors and structured records to the policy. The policy then chooses a legal action for its own manager. + +For automated checks, use independently created input and synthetic fixtures. Parser tests should exercise quoting, named arguments and block boundaries. Session tests should verify real outcomes such as a rejected stale action leaving state unchanged, a question being resolved by its actual owner, or a cancelled staged offer releasing its suspended operation. A printout matching a proposed answer is not evidence that the game state changed correctly. + +Replay checks compare execution with the same binary, data and initial state; they do not prove universal compatibility with every original edition. Keep test outputs private when they contain game text or personal information. Public bug reports should contain minimal independently written steps, relevant version identifiers and the observed failure, without original executables, artwork, recordings or saved games. + +Build/test setup is described in [BUILDING](../BUILDING.md). Original-data checks require a user-supplied installation and can be skipped when that input is absent. Do not report a skipped check as passed. New frontend code should reuse session actions rather than implementing another transfer, match or finance engine. diff --git a/docs/CLI_CONCEPT/12-beispiele.md b/docs/CLI_CONCEPT/12-beispiele.md new file mode 100644 index 0000000..6dbb568 --- /dev/null +++ b/docs/CLI_CONCEPT/12-beispiele.md @@ -0,0 +1,69 @@ +# Small console examples + +These fragments illustrate the console syntax. They are not a recorded game session. Run each only in the indicated context and inspect the actual response before submitting a dependent block. + +## Discover commands + +```text +ListOptions +Help +Status +go. +``` + +## Inspect a running career + +```text +State(Desk) +State(Lineup) +Advice +go. +``` + +`State` requires a running career. A manager client can only inspect its permitted owned views. Read returned IDs before constructing actions that refer to a player or club. + +## Open a management window + +From the active manager's desktop: + +```text +Open(Tactics) +ListOptions +go. +``` + +Choose a supported setting using the returned help, then close the window before ending the turn. A command executed earlier in a failed batch is not undone. + +## Resolve a question + +If the current response addresses question ID 42 to this manager and lists `No` as an option, this block selects it: + +```text +Answer(42, No) +go. +``` + +The number 42 is illustrative. Always use the actual ID, owner and options. Do not repeat a previous answer against a new question. + +## Finish a turn or advance a match + +From the desktop, after completing management decisions: + +```text +Kickoff +go. +``` + +From an active match before half-time: + +```text +ShowMatchStats +Run(Halftime) +go. +``` + +Check the returned minute and current phase before advancing again. Use `Run(End)` after half-time. With multiple managers, the shared clock waits for every required seat. Questions can interrupt these requests. + +## Ask a mailbox client to wait + +After starting a multi-seat server as described in the [client introduction](../CONSOLE_CLIENTS.md), send `WaitTurn` followed by `go.` to that seat using `--send`. Keep that one request pending until its response arrives. Do not start a second client for the same seat merely because the server has not answered yet. diff --git a/docs/CLI_CONCEPT/15-frontends.md b/docs/CLI_CONCEPT/15-frontends.md new file mode 100644 index 0000000..6fa950d --- /dev/null +++ b/docs/CLI_CONCEPT/15-frontends.md @@ -0,0 +1,13 @@ +# Alternative frontends + +A frontend can use the console without duplicating gameplay rules. Start `openbmh_cli --console` with standard input/output, a directory mailbox or a loopback socket. All three reach the same session. See the [client introduction](../CONSOLE_CLIENTS.md) for framing and ownership. + +`--json` emits one JSON object per output line. Each has a line class, window, player and text; structured information is carried in `data`. Table records include both displayed cells and named values where available. Question records include their ID, recipient, options and default. Inspect these fields instead of parsing translated labels. + +`State(view)` returns an owned projection. Supported views include `Desk`, `Table`, `Lineup`, `Mailbox`, `Bank`, `Market`, `Advertising`, `Contracts`, `Stadium`, `Toto`, `Training` and `Camp`. Mutations still use the current window's commands and the session's normal validation. A state snapshot does not grant permission to act for another manager. + +Semantic fields such as `plain_background`, `solid_panel_background`, `compact_dialog_frame`, `replay_progression_mode` and `replay_chance_mode` describe projected behaviour. Their names are independent of executable table locations. Presence flags such as `has_replay_progression_mode` describe whether the corresponding value is available; they are not extra gameplay switches. + +Rendering should retain the revision and identifiers associated with a projection. Refresh after successful mutation, manager handoff or a season transition. Modal editors have their own lifetime: update their staged fields or cancel through their owning action, and do not keep rendering pointers into a mutable session object. + +The transport is a local integration interface, not an authenticated public game service. A network-facing application needs its own access control and deployment design; changing the socket bind address is not a complete service architecture. diff --git a/docs/CLI_CONCEPT/README.md b/docs/CLI_CONCEPT/README.md new file mode 100644 index 0000000..e156e4e --- /dev/null +++ b/docs/CLI_CONCEPT/README.md @@ -0,0 +1,26 @@ +# Console reference + +`openbmh_cli --console` provides a window-oriented command language over the same career session used by the graphical game. It supports interactive use, scripts, independent manager clients and alternative frontends. It is separate from the smaller [JSON request protocol](../protocol.md) selected without `--console`. + +```sh +openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --seed 1 +``` + +Enter `ListOptions`, then `go.` on its own line to see the current commands. Use `Help` for signatures. Commands execute as a block when `go.` is read; they are not executed merely by entering a line. + +- [Syntax, output, errors and questions](01-grundlagen.md) +- [Windows and navigation](02-fenster.md) +- [Starting and loading careers](03-start.md) +- [Desktop, calendar and saved games](04-schreibtisch.md) +- [Tables and information](05-information.md) +- [Club management](06-verein.md) +- [Matches and season boundaries](07-spieltag.md) +- [Settings](08-einstellungen.md) +- [Text and edition handling](09-texte.md) +- [Client development and tests](10-agenten-und-tests.md) +- [Small examples](12-beispiele.md) +- [Alternative frontends](15-frontends.md) + +The [client and agent introduction](../CONSOLE_CLIENTS.md) explains mailbox/socket transport and safe ownership rules. [commands.csv](commands.csv) is a machine-readable command/window index. Its nine-column schema is retained for existing tooling; descriptive provenance columns may be empty, and implementation markers are not a runtime capability query. The running build's `ListOptions` and `Help` take precedence over this index. Recognised operations can still return `E_ENGINE_GAP` when a required engine path is unavailable. + +Examples use independently written names and placeholder paths. The repository supplies no original game content, text catalogue or recorded game session. diff --git a/docs/CLI_CONCEPT/commands.csv b/docs/CLI_CONCEPT/commands.csv new file mode 100644 index 0000000..b7f4797 --- /dev/null +++ b/docs/CLI_CONCEPT/commands.csv @@ -0,0 +1,349 @@ +"window";"command";"parameters";"effect";"errors";"engine";"c4";"status";"source" +"*";"ListOptions";"[command:string | all]";"commands possible here; ListOptions(all) also shows locked ones";"—";"";"";"cli";"01-grundlagen.md" +"*";"GoBack";"–";"right mouse button: one level back, otherwise nothing";"—";"";"";"cli";"01-grundlagen.md" +"*";"Chat";"[to:int], text:string";"message to all, or to one player (0 = only the log)";"E_BAD_ARGUMENT";"";"";"cli";"01-grundlagen.md" +"*";"ChatLog";"[count:int=20]";"the last chat messages";"—";"";"";"cli";"01-grundlagen.md" +"*";"Answer";"id:int, option:enum";"answer the open question";"E_NOT_YOUR_TURN, E_BAD_ARGUMENT";"";"";"cli";"01-grundlagen.md" +"*";"Status";"–";"window, player and a short overview";"—";"";"";"cli";"01-grundlagen.md" +"*";"State";"view:enum(Desk,Table,Lineup,Mailbox,Bank,Market,Advertising,Contracts,Stadium,Toto,Training,Camp)";"the full projection of a view as structured (JSON) data";"E_NOT_IN_WINDOW, E_MODE_LOCKED";"";"";"cli";"01-grundlagen.md" +"*";"Advice";"–";"situations that need a decision now: form, squad, contracts, advertising, money";"E_NOT_IN_WINDOW";"";"";"cli";"01-grundlagen.md" +"*";"Scoreboard";"–";"all human managers: league, place, points, balance, strength of the best eleven";"E_NOT_IN_WINDOW";"";"";"cli";"01-grundlagen.md" +"*";"Help";"[command:string]";"command reference (all windows)";"—";"";"";"cli";"01-grundlagen.md" +"*";"Quit";"[force:bool=false]";"end the session (asks first during a game)";"—";"";"";"ready";"01-grundlagen.md" +"NewGame";"ShowOptions";"–";"show the options with their current values";"—";"";"";"partial";"03-start.md" +"NewGame";"NewGame";"duration:int(1..5), difficulty:int(1..10), managers:int(1..4), mode:int(1..3), league:bool, world:bool";"set all options and continue (= right mouse)";"E_BAD_ARGUMENT";"";"";"partial";"03-start.md" +"NewGame";"SetDuration";"duration:int(1..5)";"1-4 seasons, 5 = endless";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame";"SetDifficulty";"difficulty:int(1..10)";"number of balls";"E_BAD_ARGUMENT";"";"";"partial";"03-start.md" +"NewGame";"SetManagers";"managers:int(1..4)";"human managers";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame";"SetMode";"mode:int(1..3)";"range of desk functions";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame";"SetLeagueMode";"on:bool";"league mode on/off";"E_RULE";"";"";"ready";"03-start.md" +"NewGame";"SetWorldMode";"on:bool";"world cup mode on/off";"E_RULE";"";"";"ready";"03-start.md" +"NewGame";"OpenLoadBrowser";"–";"open the load browser";"—";"";"";"ready";"03-start.md" +"NewGame";"LoadGame";"filename:string";"load a saved game";"E_IO, E_RULE";"";"";"ready";"03-start.md" +"NewGame.Select";"ListTeams";"[league:int | tab:enum]";"clubs of a picker tab (Bundesliga ... AdditionalB)";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame.Select";"ListPortraits";"–";"the twelve portraits and who took them";"—";"";"";"ready";"03-start.md" +"NewGame.Select";"ListStrengths";"–";"the three club strengths";"—";"";"";"ready";"03-start.md" +"NewGame.Select";"ShowSelection";"–";"the choices of this player";"—";"";"";"ready";"03-start.md" +"NewGame.Select";"SetManagerName";"name:string(1..20)";"the manager's name (1-20 characters)";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame.Select";"SetClub";"club:Club";"the club: club: from ListTeams or ""name""";"E_RULE";"";"";"ready";"03-start.md" +"NewGame.Select";"SetStartLeague";"league:enum(Bundesliga,SecondLeague,RegionalA,RegionalB,Oberliga)";"the league to start in";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame.Select";"SetStrength";"strength:enum(Upper,Middle,Lower)";"the club's strength";"E_BAD_ARGUMENT";"";"";"ready";"03-start.md" +"NewGame.Select";"SetPortrait";"portrait:int(0..11)";"the manager's portrait";"E_RULE";"";"";"ready";"03-start.md" +"NewGame.Select";"SelectTeam";"managerName:string, club:Club, startLeague:enum, strength:enum, portrait:int";"set all five and ask for confirmation";"—";"";"";"ready";"03-start.md" +"NewGame.Select";"Confirm";"–";"show the summary and ask ""all details correct?""";"E_RULE";"";"";"ready";"03-start.md" +"NewGame.Select.Confirm";"ShowSummary";"–";"the choices of this player";"—";"";"";"ready";"03-start.md" +"NewPlayer";"ShowNewPlayerOptions";"–";"Show New Player Options. See current Help for behaviour and bounds.";"—";"";"";"ready";"03-start.md" +"NewPlayer";"SetManagers";"managers:int(current..4)";"Set Managers. See current Help for behaviour and bounds.";"E_RULE";"";"";"ready";"03-start.md" +"NewPlayer";"SetDifficulty";"difficulty:int(1..10)";"Set Difficulty. See current Help for behaviour and bounds.";"E_RULE";"";"";"ready";"03-start.md" +"NewPlayer";"Confirm";"–";"Confirm. See current Help for behaviour and bounds.";"—";"";"";"ready";"03-start.md" +"Desktop";"ShowDesk";"–";"all displays of the desk";"—";"";"";"ready";"04-schreibtisch.md" +"Desktop";"ShowDate";"–";"date, weekday, season day, league round";"—";"";"";"ready";"04-schreibtisch.md" +"Desktop";"ShowFinance";"–";"balance, savings, ticket price";"—";"";"";"partial";"04-schreibtisch.md" +"Desktop";"ShowFanStanding";"–";"standing with the fans";"—";"";"";"ready";"04-schreibtisch.md" +"Desktop";"ShowLamps";"–";"the ten warning lamps";"—";"";"";"ready";"04-schreibtisch.md" +"Desktop";"ShowLastGames";"–";"the last six games";"—";"";"";"partial";"04-schreibtisch.md" +"Desktop";"ShowOpponent";"–";"the next game and opponent";"—";"";"";"partial";"04-schreibtisch.md" +"Desktop";"ShowPositionCurves";"[own|opponent]";"table positions per matchday";"—";"";"";"partial";"04-schreibtisch.md" +"Desktop";"ShowAutomation";"–";"the five automations";"—";"";"";"ready";"04-schreibtisch.md" +"Desktop";"Open";"window:enum | menu:int";"open a window (click on its icon); see the lines below";"E_MODE_LOCKED, E_BAD_ARGUMENT";"";"";"ready";"04-schreibtisch.md" +"Desktop";"Key";"letter:enum(A..Z)";"a key on the desk (G = Kickoff)";"E_BAD_ARGUMENT";"";"";"ready";"04-schreibtisch.md" +"Desktop";"SetTicketPrice";"price:int(8..25)";"the ticket price (price scale)";"E_BAD_ARGUMENT, E_PHASE_LOCKED";"";"";"partial";"04-schreibtisch.md" +"Desktop";"SetAutomation";"feature:enum(Lineup,Substitution,Tactics,Marking,Training), on:bool";"switch one of the five automations (Lineup: a saved formation 1-8)";"E_RULE";"";"";"ready";"04-schreibtisch.md" +"Desktop";"Kickoff";"–";"hand over to the next player or start the day";"E_PENDING_QUESTION";"";"";"ready";"04-schreibtisch.md" +"Desktop";"OpenMailbox";"–";"open the mailbox (Kicker)";"—";"";"";"partial";"04-schreibtisch.md" +"Desktop";"OpenDrawer";"–";"open the menu bar";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop";"PullPlug";"–";"the plug: quit after a question";"—";"";"";"ready";"04-schreibtisch.md" +"Mailbox";"ListMessages";"–";"the messages of this manager (msg numbers for Keep/Delete)";"—";"";"";"partial";"04-schreibtisch.md" +"Mailbox";"KeepMessage";"msg:int";"keep a message / let it go (at most five)";"E_RULE";"";"";"partial";"04-schreibtisch.md" +"Mailbox";"DeleteMessage";"msg:int";"throw a message away";"E_BAD_ARGUMENT";"";"";"partial";"04-schreibtisch.md" +"Desktop.Drawer";"ListIcons";"–";"List Icons. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"MoveIcon";"window:enum, x:int, y:int";"Move Icon. See current Help for behaviour and bounds.";"E_RULE";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"OpenFolder";"folder:int(1..3)";"Open Folder. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"OpenTrash";"–";"Open Trash. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"StoreIcon";"window:enum, folder:int(1..3)";"Store Icon. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"RetrieveIcon";"window:enum";"Retrieve Icon. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"SaveMenuDesign";"file:string";"Save Menu Design. See current Help for behaviour and bounds.";"E_IO";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"LoadMenuDesign";"file:string";"Load Menu Design. See current Help for behaviour and bounds.";"E_IO";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"SetTransparent";"window:enum, on:bool";"Set Transparent. See current Help for behaviour and bounds.";"—";"";"";"gap";"04-schreibtisch.md" +"Desktop.Drawer";"CloseDrawer";"–";"Close Drawer. See current Help for behaviour and bounds.";"E_RULE";"";"";"gap";"04-schreibtisch.md" +"Calendar";"ShowCalendar";"[month:int(1..12)]";"Show Calendar. See current Help for behaviour and bounds.";"—";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"ListFiles";"–";"List Files. See current Help for behaviour and bounds.";"—";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"ChangeDirectory";"name:string";"Change Directory. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"ParentDirectory";"–";"Parent Directory. See current Help for behaviour and bounds.";"—";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"SelectFile";"name:string";"Select File. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"FileInfo";"name:string";"File Info. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"Load";"[name:string]";"Load. See current Help for behaviour and bounds.";"E_IO, E_RULE";"";"";"partial";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"Save";"[name:string], [overwrite:bool=false]";"Save. See current Help for behaviour and bounds.";"E_IO, E_RULE";"";"";"ready";"04-schreibtisch.md" +"LoadGame|SaveGame|NewGame.LoadGame";"DeleteFile";"name:string";"Delete File. See current Help for behaviour and bounds.";"E_IO, E_ENGINE_GAP";"";"";"partial";"04-schreibtisch.md" +"LeagueTable";"ShowTable";"[league:int(0..8)]";"the table (without league: the one shown)";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"LeagueTable";"SetLeague";"league:int(0..8)";"show another league";"E_RULE";"";"";"partial";"05-information.md" +"LeagueTable";"ToggleEurope";"–";"Toggle Europe. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"LeagueTable";"SetView";"view:enum(Total,Home,Away)";"Set View. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"LeagueTable";"SetCriteria";"points:bool, goals:bool, goalsAgainst:bool";"Set Criteria. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"LeagueTable";"SetRange";"all | from:int, to:int";"Set Range. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"LeagueTable";"SetPointsMode";"mode:enum(Normal,English)";"Set Points Mode. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"LeagueTable";"ComputerTip";"–";"Computer Tip. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"engine";"05-information.md" +"LeagueTable";"OpenFixtures";"–";"the fixtures of this league";"—";"";"";"partial";"05-information.md" +"LeagueTable";"OpenStrengths";"–";"Open Strengths. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"LeagueTable";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"Fixtures";"ShowFixtures";"[league:int, matchday:int]";"the page shown (optionally another league / matchday first)";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"Fixtures";"SetLeague";"league:int(0..8)";"another league";"—";"";"";"partial";"05-information.md" +"Fixtures";"SetMatchday";"matchday:int";"go to a matchday";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"Fixtures";"NextMatchday";"–";"the next matchday (arrow)";"—";"";"";"partial";"05-information.md" +"Fixtures";"PreviousMatchday";"–";"the previous matchday (arrow)";"—";"";"";"partial";"05-information.md" +"Fixtures";"FindGame";"home:Club, away:Club";"Find Game. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"Fixtures";"GamesOf";"club:Club";"Games Of. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Fixtures";"Page";"n:int";"Page. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"Fixtures";"ShowPostponed";"–";"the postponed games";"—";"";"";"partial";"05-information.md" +"Fixtures";"ComputerTip";"–";"the computer's forecast for this page";"E_ENGINE_GAP";"";"";"partial";"05-information.md" +"Fixtures";"OpenTable";"–";"the league table";"—";"";"";"partial";"05-information.md" +"Fixtures";"OpenStrengths";"–";"Open Strengths. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Fixtures";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"Strengths";"ShowStrengths";"[league:int]";"Show Strengths. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SetLeague";"league:int(0..8)";"Set League. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SetCriteria";"fitness:bool, skill:bool, form:bool, morale:bool";"Set Criteria. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SetLines";"goalkeeper:bool, defence:bool, midfield:bool, attack:bool";"Set Lines. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SetZeroValue";"–";"Set Zero Value. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SortByAge";"on:bool";"Sort By Age. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"SetPlayerFilter";"filter:enum(All,OnPitchOnly)";"Set Player Filter. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"OpenFixtures";"–";"Open Fixtures. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"OpenTable";"–";"Open Table. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Strengths";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"TeamInfo";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"TeamInfo";"ShowTeamSquad";"[view:enum(A,B)]";"the club's squad";"—";"";"";"partial";"05-information.md" +"TeamInfo";"ShowTeamStatistics";"[scope:enum(Home,Away,Total)]";"Show Team Statistics. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"TeamInfo";"SetBroadcast";"club:Club, mode:enum(Dots,Headphones,Camera)";"Set Broadcast. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"TeamInfo";"ShowPlayer";"player:Player";"a player of this club";"—";"";"";"ready";"05-information.md" +"TeamInfo";"CloseTeamInfo";"–";"back to where it was opened";"—";"";"";"partial";"05-information.md" +"Achievements";"ShowAchievements";"–";"Show Achievements. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Achievements";"ShowCompetitionSeason";"competition:enum(League,DfbCup,European)";"Show Competition Season. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"OtherGames";"ShowCompetition";"[competition:enum, round:enum, matchday:int]";"Show Competition. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT, E_RULE";"";"";"partial";"05-information.md" +"OtherGames";"SetCompetition";"competition:enum(DfbCup,UefaCup,ChampionsLeague,CupWinners,World,SuperCup)";"Set Competition. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"OtherGames";"SetRound";"round:string";"Set Round. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"05-information.md" +"OtherGames";"NextMatchday";"–";"Next Matchday. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"OtherGames";"PreviousMatchday";"–";"Previous Matchday. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"OtherGames";"CompleteView";"–";"Complete View. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"OtherGames";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"IndoorTable";"ShowIndoorTable";"–";"Show Indoor Table. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"IndoorTable";"OpenTeamInfo";"club:Club";"Open Team Info. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"05-information.md" +"TopScorers";"ShowScorers";"[list:enum(Goals,Assists,Score), scope:enum(League,Managers)]";"the best ten: goals, assists or both; whole league or managers' clubs";"—";"";"";"ready";"05-information.md" +"TopScorers";"SetList";"list:enum(Goals,Assists,Score)";"TORSCHÜTZEN / VORLAGEN / SCORER";"—";"";"";"ready";"05-information.md" +"TopScorers";"SetScope";"scope:enum(League,Managers)";"GESAMTE LIGA / NUR MANAGER";"—";"";"";"ready";"05-information.md" +"FairPlay";"ShowFairPlay";"–";"Show Fair Play. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"HighScore";"ShowHighScore";"–";"the high score list and your current score";"—";"";"";"ready";"05-information.md" +"Statistics";"OpenView";"view:enum(Opportunities,AllTimeTable,SeriesRecords,Transfers,WorldCup,Winners,Charts,Finances,MinuteStats)";"Open View. See current Help for behaviour and bounds.";"—";"";"";"cli";"05-information.md" +"Statistics";"ShowOpportunities";"[mode:enum(A,B,C,D)]";"Show Opportunities. See current Help for behaviour and bounds.";"—";"";"";"engine";"05-information.md" +"Statistics";"ShowAllTimeTable";"[country:enum(Bundesliga,France,England,Spain,Italy)], [mode:enum(Absolute,Relative)]";"Show All Time Table. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"05-information.md" +"Statistics";"ShowSeriesRecords";"–";"Show Series Records. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Statistics";"ShowTransferHistory";"–";"Show Transfer History. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"05-information.md" +"Statistics";"ShowWorldCupStats";"[nation:string]";"Show World Cup Stats. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"05-information.md" +"Statistics";"ShowWinners";"[competition:enum(League,DfbCup,ChampionsLeague,CupWinners,WorldCup,EuroCup,IndoorMasters,SuperCup)]";"Show Winners. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Statistics";"ShowCharts";"kind:enum(TablePosition,GateIncome,Balance,Strength,AdvertisingIncome,Assets), [mode:enum(Absolute,Relative)]";"Show Charts. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Statistics";"ShowFinances";"–";"Show Finances. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"Statistics";"ShowMinuteStats";"–";"Show Minute Stats. See current Help for behaviour and bounds.";"—";"";"";"partial";"05-information.md" +"*";"ListLeagues";"–";"leagues with number and size";"—";"";"";"ready";"05-information.md" +"*";"ListClubs";"[league:int]";"List Clubs. See current Help for behaviour and bounds.";"—";"";"";"cli";"05-information.md" +"Lineup";"ShowSquad";"[view:enum(A,B)]";"the squad: values, strength, place";"—";"";"";"partial";"06-verein.md" +"Lineup";"SetSquadView";"view:enum(A,B)";"DATEN-A / DATEN-B";"—";"";"";"partial";"06-verein.md" +"Lineup";"SwapPlayers";"first:Player, second:Player";"exchange two players' places";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup";"OpenPlayer";"player:Player";"the player card (PlayerCard)";"—";"";"";"ready";"06-verein.md" +"Lineup";"OpenPitch";"–";"the pitch (Lineup.Pitch)";"E_ENGINE_GAP";"";"";"partial";"06-verein.md" +"Lineup";"OpenTeamList";"–";"Open Team List. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup";"ShowForeigners";"–";"Show Foreigners. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"ShowPitch";"–";"the eleven with depth/lane, formations, automatic weights";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"SetFormation";"slot:int(1..8)";"one of the eight formations (1-4 given, 5-8 own); the automatic line-up takes over";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Lineup.Pitch";"SaveFormation";"slot:int(5..8)";"save the current positions in an own formation slot (long press)";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Lineup.Pitch";"MovePlayer";"player:Player, depth:int, lane:int";"place a starter freely (switches the automatic line-up off)";"E_RULE";"";"";"ready";"06-verein.md" +"Lineup.Pitch";"SwapPitch";"first:Player, second:Player";"exchange two players on the pitch / bench";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"SetAutoWeights";"kind:enum(Position,SideAndRole,Fatigue), value:int(0..3)";"an automatic line-up weight (the cup is clicked until the value); then SetFormation again";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Lineup.Pitch";"ShowAutoWeights";"–";"the three automatic line-up weights";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"ScrollList";"direction:enum(Up,Down)";"Scroll List. See current Help for behaviour and bounds.";"—";"";"";"cli";"06-verein.md" +"Lineup.Pitch";"SetSquadView";"view:enum(A,B)";"DATEN-A / DATEN-B";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"OpenTeamList";"–";"Open Team List. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"OpenOrder";"–";"ORDER: the instructions of the starters (Lineup.Order)";"—";"";"";"ready";"06-verein.md" +"Lineup.Pitch";"OpenMarking";"–";"Open Marking. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"ShowZoneCoverage";"–";"Show Zone Coverage. See current Help for behaviour and bounds.";"E_RULE";"";"";"gap";"06-verein.md" +"Lineup.Pitch";"OpenSetPieces";"–";"Open Set Pieces. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"ShowPairs";"–";"the Hall partners stored on the tactics board";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Pitch";"PairPlayers";"first:Player, second:Player, depth:int(0..19), lane:int(0..8)";"place the first Hall starter beside the second at the explicit target coordinates";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Order";"ShowOrders";"–";"offense, running, commitment, fighting of every starter";"—";"";"";"ready";"06-verein.md" +"Lineup.Order";"SetOrder";"player:Player, aspect:enum(Offense,Run,Commitment,Fighting), value:int";"one instruction of a starter (as a click in its bar)";"E_BAD_ARGUMENT, E_RULE";"";"";"ready";"06-verein.md" +"Lineup.Marking";"ShowOpponentSquad";"–";"Show Opponent Squad. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Marking";"SetMarking";"own:Player, opponent:Player";"Set Marking. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Lineup.Marking";"ClearMarking";"opponent:Player";"Clear Marking. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup.SetPieces";"ShowSetPieces";"–";"Show Set Pieces. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Lineup.SetPieces";"SetSetPieceTaker";"kind:enum(FreeKick,Penalty,Corner), player:Player";"Set Set Piece Taker. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Lineup.SetPieces";"SetSetPieceAuto";"[kind:enum(FreeKick,Penalty,Corner)]";"Set Set Piece Auto. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"PlayerCard";"ShowPlayer";"[player:Player]";"the card (another player of the squad by name)";"—";"";"";"ready";"06-verein.md" +"PlayerCard";"OpenPlayer";"player:Player";"another player's card";"—";"";"";"ready";"06-verein.md" +"PlayerCard";"OpenPlayerStatistics";"–";"the development charts (own players)";"E_RULE";"";"";"ready";"06-verein.md" +"PlayerCard";"Negotiate";"–";"Negotiate. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"PlayerCard";"NationalSquadAdd";"–";"National Squad Add. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"PlayerCard";"NationalSquadRemove";"–";"National Squad Remove. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"PlayerCard.Statistics";"ShowPlayerStatistics";"[chart:enum(Value,Form,Strength,Total), mode:enum(Absolute,Relative)]";"a development chart as a series";"—";"";"";"ready";"06-verein.md" +"PlayerCard.Statistics";"SetChart";"chart:enum(Value,Form,Strength,Total)";"SPIELER-WERT / FORM / STÄRKE / GESAMT";"—";"";"";"ready";"06-verein.md" +"PlayerCard.Statistics";"SetMode";"mode:enum(Absolute,Relative)";"ABS / REL";"—";"";"";"ready";"06-verein.md" +"PlayerCard.Statistics";"BackToPlayerInfo";"–";"back to the card";"—";"";"";"ready";"06-verein.md" +"Tactics";"ShowTactics";"–";"the eight settings with value and maximum";"—";"";"";"ready";"06-verein.md" +"Tactics";"SetTactic";"item:int(0..7), value:int";"set a value directly (item 0 ends the assistant's D/O control)";"E_BAD_ARGUMENT, E_RULE";"";"";"ready";"06-verein.md" +"Tactics";"CycleTactic";"item:int(0..6)";"a click: value + 1, after the maximum 0";"E_RULE";"";"";"ready";"06-verein.md" +"Training";"ShowTraining";"–";"types, areas, sums, players, automation";"—";"";"";"ready";"06-verein.md" +"Training";"SetTrainingType";"type:enum(TOR,ABW,MIT,STU), balls:int(0..3)";"balls of a player type (sum <= 8)";"E_RULE";"";"";"ready";"06-verein.md" +"Training";"SetTrainingArea";"area:enum(Fitness,Skill,Corner,FreeKick,Tackling,Pass,Shot,Speed,Game), balls:int(0..3)";"balls of a training area (F+S <= 4, rest <= 18)";"E_RULE";"";"";"ready";"06-verein.md" +"Training";"SetPlayerIntensity";"player:Player, intensity:int(1..3)";"training intensity of a player";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Training";"CyclePlayerFocus";"player:Player";"the player's focus symbol: next focus";"—";"";"";"ready";"06-verein.md" +"Training";"SetTrainingAutomation";"index:int(0..4), on:bool";"one automation bit (D p. 109)";"E_RULE";"";"";"ready";"06-verein.md" +"Training";"InitializeTraining";"–";"the original initialization (only when needed)";"—";"";"";"ready";"06-verein.md" +"TrainingCamp";"ListResorts";"–";"the eight sports schools with stars and price";"—";"";"";"ready";"06-verein.md" +"TrainingCamp";"ShowCamp";"–";"sliders, recuperation, visits";"—";"";"";"ready";"06-verein.md" +"TrainingCamp";"SetCampFocus";"fitness:int(0..15), skill:int(0..15), game:int(0..15)";"the three sliders; recuperation follows";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"TrainingCamp";"BookCamp";"resort:int(0..7)";"MACH ICH: book the sports school";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"ready";"06-verein.md" +"Transfer";"ShowMarket";"[page:int]";"the offered players (20 per page)";"—";"";"";"partial";"06-verein.md" +"Transfer";"SetMarketFilter";"positions:list(TOR,ABW,MIT,STU) | All";"ALLE / TOR / ABW / MIT / STU";"—";"";"";"partial";"06-verein.md" +"Transfer";"SetSquadView";"view:enum(Active,Team)";"Set Squad View. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"SetSquadSheet";"sheet:enum(A,B)";"Set Squad Sheet. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"SetMarketVisible";"on:bool";"Set Market Visible. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"ShowPlayer";"player:Player";"Show Player. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"SellPlayer";"player:Player";"VER-KAUFEN: put an own player on the list";"E_RULE";"";"";"partial";"06-verein.md" +"Transfer";"LoanOutPlayer";"player:Player, months:int(12|24)";"VER-LEIHEN: offer an own player for loan";"E_RULE";"";"";"ready";"06-verein.md" +"Transfer";"BuyPlayer";"player:Player";"VER-KAUFEN on a market player: the offer editor";"E_RULE";"";"";"partial";"06-verein.md" +"Transfer";"HirePlayer";"player:Player, months:int(12|24)";"VER-LEIHEN on a market player: the loan offer";"E_RULE";"";"";"ready";"06-verein.md" +"Transfer";"OpenOffers";"player:Player";"Open Offers. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"OpenSearch";"–";"Open Search. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"OpenPoach";"–";"ABWERBEN: pick a player of another club (Transfer.Poach)";"—";"";"";"ready";"06-verein.md" +"Transfer";"ShowTransferNews";"[count:int]";"Show Transfer News. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer";"ShowTeamInfo";"–";"Show Team Info. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer.Negotiate";"ShowNegotiation";"–";"demand, quote and your offer";"—";"";"";"partial";"06-verein.md" +"Transfer.Negotiate";"SetOffer";"fee:money, salary:money, years:int(1..4), bonusGoal:int, bonusPoints:int, bonusAppearance:int, bonusChampion:int, bonus2to5:int, bonus6to10:int, bonusAvoidRelegation:int";"all ten fields";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Transfer.Negotiate";"SetOfferField";"field:enum(Fee,Salary,Years,BonusGoal,BonusPoints,BonusAppearance,BonusChampion,Bonus2to5,Bonus6to10,BonusAvoidRelegation), value:int";"change one field (a fresh quote follows)";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Transfer.Negotiate";"SubmitOffer";"–";"ANGEBOT: hand in the offer";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"partial";"06-verein.md" +"Transfer.Negotiate";"ShowTeamInfo";"–";"TEAM-INFO: your club's squad, as the editor shows it";"—";"";"";"ready";"06-verein.md" +"Transfer.Negotiate";"ShowPlayerInfo";"–";"SPIELER-INFO: the player's card with his market value";"—";"";"";"ready";"06-verein.md" +"Transfer.Search";"ShowSearchProfile";"–";"Show Search Profile. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer.Search";"SuggestProfile";"–";"Suggest Profile. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"06-verein.md" +"Transfer.Search";"SetSearchProfile";"types:list(TOR,ABW,MIT,STU), age:range, strength:range, focus:list(Fitness,Skill,Form), side:enum(Left,Right,Both), style:enum(Defensive,Offensive,Both), price:enum(Min,Normal,Max)";"Set Search Profile. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Transfer.Search";"StartSearch";"–";"Start Search. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"06-verein.md" +"Transfer.Poach";"ListPoachClubs";"[league:int]";"the clubs of a league (default: own)";"—";"";"";"ready";"06-verein.md" +"Transfer.Poach";"ListClubPlayers";"club:Club";"the players of the club";"—";"";"";"ready";"06-verein.md" +"Transfer.Poach";"PoachPlayer";"player:Player";"the offer to a player of another club (decided at once)";"E_RULE";"";"";"ready";"06-verein.md" +"Transfer.Offers";"ListOffers";"[player:Player]";"List Offers. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer.Offers";"AcceptOffer";"offer:int";"Accept Offer. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Transfer.Offers";"RejectOffer";"offer:int";"Reject Offer. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Transfer.Offers";"NegotiateOffer";"offer:int";"Negotiate Offer. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"partial";"06-verein.md" +"Transfer.Offers";"ChooseBuyer";"player:Player, offer:int";"Choose Buyer. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Contracts";"ShowContracts";"[sheet:enum(A,B)]";"the squad with salaries and contract months";"—";"";"";"ready";"06-verein.md" +"Contracts";"ShowTeamBonuses";"–";"the seven team bonuses (percent of the salary)";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Contracts";"SetTeamBonus";"kind:enum(Goal,Points,Appearance,Champion,Place2to5,Place6to10,AvoidRelegation), percent:int";"a team bonus; it can only be raised";"E_RULE, E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Contracts";"OpenNegotiation";"player:Player";"the player's demands (Contracts.Negotiate)";"E_RULE";"";"";"partial";"06-verein.md" +"Contracts.Negotiate";"ShowDemands";"–";"the demands for 1-4 years";"—";"";"";"partial";"06-verein.md" +"Contracts.Negotiate";"SetContractOffer";"years:int(1..4), salary:money";"the salary offer (monthly)";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Contracts.Negotiate";"SetInsurance";"form:enum(A,B,C,D), months:int";"insure the player (no question)";"E_RULE";"";"";"partial";"06-verein.md" +"Contracts.Negotiate";"SetPlayerBonus";"kind:enum(Goal,Points,Appearance,Champion,Place2to5,Place6to10,AvoidRelegation), percent:int";"a bonus for this player (PRÄMIEN)";"E_RULE";"";"";"partial";"06-verein.md" +"Contracts.Negotiate";"MakeOffer";"–";"ANGEBOT MACHEN: the player decides";"E_RULE";"";"";"partial";"06-verein.md" +"Bank";"ShowBank";"–";"balance, savings, credit line, season base";"—";"";"";"partial";"06-verein.md" +"Bank";"OpenAccount";"–";"the finance overview (Bank.Account)";"—";"";"";"partial";"06-verein.md" +"Bank";"OpenSavings";"–";"the fixed deposit (Bank.Savings)";"—";"";"";"ready";"06-verein.md" +"Bank";"OpenCredit";"[lender:enum(Bank,Manager1,Manager2,Manager3,Manager4)]";"the credit view (Bank.Credit)";"E_RULE";"";"";"ready";"06-verein.md" +"Bank";"OpenRealEstate";"–";"real estate funds (Bank.RealEstate)";"—";"";"";"ready";"06-verein.md" +"Bank";"OpenShares";"–";"the stock market (Bank.Shares)";"—";"";"";"ready";"06-verein.md" +"Bank.Account";"ShowFinanceOverview";"–";"assets, debts and net worth";"—";"";"";"partial";"06-verein.md" +"Bank.Account";"ShowAssetProfitLoss";"asset:int(0..11)";"profit/loss of a share";"E_ENGINE_GAP";"";"";"partial";"06-verein.md" +"Bank.Savings";"ShowSavings";"–";"account and fixed deposit";"—";"";"";"ready";"06-verein.md" +"Bank.Savings";"Deposit";"amount:money(>0)";"account -> fixed deposit";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Bank.Savings";"Withdraw";"amount:money(>0)";"fixed deposit -> account";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Bank.Shares";"ListShares";"–";"the twelve shares";"—";"";"";"ready";"06-verein.md" +"Bank.Shares";"ShowShare";"asset:int(0..11)";"one share with its last 30 prices";"—";"";"";"ready";"06-verein.md" +"Bank.Shares";"ShareAdvice";"asset:int(0..11)";"the bank's tip for a share";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Bank.Shares";"BuyShares";"asset:int(0..11), count:int(>0)";"buy shares";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"ready";"06-verein.md" +"Bank.Shares";"SellShares";"asset:int(0..11), count:int(>0)";"sell shares";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Bank.RealEstate";"ListRealEstate";"–";"the six real estate funds";"—";"";"";"ready";"06-verein.md" +"Bank.RealEstate";"BuyRealEstate";"type:int(0..5), units:int(>0)";"buy units";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Bank.RealEstate";"SellRealEstate";"type:int(0..5), units:int(>0)";"sell units";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Bank.Credit";"ShowCredit";"[lender:enum(Bank,Manager1..4)]";"the credit rows with the editable ranges";"—";"";"";"ready";"06-verein.md" +"Bank.Credit";"SetCreditAmount";"amount:money";"AUSGEZAHLTER BETRAG: the credit";"E_RULE";"";"";"ready";"06-verein.md" +"Bank.Credit";"SetCreditPayment";"monthly:money";"the monthly payment: within 20 % of the annuity for a credit from a manager";"E_RULE";"";"";"ready";"06-verein.md" +"Bank.Credit";"SetCreditTerm";"months:int";"LAUFZEIT in months";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Bank.Credit";"RepayCredit";"amount:money | All";"RÜCKZAHLUNG: pay back (All = as much as possible)";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Bank.Credit";"ConfirmCredit";"–";"book the changes (asks about fees)";"E_RULE";"";"";"ready";"06-verein.md" +"Bank.Credit";"CancelCredit";"–";"discard the changes";"—";"";"";"ready";"06-verein.md" +"Stadium";"ShowStadium";"–";"facilities, maintenance and blocks";"—";"";"";"partial";"06-verein.md" +"Stadium";"ShowFutureExpansion";"–";"Show Future Expansion. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Stadium";"QuoteBlockExpansion";"block:enum(A..H), seats:int, seated:bool, roofed:bool";"Quote Block Expansion. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"06-verein.md" +"Stadium";"ConfirmBlockExpansion";"[tip:bool=false]";"Confirm Block Expansion. See current Help for behaviour and bounds.";"E_INSUFFICIENT_FUNDS";"";"";"partial";"06-verein.md" +"Stadium";"DeclineBlockExpansion";"–";"Decline Block Expansion. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Stadium";"BuildFacility";"facility:enum(Floodlights,Scoreboard,PitchHeating,VipLounge)";"technical expansion (AUSBAUEN): tier and tip questions";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"ready";"06-verein.md" +"Stadium";"Maintain";"item:enum(Pitch,Comfort,Condition,Safety)";"maintenance: tier and tip questions";"E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Stadium";"SetTicketPrice";"price:int(8..25)";"the ticket price (as on the desk)";"E_BAD_ARGUMENT";"";"";"partial";"06-verein.md" +"Stadium";"OpenPeriphery";"–";"SICHT: PANORAMA (Stadium.Periphery)";"—";"";"";"ready";"06-verein.md" +"Stadium";"OpenData";"–";"Open Data. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Stadium.Periphery";"ListPeriphery";"–";"the 14 objects: built, building, days";"—";"";"";"ready";"06-verein.md" +"Stadium.Periphery";"QuotePeriphery";"object:int(0..13)";"the building firm's current offer (question)";"E_RULE";"";"";"ready";"06-verein.md" +"Stadium.Periphery";"BuildPeriphery";"object:int(0..13), price:money";"accept the offer";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"ready";"06-verein.md" +"Stadium.Periphery";"DeclinePeriphery";"object:int(0..13), price:money";"decline the offer";"—";"";"";"ready";"06-verein.md" +"Stadium.Periphery";"OpenInterior";"–";"SICHT: INNEN (back to Stadium)";"—";"";"";"partial";"06-verein.md" +"Stadium.Data";"ShowStadiumData";"[chart:enum(Spectators,Admission,StadiumValue,ExtraIncome,Income,Costs), mode:enum(Absolute,Relative)]";"Show Stadium Data. See current Help for behaviour and bounds.";"—";"";"";"partial";"06-verein.md" +"Advertising";"ShowAdvertising";"–";"all boards, shirt, TV and the spending";"—";"";"";"ready";"06-verein.md" +"Advertising";"ListAdOffers";"slot:enum(Board1..Board14,Shirt,Tv)";"the offers for a board, the shirt or TV (an expired contract: renewal first)";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Advertising";"AcceptAdOffer";"slot:enum, offer:int";"ANNEHMEN";"E_RULE";"";"";"ready";"06-verein.md" +"Advertising";"DeclineAdOffer";"–";"ABBRECHEN";"—";"";"";"ready";"06-verein.md" +"Advertising";"SetSpending";"kind:enum(PublicRelations,FanCare), amount:money";"monthly budget for press work or fan care";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Advertising";"BuyFanItems";"amount:money";"buy fan articles (sold in 6-9 weeks)";"E_INSUFFICIENT_FUNDS, E_RULE";"";"";"ready";"06-verein.md" +"Environment";"ShowEnvironment";"–";"staff levels and the youth academy";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Environment";"SetStaffLevel";"role:enum(AssistantCoach,Doctor,Physio), level:int(0..6)";"click a staff tile: level 0..6, 5 000 a month each";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Environment";"SetYouthAcademy";"state:enum(On,Off)";"start (July/August) or stop the youth academy";"—";"";"";"ready";"06-verein.md" +"Balance";"ShowBalance";"–";"all items, the view and the planned profit or loss";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Balance";"SetBalanceView";"view:enum(SoFar,Real,Future)";"left button: so far / real / future";"—";"";"";"ready";"06-verein.md" +"Balance";"SetBalanceItem";"item:enum(IncomeShirt,IncomeBoards,IncomeTv,IncomePeriphery,IncomeRentInterest,IncomeMisc,ExpenseSalaries,ExpenseStadium,ExpenseYouth,ExpenseCoTrainer,ExpenseDoctor,ExpensePhysio,ExpenseTrainingCamp,ExpenseFanCare,ExpensePr,ExpenseInterest,ExpenseMisc,OtherHomeGames,AverageGate,TicketPrice), value:int";"change a planned value (views Real and Future)";"E_RULE, E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Balance";"TakeActuals";"–";"""Werte akt."": drop the own changes, back to the game's figures";"—";"";"";"ready";"06-verein.md" +"Toto";"ShowToto";"–";"the eleven matches with your tips";"—";"";"";"ready";"06-verein.md" +"Toto";"SetTip";"match:int(1..11), tip:enum(1,0,2)";"the tip for one match";"E_BAD_ARGUMENT";"";"";"ready";"06-verein.md" +"Toto";"SetStake";"amount:money(>=0)";"the stake";"E_BAD_ARGUMENT, E_INSUFFICIENT_FUNDS";"";"";"ready";"06-verein.md" +"Toto";"SubmitToto";"[stake:money, tips:list(11)]";"MACH ICH: hand in the coupon";"E_RULE";"";"";"ready";"06-verein.md" +"Toto";"ClearToto";"–";"all tips back to 1, stake 0";"—";"";"";"ready";"06-verein.md" +"Friendlies";"ListFriendlyOpponents";"[league:int(0..8)]";"the clubs of a league (default: own)";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Friendlies";"ProposeFriendly";"club:Club, venue:enum(Home,Away)";"the offer: costs and who pays";"E_RULE";"";"";"ready";"06-verein.md" +"Friendlies";"ListFreeDates";"–";"the days the friendly can be played";"—";"";"";"ready";"06-verein.md" +"Friendlies";"SetFriendlyDate";"date:date";"book the friendly on a free date (YYYY-MM-DD)";"E_RULE";"";"";"ready";"06-verein.md" +"Reschedule";"ListRescheduleGames";"–";"own home league matches that can be moved";"E_MODE_LOCKED";"";"";"ready";"06-verein.md" +"Reschedule";"ListRescheduleDates";"game:date";"the days the match can be moved to";"—";"";"";"ready";"06-verein.md" +"Reschedule";"MoveGame";"game:date, to:date";"move the match to a free day";"E_RULE";"";"";"ready";"06-verein.md" +"Reschedule";"ListMovedGames";"–";"moved matches that can still be taken back (new date)";"—";"";"";"ready";"06-verein.md" +"Reschedule";"UndoMove";"game:date";"take a move back (game = the new date); the match is played on its matchday again";"E_RULE";"";"";"ready";"06-verein.md" +"Match";"Step";"[minutes:int=1]";"let the clock run n minutes (default 1)";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"Run";"[until:enum(Halftime,End)=End]";"run to half time or to the end of the day";"—";"";"";"ready";"07-spieltag.md" +"Match";"Pause";"–";"Pause. See current Help for behaviour and bounds.";"—";"";"";"gap";"07-spieltag.md" +"Match";"Resume";"–";"Resume. See current Help for behaviour and bounds.";"—";"";"";"gap";"07-spieltag.md" +"Match";"ShowMatchStats";"[match:int]";"the scoreboard: score, chances, cards, spectators, weather";"—";"";"";"partial";"07-spieltag.md" +"Match";"Watch";"match:int";"Watch. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"Substitute";"out:Player, in:Player";"a substitution: a player leaves, a bench player comes on";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"SetFormation";"slot:int(1..8)";"not during a match (move single players with MovePlayer)";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"MovePlayer";"player:Player, depth:int, lane:int";"place a starter on another position for the rest of the match (from minute 3)";"E_RULE";"";"";"ready";"07-spieltag.md" +"Match";"SetTactic";"item:int(0..7), value:int";"change a tactic setting during the match (item 0 ends the assistant's D/O control)";"E_RULE";"";"";"ready";"07-spieltag.md" +"Match";"ShowTactics";"–";"the eight tactic settings of your team in this match";"E_RULE";"";"";"ready";"07-spieltag.md" +"Match";"SetMarking";"own:Player, opponent:Player";"Set Marking. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"SetOrder";"player:Player, aspect:enum, value:int";"Set Order. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"07-spieltag.md" +"Match";"Open";"window:enum(Lineup,Tactics,Table,Fixtures,Settings)";"Open. See current Help for behaviour and bounds.";"—";"";"";"gap";"07-spieltag.md" +"Match";"ShowSquad";"–";"your team on the pitch and on the bench";"—";"";"";"partial";"07-spieltag.md" +"Desktop|Lineup|Friendlies";"ShowNationalSquad";"–";"Show National Squad. See current Help for behaviour and bounds.";"—";"";"";"partial";"07-spieltag.md" +"Desktop|Lineup|Friendlies";"NationalSquadAdd";"player:Player";"National Squad Add. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"07-spieltag.md" +"Desktop|Lineup|Friendlies";"NationalSquadRemove";"player:Player";"National Squad Remove. See current Help for behaviour and bounds.";"E_RULE";"";"";"partial";"07-spieltag.md" +"GameEnd";"ShowHighScore";"–";"Show High Score. See current Help for behaviour and bounds.";"—";"";"";"ready";"07-spieltag.md" +"GameEnd";"NewGame";"duration:int(1..5), difficulty:int(1..10), managers:int(1..4), mode:int(1..3), league:bool, world:bool";"New Game. See current Help for behaviour and bounds.";"E_BAD_ARGUMENT";"";"";"ready";"07-spieltag.md" +"GameEnd";"LoadGame";"filename:string";"Load Game. See current Help for behaviour and bounds.";"E_IO";"";"";"ready";"07-spieltag.md" +"Desktop";"ShowSportschau";"[part:enum(Results,TimeBar,BestEleven,MatchdayOverview)]";"Show Sportschau. See current Help for behaviour and bounds.";"E_ENGINE_GAP";"";"";"gap";"07-spieltag.md" +"Settings";"ShowSettings";"[group:enum(Results,Sound,Game,Limits,MenuEdit,Functions,Sportschau,Display,Values,Delays)]";"the switch field A1-T9";"—";"";"";"partial";"08-einstellungen.md" +"Settings";"ShowSwitch";"key:string";"one switch";"E_BAD_ARGUMENT";"";"";"partial";"08-einstellungen.md" +"Settings";"SetSwitch";"key:string, value:int";"set a switch (on/off or a number)";"E_BAD_ARGUMENT, E_PHASE_LOCKED";"";"";"partial";"08-einstellungen.md" +"Settings";"IncreaseSwitch";"key:string";"the plus field (columns 8, 9)";"E_BAD_ARGUMENT";"";"";"partial";"08-einstellungen.md" +"Settings";"DecreaseSwitch";"key:string";"the minus field (columns 8, 9)";"E_BAD_ARGUMENT";"";"";"partial";"08-einstellungen.md" +"Settings";"LoadSettings";"file:string";"Load Settings. See current Help for behaviour and bounds.";"E_IO";"";"";"partial";"08-einstellungen.md" +"Settings";"SaveSettings";"file:string";"Save Settings. See current Help for behaviour and bounds.";"E_IO";"";"";"partial";"08-einstellungen.md" +"Settings";"ShowReadme";"–";"Show Readme. See current Help for behaviour and bounds.";"E_IO";"";"";"partial";"08-einstellungen.md" +"*";"HarnessState";"[path:string]";"Harness State. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessHash";"–";"Harness Hash. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessInvariants";"–";"Harness Invariants. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessAutopilot";"player:int(1..4), policy:enum(Default,Saver,Spender,Random,Off)";"Harness Autopilot. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessFast";"matchdays:int, [until:enum(Matchday,Season,GameEnd)]";"Harness Fast. See current Help for behaviour and bounds.";"E_RULE";"";"";"cli";"01-grundlagen.md" +"*";"HarnessCoverage";"–";"Harness Coverage. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessSeed";"–";"Harness Seed. See current Help for behaviour and bounds.";"—";"";"";"cli";"01-grundlagen.md" +"*";"HarnessExpect";"text:string";"Harness Expect. See current Help for behaviour and bounds.";"E_RULE";"";"";"cli";"01-grundlagen.md" diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md new file mode 100644 index 0000000..77a71c2 --- /dev/null +++ b/docs/COMPATIBILITY.md @@ -0,0 +1,13 @@ +# Compatibility decisions + +OpenBMH aims to preserve the familiar game while handling malformed input and unsafe edge cases explicitly. A reconstruction can remain faithful without reproducing a crash or pretending to implement an unknown path. + +- Content such as names, text, graphics and edition-specific tables is loaded from the user's installation. OpenBMH's shared rule base supplies simulation values; selecting another data edition does not select a separate engine. +- Safety checks reject transactions that would exhaust required return capacity, use stale identities or lose a valid state. Unsupported operations report their limitation rather than inventing an outcome. +- Calendar progression handles boundary days and seasonal transitions without relying on unsafe fixed-day assumptions. +- Saves are written from the committed session state. Saving does not deliberately replay unrelated game actions. +- The reconstruction uses two deterministic random generators with explicit integer semantics. This supports reproducible runs, but is not a promise of complete bit-for-bit equivalence to every original edition or across changed engine versions. + +Intentional changes in code should use the marker `OpenBMH deviates from the original:` and explain their purpose. Adding a new behaviour or balance change requires a concrete description and relevant tests; this page is not permission to substitute guessed rules. + +The [generated differences catalogue](DIFFERENCES.md) lists these markers with links to their source files. diff --git a/docs/CONSOLE_CLIENTS.md b/docs/CONSOLE_CLIENTS.md new file mode 100644 index 0000000..22abfbf --- /dev/null +++ b/docs/CONSOLE_CLIENTS.md @@ -0,0 +1,47 @@ +# Writing a console client or agent + +The console is a local control interface for one running career. Human clients, bots and alternative frontends use the same actions and rule checks. Start with [the console reference](CLI_CONCEPT/README.md); use runtime `ListOptions` and `Help` rather than guessing a command from a graphical label. + +## Choose a transport + +For a single process, start `openbmh_cli --console --data "path/to/game" --saves "path/to/saves"`. Send command lines on stdin and finish each block with `go.`. `--json` provides structured output records. + +For separate manager processes, start a local mailbox server: + +```sh +openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --serve mailbox --seats 4 --seed 1 +``` + +A client sends one block on stdin to: + +```sh +openbmh_cli --send mailbox/seat1 --timeout 3600 +``` + +The client still supplies a terminating `go.` line. Seats are numbered 1–4 and represent human manager slots, not runtime team IDs. Submit one request at a time for each seat. A long-running `WaitTurn` or match-clock request must finish before another client uses that seat. A timeout or interrupted shell client does not establish that the server cancelled the game action. + +Alternatively, `--listen PORT --seats N` binds a local socket on `127.0.0.1`. A connection selects `SEAT k` when seats are enabled. Blocks end with `go.` and responses with a line containing only `.`. Keep one connection/request owner per seat. See `--help` for supported combinations of transport and log options. + +## Track ownership and the whole response + +Keep the current seat, window, manager/club identity, phase and pending question/editor. Parse the entire response before choosing the next action. A question can arrive in information produced during another manager's turn or a suspended calendar advance. Match the question's recipient to this client; answer with its actual ID and listed option. + +The seat hub can prefix a response with information accumulated while other managers played. Do not mistake an old desktop in that feed for the current owned projection. Retain questions and errors from the full response, then use the current own state for financial or squad decisions. A new window header is not emitted after every operation. Status can instead report `matchday running, minute N`. + +Use `WaitTurn` when another seat owns management. At a desktop, apply a short batch of independent decisions, then put `Kickoff` last. Reinspect after actions that open a question, negotiate a contract or change the meaning of a row. Unknown questions require a policy decision; `GoBack` can commit a default or cancel an editor and must not be used as a generic acknowledgement. + +## Shared matches and calendar boundaries + +In a stepped match, `Run` and `Step` participate in a barrier across the required seats. Put the clock command last. Read the returned actual minute and phase before choosing another stop; do not request half-time after that boundary. A manager without a fixture still participates in the barrier but should not issue substitutions or tactical edits for another team's match. + +Questions and staged offer editors can suspend a calendar operation. Finish the owning question/editor before requesting another advance. Once an answered clock request returns without advancement, inspect why before sending another readiness request; blindly replaying a mutation can duplicate an effect. + +A useful automated policy inspects budget, advertising, contracts, squad availability and tactics at deliberate intervals, using explicit rules and bounds. `Advice` supplies observations, not a complete strategy. Count actual `season_index` changes and inspect `phase` at year end; a historical table or summary does not constitute another completed season. + +## Reproducibility and recovery + +Record the binary version, data edition, seed, time mode and the exact submitted blocks when a reproducible session matters. The seed alone is insufficient if the initial save, data or command order differs. `--log`, `--replay` and, for supported multi-seat sessions, `--resume` provide execution records; a replay must use compatible inputs. + +Keep an independent input receipt. Mailbox request files are transport state: a held request may be rewritten to `WaitTurn`, including a request originally submitted as a clock command. Such a file is not proof of what was first sent. Preserve responses and raw bytes before decoding diagnostics. Do not publish logs containing proprietary game text, saves or personal data. + +For restart, use a fresh mailbox, pin the intended binary and verify the recovered current phase, manager and pending operation. Do not silently adopt an old client request or run two processes against the same seat. Normal saved games and replay are the supported starting points; editing native state to get past a question defeats the ownership checks the client is meant to exercise. diff --git a/docs/DIFFERENCES.md b/docs/DIFFERENCES.md new file mode 100644 index 0000000..c093572 --- /dev/null +++ b/docs/DIFFERENCES.md @@ -0,0 +1,37 @@ +# Intentional differences from the original + +Generated from source comment markers by `tools/public_release/collect_differences.py`. + +See [Compatibility decisions](COMPATIBILITY.md) for the overall policy. These entries +describe deliberate changes; they are not a list of every known compatibility limit. + +- [src/app/career_session.cpp](../src/app/career_session.cpp): supports designated set-piece record initialization and validation. +- [src/cli/console/windows_environment.cpp](../src/cli/console/windows_environment.cpp): uses monthly staff levels in increments of five thousand and the supported youth-academy controls. +- [src/formats/le.hpp](../src/formats/le.hpp): applies a shared supported rule profile when loading editions with different rule-table values. +- [src/formats/rule_base.cpp](../src/formats/rule_base.cpp): normalizes live-scene defaults, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit across supported editions. +- [src/formats/rule_base.hpp](../src/formats/rule_base.hpp): normalizes live-scene options, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit. +- [src/game/balance_plan.cpp](../src/game/balance_plan.cpp): omits the discontinued youth-group cost categories and uses league-specific youth-academy limits. +- [src/game/balance_plan.hpp](../src/game/balance_plan.hpp): uses the supported staff and youth-academy cost categories. +- [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. +- [src/game/desk_actions.cpp](../src/game/desk_actions.cpp): uses the supported transfer-fee arithmetic and designated set-piece fields. +- [src/game/desk_actions.hpp](../src/game/desk_actions.hpp): supports designated set-piece records and the supported transfer-editor rules. +- [src/game/environment.hpp](../src/game/environment.hpp): enables the supported youth academy and represents staff levels in monthly increments of five thousand. +- [src/game/highscore.cpp](../src/game/highscore.cpp): reads the supported edition-specific high-score format from the loaded image. +- [src/game/lineup.cpp](../src/game/lineup.cpp): disables the foreign-player limit in the supported rule profile. +- [src/game/lineup.hpp](../src/game/lineup.hpp): disables the foreign-player limit and supports owner-bound designated set-piece selection. +- [src/game/match.hpp](../src/game/match.hpp): uses the enhanced injury selection and suspension rules. +- [src/game/match_engine.cpp](../src/game/match_engine.cpp): supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +- [src/game/month.cpp](../src/game/month.cpp): omits the two discontinued youth-group cost categories from monthly accounts. +- [src/game/season.cpp](../src/game/season.cpp): uses the enhanced youth-academy season settlement and player-generation rules. +- [src/game/season.hpp](../src/game/season.hpp): uses the enhanced youth-academy season settlement and player-generation rules. +- [src/game/state.hpp](../src/game/state.hpp): retains designated set-piece selections in the supported manager-record extension. +- [src/game/week.cpp](../src/game/week.cpp): uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +- [src/game/week.hpp](../src/game/week.hpp): uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum. +- [src/game/weekly.cpp](../src/game/weekly.cpp): uses the supported weekly-event configuration, with its rule switch disabled. +- [src/game/weekly.hpp](../src/game/weekly.hpp): uses the supported weekly processing and transfer rule profile. +- [src/ui/advertising.cpp](../src/ui/advertising.cpp): uses the supported youth-academy cap and its saved cost fields. +- [src/ui/environment.cpp](../src/ui/environment.cpp): omits the two discontinued youth groups from the environment screen. +- [src/ui/league_table.hpp](../src/ui/league_table.hpp): uses three points for a win in the supported rule profile. +- [src/ui/pitch.cpp](../src/ui/pitch.cpp): supports owner-bound designated set-piece selection in the extended manager record. +- [src/ui/save_load.cpp](../src/ui/save_load.cpp): omits DOS drive and delete buttons in the directory-confined save/load view. diff --git a/docs/RNG.md b/docs/RNG.md new file mode 100644 index 0000000..78dfb95 --- /dev/null +++ b/docs/RNG.md @@ -0,0 +1,31 @@ +# Random generators + +OpenBMH uses two explicit stateful generators in `src/game/random.hpp`. Frontends do not create gameplay randomness. Save and rollback operations must preserve the relevant generator state and call order. + +## General generator + +The compatibility generator uses a 32-bit unsigned linear recurrence: + +```text +seed = seed * 0x41C64E6D + 0x3039 (modulo 2^32) +r = (seed >> 16) & 0x7FFF +n = hi - lo + 1 +product = signed32(unsigned32(r) * unsigned32(n)) +result = lo + product / 32768 +``` + +The product wraps at 32 bits and signed division truncates toward zero. For an empty range it returns the lower bound without drawing. A run's initial seed is supplied explicitly by the session/CLI when reproducibility is required. + +## Game generator + +The second stream has a separate recurrence and can be reseeded by defined game operations: + +```text +seed = signed32(unsigned32(seed) * 16 + 0xA7) % 4000000 +product = signed32(unsigned32(seed) * unsigned32(hi - lo + 1)) +result = product / 4000000 + lo +``` + +Signed division truncates toward zero; overflow in the indicated products wraps at 32 bits before signed interpretation. Replacing this with floating-point arithmetic or a standard-library distribution changes results. Negative intermediate values must retain their specified semantics. + +Observing or rendering a value should not draw random numbers unless opening that actual game operation requires it. Transactional failures restore both streams with the game state. A seed alone is not a complete replay specification: engine version, data, options and command order also matter. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..d3afe2d --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,29 @@ +# Roadmap + +OpenBMH combines a playable reconstruction with a foundation for extension. These milestones describe direction and dependencies, not promised dates. + +## 0.1: a usable engine + +Career management, matches, finances, transfers, original-style SDL2 screens, audio and a console share the same session logic. German game data is the primary target; Football Limited support is experimental. Compatibility and remaining limitations are documented in the [release notes](release/0.1/RELEASE_NOTES.md). + +## 0.15: broader English compatibility + +Complete edition-specific loading, presentation, competitions and sound support. Imported content determines names, text, clubs and league organisation; a shared engine rule base defines the simulation. + +## 0.2: open data and typed state + +Introduce a documented import format and a native save format, retaining supported legacy import where practical. Replace fixed-layout state gradually with typed clubs, players, contracts and competitions. Keep each intermediate stage usable and cover transitions with tests. + +## 0.3: configurable rules + +Expose rule values and balance choices as configuration, with reproducible simulations to assess changes. Improve tactical automation, transfer decisions and scoring distributions through documented changes rather than hidden edition-specific branches. + +## 0.4: adaptable interfaces and competitions + +Add a scalable interface through the shared application/protocol boundary. Make league sizes and competition structures data-driven. Define content-pack formats for independently licensed artwork, names and other resources; do not distribute third-party material without permission. + +## 0.5: independently distributable content + +Provide original or freely licensed graphics, sound and generated football worlds so that OpenBMH can be played without proprietary game data. Support editors, new competitions and multiplayer clients built on the same engine interfaces. + +The typed model and open format are prerequisites for flexible competitions, configurable rules and new content. See [architecture](architecture.md) for the current boundaries and [compatibility decisions](COMPATIBILITY.md) for intentional departures. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..1180b4a --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,39 @@ +# Architecture + +OpenBMH is a C++20 engine with graphical and console frontends. The implementation reads externally supplied game data; it does not execute the original program. See [file formats](formats/README.md) for the compatibility representations and [roadmap](ROADMAP.md) for the planned typed model. + +## Layers + +| Directory | Responsibility | +|---|---| +| `src/formats` | Binary readers, explicit-width records, palettes, fonts, images, text, executable-data loading and save containers | +| `src/game` | Game state, random generators, career setup, scheduling, match simulation, accounting and weekly/monthly/seasonal progression | +| `src/app` | CareerSession, shared actions, revisions, ownership, transactional publication and rollback | +| `src/ui` | View projections, rendering and input interpretation for game screens | +| `src/cli` | Command language, structured protocol, console windows and multi-client seat routing | +| `src/audio` | Bank decoding, synthesis, playback and cues, without authority to change gameplay | +| `src/launch` | Locating user data, archive extraction, edition normalisation and file selection | + +`bmhcore` contains the format and game layers. `bmhui`, `openbmh_audio` and the application session provide reusable pieces above it. Frontends should translate actions and display results; they should not introduce independent transfer, calendar or financial rules. + +## Session boundary + +`CareerSession` owns the live game, the two random streams and progression state. Requests identify the manager and the revision they observed. Shared actions validate that identity, stage state and random effects, and publish supported results together. Rejected requests must not leave partial transactions. + +Some calendar operations need synchronous human decisions. Their presenters own a staged state until the question or editor returns. A console worker hands control to the input thread while paused; exactly one thread operates on that transaction at a time. Cancellation, failure and process shutdown must release the owner and preserve the transaction's rollback contract. A view must not read live state as though it were the paused staged state. + +## Calendar and matches + +The turn driver moves between manager desks, match clocks and calendar events. Weekly, monthly and seasonal processing can produce decisions as well as simulation results. Match groups contain the day's competitions; a manager can intervene only in a group involving that manager's team. A multi-client match clock advances at a barrier shared by all seats. + +## Compatibility state + +The current game model combines interpreted vectors with fixed-layout compatibility blocks. Identifiers are not interchangeable: a club's stable identity, current runtime team index, squad row and player id represent different things. Guard each at its boundary. Fixed offsets belong to file/layout code; preserve integer widths and signedness when porting calculations. + +Legacy saves serialize blocks in a fixed order and store name pools separately. Runtime UI owners, pending input and frontend capabilities are not additional save fields. See [FBM](formats/FBM.md), [state records](formats/STATE.md) and [RNG](RNG.md). + +## Public interfaces and validation + +The [console reference](CLI_CONCEPT/README.md) documents window commands. [protocol.md](protocol.md) describes structured requests, and [CONSOLE_CLIENTS.md](CONSOLE_CLIENTS.md) explains safe client ownership and batching. Prefer shared projections/actions when adding another frontend. + +Use synthetic data for public tests and locally supplied installations only for data-dependent checks. Renderer tests, simulation tests and target-platform runtime checks answer different questions; document what each validates. See [CONTRIBUTING.md](../CONTRIBUTING.md). diff --git a/docs/formats/COL.md b/docs/formats/COL.md new file mode 100644 index 0000000..04b9128 --- /dev/null +++ b/docs/formats/COL.md @@ -0,0 +1,7 @@ +# Palette: `M3PC.COL` + +The file contains 256 RGB triplets: 768 bytes, with each channel a six-bit VGA DAC value. `load_palette` in `src/formats/palette.cpp` requires at least that size and ignores trailing data. + +A channel is masked with `0x3f` and expanded to eight bits using `(v * 255 + 31) / 63`. Rendering uses opaque alpha unless the drawing operation supplies transparency separately. No palette index is inherently transparent. + +Some [VGA](VGA.md) images supply a separate palette. The same channel conversion applies. `Palette::nearest` is an implementation helper for colour matching, not an additional file field. diff --git a/docs/formats/CONFIG.md b/docs/formats/CONFIG.md new file mode 100644 index 0000000..a6ac7eb --- /dev/null +++ b/docs/formats/CONFIG.md @@ -0,0 +1,11 @@ +# Legacy installation configuration + +`SOUND.CFG` and `PFAD.MAN` belong to the DOS installation. OpenBMH uses host SDL audio and its data-directory configuration instead of DOS ports, IRQs, DMA channels or path-prefix files. + +## `SOUND.CFG` + +The 30-byte file begins with the nine-byte `ALPTRAUM!` signature. A marker byte and two words precede two eight-byte device records. Each record contains four little-endian words representing the enabled state and legacy Sound Blaster configuration. These values describe the old machine, not valid SDL device settings. + +## `PFAD.MAN` + +This short legacy text file supplies a DOS path prefix. OpenBMH accepts a game location through startup selection or `--data`. Do not copy machine-specific DOS configuration into a new OpenBMH configuration file. diff --git a/docs/formats/EIN.md b/docs/formats/EIN.md new file mode 100644 index 0000000..411f747 --- /dev/null +++ b/docs/formats/EIN.md @@ -0,0 +1,7 @@ +# Switch settings: `.EIN` and saved settings + +The legacy settings block is 180 bytes: twenty rows of nine bytes, without a header or encryption. The same block is retained in [FBM](FBM.md). OpenBMH's settings actions operate on the career's block; standalone `.EIN` import is not the save mechanism. + +Rows are indexed 0–19 and columns 0–8 in code. On-screen row letters and one-based column labels are presentation conventions. For supported boolean cells, zero means enabled and one means disabled. Some cells carry high-bit flags, reserved values or numeric settings; do not normalise the whole block to booleans. + +`src/game/state.hpp`, the settings action implementation and the settings projection define supported cells and their bounds. Availability can also depend on the current frontend's audio capabilities. A failed audio device is not represented by rewriting the stored music preference. Clients should use the projected availability and normal actions rather than editing raw settings bytes. diff --git a/docs/formats/EXECUTABLE_LAYOUT.md b/docs/formats/EXECUTABLE_LAYOUT.md new file mode 100644 index 0000000..ab4da9a --- /dev/null +++ b/docs/formats/EXECUTABLE_LAYOUT.md @@ -0,0 +1,1985 @@ +# Executable and runtime layout constants + +OpenBMH reads the executable image supplied with the user's game installation. +The compatibility adapters bind fields in that image's loaded address space. +The declarations in [`executable_layout.hpp`](../../src/formats/executable_layout.hpp) +name format locations and test fixture bounds; they contain no game resources. + +The adapter uses the German-format layout internally. English image fields are +translated into that layout. The values below are data locations or bounds, +not callable functions. Structure-relative offsets and bit masks remain separate. + +Each declaration uses `inline constexpr auto` with the original integer spelling +and suffix. This preserves signedness, expression typing and constant-expression +use. Do not replace these with a single integer type without checking call sites. + +`LayoutTranslation` names identify relocation-table fields read from the selected +image. Ordinal suffixes distinguish fields; they do not encode addresses. `Fixture` +and `Synthetic` names describe test setup, including arbitrary synthetic workspace +locations and buffer sizes; they are not additional original-game layout claims. + +Generated by `tools/public_release/collect_layout.py`. Update this table when +declarations change. Game text, resort, image and audio fallbacks belong outside it. + +| Constant | Literal | Use | +|---|---|---| +| `Achievements_Fill_ExecutableField` | `0xae090` | German-compatible image / runtime field | +| `Achievements_Fill_ExecutableField2` | `0xae094` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField` | `0xa2229` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField2` | `0xa3c70` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField3` | `0xa3c71` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField4` | `0xa3c7a` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField4Unsigned` | `0xa3c7aU` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField5` | `0xa3c7b` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField5Unsigned` | `0xa3c7bU` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField6` | `0xa3c7c` | German-compatible image / runtime field | +| `Achievements_Fill_RuntimeField6Unsigned` | `0xa3c7cU` | German-compatible image / runtime field | +| `Achievements_Fill_TextPointer` | `0xaf09c` | German-compatible image / runtime field | +| `Achievements_FormatError_ExecutableField` | `0xa10f4` | German-compatible image / runtime field | +| `Achievements_FormatError_RuntimeField` | `0xa10f6` | German-compatible image / runtime field | +| `Achievements_FormatError_RuntimeField2` | `0xa245b` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer` | `0xa10f7` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer2` | `0xae098` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer3` | `0xae6c8` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer4` | `0xaf08c` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer5` | `0xaf090` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer6` | `0xaf098` | German-compatible image / runtime field | +| `Achievements_FormatError_TextPointer7` | `0xaf0a0` | German-compatible image / runtime field | +| `ActiveManager` | `0xafb59` | German-compatible image / runtime field | +| `ActiveSelectors` | `0xa25b0` | German-compatible image / runtime field | +| `AdGroupId` | `0xa2218` | German-compatible image / runtime field | +| `AdditionalLeagueStrengthRanges` | `0xa2c27` | German-compatible image / runtime field | +| `AdditionalStadiumPrices` | `0xa3751` | German-compatible image / runtime field | +| `Advertising_Button_RuntimeField` | `0xa435e` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField` | `0xa43ea` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField2` | `0xa441a` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField3` | `0xa4904` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField4` | `0xa492c` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField5` | `0xa4954` | German-compatible image / runtime field | +| `Advertising_Click_RuntimeField6` | `0xa497c` | German-compatible image / runtime field | +| `Advertising_FormatError_ExecutableField` | `0xa157e` | German-compatible image / runtime field | +| `Advertising_FormatError_ExecutableField2` | `0xa1581` | German-compatible image / runtime field | +| `Advertising_FormatError_ExecutableField3` | `0xae2a8` | German-compatible image / runtime field | +| `Advertising_FormatError_RuntimeField` | `0xa48fc` | German-compatible image / runtime field | +| `Advertising_FormatError_RuntimeField2` | `0xa48fe` | German-compatible image / runtime field | +| `Advertising_FormatError_RuntimeField3` | `0xa4900` | German-compatible image / runtime field | +| `Advertising_FormatError_RuntimeField4` | `0xa4902` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer` | `0xa157c` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer10` | `0xae26c` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer11` | `0xae270` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer12` | `0xae274` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer13` | `0xae278` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer14` | `0xae27c` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer15` | `0xae280` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer16` | `0xae284` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer17` | `0xaea98` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer18` | `0xaeb14` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer19` | `0xaeec0` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer2` | `0xae048` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer20` | `0xaeec4` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer21` | `0xaeec8` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer3` | `0xae04c` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer4` | `0xae050` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer5` | `0xae054` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer6` | `0xae25c` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer7` | `0xae260` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer8` | `0xae264` | German-compatible image / runtime field | +| `Advertising_FormatError_TextPointer9` | `0xae268` | German-compatible image / runtime field | +| `Advertising_OriginalShareAdjustment_RuntimeField` | `0xac7c4` | German-compatible image / runtime field | +| `Advertising_PatternRect_RuntimeField` | `0xa3357` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField` | `0xa4920` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField2` | `0xa4948` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField3` | `0xa4970` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField4` | `0xa4998` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField5` | `0xa49a4` | German-compatible image / runtime field | +| `Advertising_Render_RuntimeField6` | `0xa49a9` | German-compatible image / runtime field | +| `Advertising_String_ExecutableField` | `0xa1585` | German-compatible image / runtime field | +| `Advertising_Text_RuntimeField` | `0xa388a` | German-compatible image / runtime field | +| `Advertising_Text_RuntimeField2` | `0xa3b93` | German-compatible image / runtime field | +| `Advertising_Text_RuntimeField2Unsigned` | `0xa3b93u` | German-compatible image / runtime field | +| `Advertising_Text_RuntimeFieldUnsigned` | `0xa388au` | German-compatible image / runtime field | +| `AlltimeTable_AlltimeTableFromGame_RuntimeField` | `0xa396a` | German-compatible image / runtime field | +| `AlltimeTable_Layout_ExecutableField` | `0xa3963` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField` | `0xa1030` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField2` | `0xa1033` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField3` | `0xa1036` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField4` | `0xa1038` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField5` | `0xa103a` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField6` | `0xa103d` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField7` | `0xa1042` | German-compatible image / runtime field | +| `AlltimeTable_Render_ExecutableField8` | `0xa1044` | German-compatible image / runtime field | +| `AlltimeTable_TeamColor_RuntimeField` | `0xa509f` | German-compatible image / runtime field | +| `AlternateEventRoll` | `0xa3649` | German-compatible image / runtime field | +| `Analytics_FormatError_ExecutableField` | `0xa21d0` | German-compatible image / runtime field | +| `Analytics_FormatError_RuntimeField` | `0xa39a4` | German-compatible image / runtime field | +| `Analytics_FormatError_RuntimeField2` | `0xa39b6` | German-compatible image / runtime field | +| `Analytics_FormatError_RuntimeField3` | `0xa39d8` | German-compatible image / runtime field | +| `Analytics_FormatError_RuntimeField4` | `0xa3a20` | German-compatible image / runtime field | +| `Analytics_Render_RuntimeField` | `0xa39aa` | German-compatible image / runtime field | +| `Analytics_Render_RuntimeField2` | `0xa39ae` | German-compatible image / runtime field | +| `Analytics_Render_RuntimeField3` | `0xa39c8` | German-compatible image / runtime field | +| `Analytics_SourceAssetMaskE_RuntimeField` | `0xbd710` | German-compatible image / runtime field | +| `Analytics_SourceAssetMaskE_RuntimeFieldUnsigned` | `0xbd710u` | German-compatible image / runtime field | +| `Audio_MatchSoundEnabled_RuntimeField` | `0xa24fb` | German-compatible image / runtime field | +| `Audio_OriginalAudioAssets_RuntimeField` | `0xa5545` | German-compatible image / runtime field | +| `Audio_OriginalAudioAssets_RuntimeField2` | `0xa9c41` | German-compatible image / runtime field | +| `Audio_OriginalAudioOptions_ExecutableField` | `0xa24fc` | German-compatible image / runtime field | +| `Audio_OriginalAudioOptions_ExecutableField2` | `0xa24fd` | German-compatible image / runtime field | +| `AutomaticTakersLabel` | `0x80ce3` | English image adapter | +| `BalancePlan_BalanceFromGame_ExecutableField` | `0xaec1c` | German-compatible image / runtime field | +| `BalancePlan_BalanceFromGame_RuntimeField` | `0xafb6b` | German-compatible image / runtime field | +| `BalancePlan_BalanceFromGame_RuntimeField2` | `0xbd102` | German-compatible image / runtime field | +| `BalancePlan_BalanceFromGame_TextPointer` | `0xaec20` | German-compatible image / runtime field | +| `BalancePlan_BalanceFromGame_TextPointer2` | `0xaec24` | German-compatible image / runtime field | +| `BalancePlan_DrawButtons_TextPointer` | `0xade30` | German-compatible image / runtime field | +| `BalancePlan_DrawButtons_TextPointer2` | `0xaec0c` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_RuntimeField` | `0xa485a` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_RuntimeField2` | `0xa485b` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer` | `0xa1521` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer2` | `0xa485c` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer3` | `0xade10` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer4` | `0xade18` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer5` | `0xaea44` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer6` | `0xaec10` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer7` | `0xaec14` | German-compatible image / runtime field | +| `BalancePlan_DrawRows_TextPointer8` | `0xaec18` | German-compatible image / runtime field | +| `BalancePlan_Fill_TextPointer` | `0xaec08` | German-compatible image / runtime field | +| `BankCredit_BankCreditContext_RuntimeField` | `0xa1434` | German-compatible image / runtime field | +| `BankCredit_BankCreditContext_RuntimeField2` | `0xa1438` | German-compatible image / runtime field | +| `BankCredit_BankCreditContext_RuntimeField3` | `0xa44f6` | German-compatible image / runtime field | +| `Bank_DrawCreditFeeConfirmation_ExecutableField` | `0xaf220` | German-compatible image / runtime field | +| `Bank_DrawCreditFeeConfirmation_ExecutableField2` | `0xaf224` | German-compatible image / runtime field | +| `Bank_DrawPropertyCard_TextPointer` | `0xa1414` | German-compatible image / runtime field | +| `Bank_DrawPropertyCard_TextPointer2` | `0xaf1d0` | German-compatible image / runtime field | +| `Bank_DrawPropertyCard_TextPointer3` | `0xaf1d4` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField` | `0xa447d` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField2` | `0xa448d` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField3` | `0xa44a1` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField4` | `0xa44a9` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField5` | `0xa44be` | German-compatible image / runtime field | +| `Bank_FinishCredit_RuntimeField6` | `0xa44c2` | German-compatible image / runtime field | +| `Bank_FormatError_ExecutableField` | `0xa140f` | German-compatible image / runtime field | +| `Bank_FormatError_ExecutableField2` | `0xae308` | German-compatible image / runtime field | +| `Bank_FormatError_ExecutableField3` | `0xaf1fc` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField` | `0xa44b1` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField10` | `0xa44e7` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField11` | `0xa44ea` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField12` | `0xa44ed` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField13` | `0xa44f0` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField14` | `0xa44f3` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField15` | `0xa4527` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField16` | `0xa452b` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField17` | `0xa452f` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField18` | `0xae0fc` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField19` | `0xae338` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField2` | `0xa44b2` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField3` | `0xa44d2` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField4` | `0xa44d5` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField5` | `0xa44d8` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField6` | `0xa44db` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField7` | `0xa44de` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField8` | `0xa44e1` | German-compatible image / runtime field | +| `Bank_FormatError_RuntimeField9` | `0xa44e4` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer` | `0xaf1e4` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer2` | `0xaf1e8` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer3` | `0xaf1ec` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer4` | `0xaf1f4` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer5` | `0xaf1f8` | German-compatible image / runtime field | +| `Bank_FormatError_TextPointer6` | `0xaf200` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField` | `0xa1408` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField2` | `0xa1412` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField3` | `0xa1417` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField4` | `0xa1419` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField5` | `0xa160c` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField6` | `0xa160e` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_ExecutableField7` | `0xa1610` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField` | `0xa2188` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField2` | `0xa44b5` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField3` | `0xa44bc` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField4` | `0xa44cb` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField5` | `0xac7b4` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_RuntimeField6` | `0xae34c` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer` | `0xa1410` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer2` | `0xa141e` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer3` | `0xae368` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer4` | `0xae380` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer5` | `0xaf1f0` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer6` | `0xaf204` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer7` | `0xaf208` | German-compatible image / runtime field | +| `Bank_OriginalToUtf8_TextPointer8` | `0xaf20c` | German-compatible image / runtime field | +| `CalendarDay` | `0xbb254` | German-compatible image / runtime field | +| `CalendarFirstLeague` | `0xa2c12` | German-compatible image / runtime field | +| `CalendarLeagueCounts` | `0xa2c0a` | German-compatible image / runtime field | +| `CalendarState_CalendarFromGame_ExecutableField` | `0xa24ea` | German-compatible image / runtime field | +| `CalendarState_CalendarFromGame_ExecutableField2` | `0xa24f5` | German-compatible image / runtime field | +| `CalendarState_FormatError_RuntimeField` | `0xa258b` | German-compatible image / runtime field | +| `CalendarState_FormatError_RuntimeField2` | `0xa2594` | German-compatible image / runtime field | +| `CalendarState_FormatError_RuntimeField2Unsigned` | `0xa2594u` | German-compatible image / runtime field | +| `CalendarState_FormatError_RuntimeField3` | `0xafae6` | German-compatible image / runtime field | +| `Calendar_Information_ExecutableField` | `0xa114c` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer` | `0xa114f` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer2` | `0xae6f8` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer3` | `0xaf0c8` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer4` | `0xaf0cc` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer5` | `0xaf0d0` | German-compatible image / runtime field | +| `Calendar_Information_TextPointer6` | `0xaf0d4` | German-compatible image / runtime field | +| `Calendar_Render_ExecutableField2Unsigned` | `0xaf0c0U` | German-compatible image / runtime field | +| `Calendar_Render_ExecutableField3Unsigned` | `0xaf0c4U` | German-compatible image / runtime field | +| `Calendar_Render_ExecutableFieldUnsigned` | `0xaf0bcU` | German-compatible image / runtime field | +| `Calendar_Render_TextPointer` | `0xae0c0` | German-compatible image / runtime field | +| `Calendar_Render_TextPointer2` | `0xae448` | German-compatible image / runtime field | +| `CareerDuration` | `0xbdb76` | German-compatible image / runtime field | +| `CareerDurationUnsigned` | `0xbdb76u` | German-compatible image / runtime field | +| `CareerSession_AdvanceLeagueFamily_ExecutableField` | `0xafb5b` | German-compatible image / runtime field | +| `CareerSession_AdvertisingSessionUnchanged_ExecutableField` | `0xafb5e` | German-compatible image / runtime field | +| `CareerSession_AnyOf_ExecutableField` | `0xb5eb4` | German-compatible image / runtime field | +| `CareerSession_AnyOf_ExecutableFieldUnsigned` | `0xb5eb4u` | German-compatible image / runtime field | +| `CareerSession_ApplyBalanceSourceStyle_ExecutableField` | `0xbdac4` | German-compatible image / runtime field | +| `CareerSession_BeginFriendlyOpponentTable_ExecutableField` | `0xa4548` | German-compatible image / runtime field | +| `CareerSession_BeginFriendlyOpponentTable_ExecutableField2` | `0xbb46e` | German-compatible image / runtime field | +| `CareerSession_BeginFriendlyOpponentTable_RuntimeField` | `0xa2bc4` | German-compatible image / runtime field | +| `CareerSession_BeginFriendlyOpponentTable_RuntimeField2` | `0xafb5c` | German-compatible image / runtime field | +| `CareerSession_CloseLeagueFamily_ExecutableField` | `0xbb138` | German-compatible image / runtime field | +| `CareerSession_CurrentLeagueTableDispatch_ExecutableField` | `0xaec80` | German-compatible image / runtime field | +| `CareerSession_CurrentLeagueTableDispatch_ExecutableField2` | `0xaec84` | German-compatible image / runtime field | +| `CareerSession_DataDirectory_RuntimeField` | `0xa2c3e` | German-compatible image / runtime field | +| `CareerSession_DataDirectory_RuntimeField2` | `0xa2c42` | German-compatible image / runtime field | +| `CareerSession_DataDirectory_RuntimeField3` | `0xa2c52` | German-compatible image / runtime field | +| `CareerSession_DataDirectory_RuntimeField4` | `0xa2c66` | German-compatible image / runtime field | +| `CareerSession_DispatchDesktopLayout_RuntimeField` | `0xa250e` | German-compatible image / runtime field | +| `CareerSession_DispatchDesktopLayout_RuntimeField2` | `0xa2517` | German-compatible image / runtime field | +| `CareerSession_DispatchLeagueTableControl_RuntimeField` | `0xa454d` | German-compatible image / runtime field | +| `CareerSession_DispatchLeagueTableControl_RuntimeField2` | `0xbb834` | German-compatible image / runtime field | +| `CareerSession_DispatchLineup_RuntimeField` | `0xa2c30` | German-compatible image / runtime field | +| `CareerSession_DispatchLiveSubstitution_ExecutableField` | `0xa366c` | German-compatible image / runtime field | +| `CareerSession_DispatchLiveTactic_RuntimeField` | `0xa20eb` | German-compatible image / runtime field | +| `CareerSession_DispatchLiveTactic_RuntimeField2` | `0xa20f3` | German-compatible image / runtime field | +| `CareerSession_DispatchLiveTactic_RuntimeField3` | `0xa2504` | German-compatible image / runtime field | +| `CareerSession_DispatchOtherGames_RuntimeField` | `0xbb13c` | German-compatible image / runtime field | +| `CareerSession_DispatchPoachUi_ExecutableField` | `0xbbcde` | German-compatible image / runtime field | +| `CareerSession_DispatchPoachUi_ExecutableFieldUnsigned` | `0xbbcdeu` | German-compatible image / runtime field | +| `CareerSession_DispatchPoachUi_TextPointer` | `0xaf260` | German-compatible image / runtime field | +| `CareerSession_DispatchPoachUi_TextPointer2` | `0xaf268` | German-compatible image / runtime field | +| `CareerSession_DispatchPoachUi_TextPointer3` | `0xaf27c` | German-compatible image / runtime field | +| `CareerSession_DispatchSettings_RuntimeField` | `0xa2309` | German-compatible image / runtime field | +| `CareerSession_DispatchSettings_TextPointer` | `0xaeb50` | German-compatible image / runtime field | +| `CareerSession_DispatchSettings_TextPointer2` | `0xaeb54` | German-compatible image / runtime field | +| `CareerSession_DispatchStadium_RuntimeField` | `0xa36d1` | German-compatible image / runtime field | +| `CareerSession_DispatchStadium_RuntimeField2` | `0xa37e5` | German-compatible image / runtime field | +| `CareerSession_DispatchStrengths_ExecutableField` | `0xa253d` | German-compatible image / runtime field | +| `CareerSession_DispatchStrengths_ExecutableField2` | `0xbbcd4` | German-compatible image / runtime field | +| `CareerSession_DispatchStrengths_ExecutableField3` | `0xbbcd5` | German-compatible image / runtime field | +| `CareerSession_DispatchStrengths_ExecutableField4` | `0xbbcd6` | German-compatible image / runtime field | +| `CareerSession_DispatchStrengths_ExecutableField5` | `0xbbcd7` | German-compatible image / runtime field | +| `CareerSession_DispatchToto_RuntimeField` | `0xbdb95` | German-compatible image / runtime field | +| `CareerSession_DispatchTransferOffer_ExecutableField` | `0xbbcdd` | German-compatible image / runtime field | +| `CareerSession_DispatchTransferOffer_ExecutableField2` | `0xbbce1` | German-compatible image / runtime field | +| `CareerSession_DispatchTransferOffer_ExecutableField2Unsigned` | `0xbbce1u` | German-compatible image / runtime field | +| `CareerSession_DispatchTransferOffer_ExecutableFieldUnsigned` | `0xbbcddu` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField` | `0xb5f7c` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField2` | `0xbbcc0` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField3` | `0xbd900` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField4` | `0xbd901` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField5` | `0xbdac5` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField6` | `0xbdac6` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField7` | `0xbdac7` | German-compatible image / runtime field | +| `CareerSession_FormatError_ExecutableField8` | `0xbdb8b` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField` | `0xa24fe` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField2` | `0xa2546` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField3` | `0xa25b4` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField4` | `0xa2c1b` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField5` | `0xa3fd4` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField6` | `0xa5057` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField7` | `0xa509d` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField8` | `0xbb83f` | German-compatible image / runtime field | +| `CareerSession_FormatError_RuntimeField9` | `0xbd8ec` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer` | `0xa1466` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer2` | `0xadf74` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer3` | `0xaec88` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer4` | `0xaec8c` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer5` | `0xaeca4` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer6` | `0xaef50` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer7` | `0xaef54` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer8` | `0xaef7c` | German-compatible image / runtime field | +| `CareerSession_FormatError_TextPointer9` | `0xaef80` | German-compatible image / runtime field | +| `CareerSession_FormatNumber_ExecutableField` | `0xa1373` | German-compatible image / runtime field | +| `CareerSession_FormatNumber_ExecutableField2` | `0xa1380` | German-compatible image / runtime field | +| `CareerSession_FormatNumber_TextPointer` | `0xa137e` | German-compatible image / runtime field | +| `CareerSession_InitializeClubModalRuntime_ExecutableField` | `0xa25c0` | German-compatible image / runtime field | +| `CareerSession_InitializeClubModalRuntime_ExecutableFieldUnsigned` | `0xa25c0u` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField` | `0xa2be9` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField2` | `0xa2bf2` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField3` | `0xa2c00` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField4` | `0xa2c0b` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField5` | `0xa2c13` | German-compatible image / runtime field | +| `CareerSession_InstallLeagueSizes_RuntimeField6` | `0xa2c34` | German-compatible image / runtime field | +| `CareerSession_Int32T_TextPointer` | `0xaeffc` | German-compatible image / runtime field | +| `CareerSession_Int32T_TextPointer2` | `0xaf21c` | German-compatible image / runtime field | +| `CareerSession_Int32T_TextPointer3` | `0xaf228` | German-compatible image / runtime field | +| `CareerSession_Int32T_TextPointer4` | `0xaf22c` | German-compatible image / runtime field | +| `CareerSession_Int32T_TextPointer5` | `0xaf230` | German-compatible image / runtime field | +| `CareerSession_Invalid_RuntimeField` | `0xa42f9` | German-compatible image / runtime field | +| `CareerSession_Invalid_RuntimeField2` | `0xbbcd8` | German-compatible image / runtime field | +| `CareerSession_LiveBoundaryFamilyScope_ExecutableField` | `0xbdb84` | German-compatible image / runtime field | +| `CareerSession_Name_TextPointer` | `0xaf100` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField` | `0xa24eb` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField2` | `0xbb46c` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField3` | `0xbb46d` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField4` | `0xbb836` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField5` | `0xbb837` | German-compatible image / runtime field | +| `CareerSession_PairingsRuntimeDraw_ExecutableField6` | `0xbb841` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer` | `0xaed10` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer2` | `0xaed14` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer3` | `0xaed18` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer4` | `0xaed1c` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer5` | `0xaed24` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer6` | `0xaed28` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer7` | `0xaed30` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer8` | `0xaed34` | German-compatible image / runtime field | +| `CareerSession_Reject_TextPointer9` | `0xaed38` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_ExecutableField` | `0xa28c2` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_ExecutableField2` | `0xa290a` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_ExecutableField3` | `0xa2982` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_RuntimeField` | `0xa295a` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_RuntimeField2` | `0xa296a` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_RuntimeField3` | `0xa29c2` | German-compatible image / runtime field | +| `CareerSession_RuntimeError_RuntimeField4` | `0xafb60` | German-compatible image / runtime field | +| `CareerSession_Save_RuntimeField` | `0xaf974` | German-compatible image / runtime field | +| `CareerSession_SportschauSourceOptions_ExecutableField` | `0xa5088` | German-compatible image / runtime field | +| `Career_BuildStadium_RuntimeField` | `0xa3771` | German-compatible image / runtime field | +| `Career_BuildStadium_RuntimeField2` | `0xa37e6` | German-compatible image / runtime field | +| `Career_BuildStadium_RuntimeField3` | `0xa37e7` | German-compatible image / runtime field | +| `Career_BuildStadium_RuntimeField4` | `0xa50d0` | German-compatible image / runtime field | +| `Career_CareerAddManager_ExecutableField` | `0xa50d4` | German-compatible image / runtime field | +| `Career_CareerAddManager_RuntimeField` | `0xa252d` | German-compatible image / runtime field | +| `Career_CareerAddManager_RuntimeField2` | `0xbd4bc` | German-compatible image / runtime field | +| `Career_CareerManagersEnd_RuntimeField` | `0xbb86c` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField` | `0xa2c76` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField10` | `0xa2fbe` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField11` | `0xa2fda` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField12` | `0xa2fe6` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField13` | `0xa3002` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField14` | `0xa300e` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField15` | `0xa302a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField16` | `0xa3036` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField17` | `0xa311a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField18` | `0xa3126` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField19` | `0xb5e34` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField19Unsigned` | `0xb5e34u` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField2` | `0xa2ec2` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField20` | `0xb5eac` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField21` | `0xb5ebc` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField22` | `0xb5efc` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField23` | `0xb5f8c` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField24` | `0xb609c` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField25` | `0xb6134` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField25Unsigned` | `0xb6134u` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField26` | `0xb623c` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField27` | `0xb6278` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField28` | `0xbb144` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField29` | `0xbb16c` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField3` | `0xa2ece` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField30` | `0xbb190` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField31` | `0xbb464` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField4` | `0xa2ed2` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField5` | `0xa2eea` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField6` | `0xa2f8a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField7` | `0xa2f96` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField8` | `0xa2f9a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_ExecutableField9` | `0xa2fb2` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField` | `0x776a8` | English image adapter | +| `Career_CompetitionPointersEnglish_RuntimeField10` | `0xa3bb8` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField11` | `0xa3bb9` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField12` | `0xa3bca` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField13` | `0xb6034` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField14` | `0xbb180` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField14Unsigned` | `0xbb180u` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField15` | `0xbb1d0` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField16` | `0xbb1e8` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField17` | `0xbb310` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField18` | `0xbb3a8` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField2` | `0xa2e7a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField3` | `0xa2e9a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField4` | `0xa2ea6` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField5` | `0xa2ef6` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField6` | `0xa2f3a` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField7` | `0xa2f46` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField8` | `0xa2f62` | German-compatible image / runtime field | +| `Career_CompetitionPointersEnglish_RuntimeField9` | `0xa2f6e` | German-compatible image / runtime field | +| `Career_CompetitionPointers_ExecutableField` | `0xbb3dc` | German-compatible image / runtime field | +| `Career_CompetitionPointers_RuntimeField` | `0xa31e2` | German-compatible image / runtime field | +| `Career_CompetitionPointers_RuntimeField2` | `0xa31ea` | German-compatible image / runtime field | +| `Career_CompetitionPointers_RuntimeField3` | `0xa31ee` | German-compatible image / runtime field | +| `Career_CompetitionPointers_RuntimeField4` | `0xa3bc0` | German-compatible image / runtime field | +| `Career_CompetitionPointers_RuntimeField5` | `0xa3bc5` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableField` | `0xbb839` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableField2` | `0xbb83a` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableField2Unsigned` | `0xbb83au` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableField3` | `0xbb83e` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableField3Unsigned` | `0xbb83eu` | German-compatible image / runtime field | +| `Career_EuropeanClub_ExecutableFieldUnsigned` | `0xbb839u` | German-compatible image / runtime field | +| `Career_GermanRoundTable_ExecutableField` | `0x6ee40` | English image adapter | +| `Career_GermanRoundTable_ExecutableField2` | `0x6eea0` | English image adapter | +| `Career_GermanRoundTable_ExecutableField3` | `0x6eed4` | English image adapter | +| `Career_GermanRoundTable_ExecutableField4` | `0x6f0bc` | English image adapter | +| `Career_NewCareerMarketsAndMoods_ExecutableField` | `0xaeaf8` | German-compatible image / runtime field | +| `Career_NewCareerMarketsAndMoods_ExecutableField2` | `0xaeafc` | German-compatible image / runtime field | +| `Career_NewCareerMarketsAndMoods_ExecutableField3` | `0xaeb00` | German-compatible image / runtime field | +| `Career_NewCareerMarketsAndMoods_ExecutableField4` | `0xaeb04` | German-compatible image / runtime field | +| `Career_NewCareerMarketsAndMoods_RuntimeField` | `0xb1de4` | German-compatible image / runtime field | +| `Career_NewCareerMarketsAndMoods_RuntimeField2` | `0xbb140` | German-compatible image / runtime field | +| `Career_Put_ExecutableField3` | `0xbb4d3` | German-compatible image / runtime field | +| `Career_RemoveJoinLoans_RuntimeField` | `0xab908` | German-compatible image / runtime field | +| `Career_RemoveJoinTransfers_RuntimeField` | `0xbb7a4` | German-compatible image / runtime field | +| `ChampionshipBonusText` | `0xa1534` | German-compatible image / runtime field | +| `ClubAuxiliaryBytes` | `0xba3b8` | German-compatible image / runtime field | +| `ClubAuxiliaryWords` | `0xba3bc` | German-compatible image / runtime field | +| `ClubBadgeSelectors` | `0xba378` | German-compatible image / runtime field | +| `ClubIdentities` | `0xba388` | German-compatible image / runtime field | +| `ClubInfo_FormatError_RuntimeField` | `0xbb884` | German-compatible image / runtime field | +| `ClubInfo_FormatError_RuntimeField2` | `0xbbcb0` | German-compatible image / runtime field | +| `ClubInfo_Raw_ExecutableField` | `0xa1160` | German-compatible image / runtime field | +| `ClubInfo_Raw_ExecutableField2` | `0xa1173` | German-compatible image / runtime field | +| `ClubInfo_Raw_RuntimeField` | `0xa4bc1` | German-compatible image / runtime field | +| `ClubInfo_Raw_RuntimeField2` | `0xa4bc3` | German-compatible image / runtime field | +| `ClubInfo_Raw_RuntimeField3` | `0xa4f8e` | German-compatible image / runtime field | +| `ClubInfo_Raw_TextPointer` | `0xae138` | German-compatible image / runtime field | +| `ClubInfo_Raw_TextPointer2` | `0xae13c` | German-compatible image / runtime field | +| `ClubInfo_Raw_TextPointer3` | `0xae140` | German-compatible image / runtime field | +| `ClubInfo_Render_ExecutableField` | `0xa1165` | German-compatible image / runtime field | +| `ClubInfo_Render_ExecutableField2` | `0xa1168` | German-compatible image / runtime field | +| `ClubInfo_Render_ExecutableField3` | `0xa116b` | German-compatible image / runtime field | +| `ClubInfo_Render_ExecutableField4` | `0xa116e` | German-compatible image / runtime field | +| `ClubInfo_Render_ExecutableField5` | `0xa1170` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer` | `0xa1163` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer2` | `0xae7d4` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer3` | `0xaf160` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer4` | `0xaf164` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer5` | `0xaf168` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer6` | `0xaf244` | German-compatible image / runtime field | +| `ClubInfo_Render_TextPointer7` | `0xaf248` | German-compatible image / runtime field | +| `ClubKitSelectors` | `0xbb68b` | German-compatible image / runtime field | +| `ClubKitSelectorsUnsigned` | `0xbb68bu` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField` | `0xa25bb` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField2` | `0xa25bf` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3` | `0xa2c36` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4` | `0xa364a` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField` | `0xa2c4e` | German-compatible image / runtime field | +| `ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2` | `0xa3c9b` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField` | `0xa13d8` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField2` | `0xae008` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField3` | `0xae8c0` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField4` | `0xaecd4` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField5` | `0xaed54` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField6` | `0xaed58` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField7` | `0xaed84` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField8` | `0xaed88` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_ExecutableField9` | `0xaed98` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_RuntimeField` | `0xa4328` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer` | `0xa13dd` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer10` | `0xaed90` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer11` | `0xaed94` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer2` | `0xa13e2` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer3` | `0xadff0` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer4` | `0xae01c` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer5` | `0xae038` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer6` | `0xae890` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer7` | `0xaed50` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer8` | `0xaed80` | German-compatible image / runtime field | +| `ClubPlayerDetail_Copy_TextPointer9` | `0xaed8c` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField` | `0xa3c7d` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField2` | `0xa3c82` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField3` | `0xa3c87` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField4` | `0xa3c8c` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField5` | `0xa3c91` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField6` | `0xa3c96` | German-compatible image / runtime field | +| `ClubPlayerDetail_DrawPortrait_RuntimeField7` | `0xa3ca0` | German-compatible image / runtime field | +| `ClubPlayerDetail_InvalidArgument_RuntimeField` | `0xabce8` | German-compatible image / runtime field | +| `ClubPlayerDetail_InvalidArgument_RuntimeField2` | `0xaf43d` | German-compatible image / runtime field | +| `ClubPlayerDetail_InvalidArgument_RuntimeField3` | `0xbbce2` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_ExecutableField` | `0xaed40` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_ExecutableField2` | `0xaed44` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_ExecutableField3` | `0xaed48` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_ExecutableField4` | `0xaed4c` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer` | `0xa13da` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer10` | `0xaed78` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer11` | `0xaed7c` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer2` | `0xae014` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer3` | `0xaed5c` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer4` | `0xaed60` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer5` | `0xaed64` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer6` | `0xaed68` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer7` | `0xaed6c` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer8` | `0xaed70` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderCard_TextPointer9` | `0xaed74` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderStatistics_ExecutableField` | `0xaded8` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderStatistics_ExecutableField2` | `0xadedc` | German-compatible image / runtime field | +| `ClubPlayerDetail_RenderStatistics_ExecutableField3` | `0xaec54` | German-compatible image / runtime field | +| `ClubSeasonRecords` | `0xbb1ec` | German-compatible image / runtime field | +| `ClubShortNameOffsets` | `0xb5d24` | German-compatible image / runtime field | +| `CoachActive` | `0xa3770` | German-compatible image / runtime field | +| `CompactDialogFrame` | `0xa366e` | German-compatible image / runtime field | +| `CompetitionCalendar` | `0xa25e6` | German-compatible image / runtime field | +| `CompetitionSelection` | `0xaf440` | German-compatible image / runtime field | +| `ComputerBettingLimits` | `0xa455c` | German-compatible image / runtime field | +| `ContractExpiryWarningText` | `0xa12cd` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField` | `0xadfdc` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField10` | `0xaecd0` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField11` | `0xaecdc` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField12` | `0xaece0` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField13` | `0xaece4` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField14` | `0xaecec` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField15` | `0xaecf4` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField16` | `0xaecf8` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField17` | `0xaed08` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField18` | `0xaed0c` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField19` | `0xaed20` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField2` | `0xadfe4` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField3` | `0xadfe8` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField4` | `0xae8a4` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField5` | `0xaecbc` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField6` | `0xaecc0` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField7` | `0xaecc4` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField8` | `0xaecc8` | German-compatible image / runtime field | +| `Contracts_Out_ExecutableField9` | `0xaeccc` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer` | `0xa13dc` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer2` | `0xa430d` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer3` | `0xaecd8` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer4` | `0xaece8` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer5` | `0xaecf0` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer6` | `0xaecfc` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer7` | `0xaed00` | German-compatible image / runtime field | +| `Contracts_Out_TextPointer8` | `0xaed04` | German-compatible image / runtime field | +| `Contracts_RenderRoster_ExecutableField` | `0xa1161` | German-compatible image / runtime field | +| `Contracts_RenderRoster_ExecutableField2` | `0xa1177` | German-compatible image / runtime field | +| `Contracts_RenderRoster_ExecutableField3` | `0xa1179` | German-compatible image / runtime field | +| `Contracts_RenderRoster_ExecutableField4` | `0xa117f` | German-compatible image / runtime field | +| `Contracts_RenderRoster_TextPointer` | `0xa21b8` | German-compatible image / runtime field | +| `Contracts_RenderRoster_TextPointer2` | `0xaecb4` | German-compatible image / runtime field | +| `Contracts_RenderRoster_TextPointer3` | `0xaf16c` | German-compatible image / runtime field | +| `Contracts_RenderRoster_TextPointer4` | `0xaf170` | German-compatible image / runtime field | +| `Controller_CalendarFromGame_TextPointer` | `0xaf028` | German-compatible image / runtime field | +| `Controller_ClubFriendlyState_TextPointer` | `0xaf120` | German-compatible image / runtime field | +| `Controller_FormatError_ExecutableField` | `0xa0020` | German-compatible image / runtime field | +| `Controller_FormatError_ExecutableField2` | `0xa24fa` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeField` | `0xa2506` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeField2` | `0xa250f` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeField2Unsigned` | `0xa250fu` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeField3` | `0xa252a` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeField3Unsigned` | `0xa252au` | German-compatible image / runtime field | +| `Controller_FormatError_RuntimeFieldUnsigned` | `0xa2506u` | German-compatible image / runtime field | +| `Controller_FormatError_TextPointer` | `0xaf094` | German-compatible image / runtime field | +| `Controller_FormatError_TextPointer2` | `0xaf124` | German-compatible image / runtime field | +| `Controller_FormatError_TextPointer3` | `0xaf128` | German-compatible image / runtime field | +| `CornerTakerLabel` | `0x80cdb` | English image adapter | +| `Coupon` | `0xaf834` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer` | `0xa10f2` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer10` | `0xa145f` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer11` | `0xa1464` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer2` | `0xa1440` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer3` | `0xa1442` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer4` | `0xa1446` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer5` | `0xa1449` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer6` | `0xa144b` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer7` | `0xa1450` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer8` | `0xa1455` | German-compatible image / runtime field | +| `CupDraw_DrawGroupOverview_TextPointer9` | `0xa1456` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField` | `0xa1614` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField2` | `0xa1616` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField3` | `0xa50ac` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField4` | `0xae6dc` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField5` | `0xae704` | German-compatible image / runtime field | +| `CupDraw_FormatError_ExecutableField6` | `0xae70c` | German-compatible image / runtime field | +| `CupDraw_FormatError_RuntimeField` | `0xa2547` | German-compatible image / runtime field | +| `CupDraw_FormatError_RuntimeField2` | `0xb6ea8` | German-compatible image / runtime field | +| `CupDraw_FormatError_RuntimeField3` | `0xb9ad8` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer` | `0xa1612` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer2` | `0xa1619` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer3` | `0xa161e` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer4` | `0xae5d0` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer5` | `0xaeb08` | German-compatible image / runtime field | +| `CupDraw_FormatError_TextPointer6` | `0xaec9c` | German-compatible image / runtime field | +| `CupDraw_GroupMarker_RuntimeField` | `0xa3bb4` | German-compatible image / runtime field | +| `CupTable` | `0xa2c6a` | German-compatible image / runtime field | +| `Cup_AdvanceCup_ExecutableField` | `0xab638` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField` | `0xa2545` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField2` | `0xa301c` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField3` | `0xafb5a` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField4` | `0xafb5f` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField5` | `0xbb146` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField6` | `0xbdb0e` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField6Unsigned` | `0xbdb0eu` | German-compatible image / runtime field | +| `Cup_AdvanceCup_RuntimeField7` | `0xbdb12` | German-compatible image / runtime field | +| `Cup_MastersQualification_RuntimeField` | `0xbd41c` | German-compatible image / runtime field | +| `Cup_MastersQualification_TextPointer` | `0xaf07c` | German-compatible image / runtime field | +| `Cup_NationalTournamentEnd_RuntimeField` | `0xa2dcc` | German-compatible image / runtime field | +| `Cup_NationalTournamentEnd_RuntimeField2` | `0xa2dce` | German-compatible image / runtime field | +| `Cup_NationalTournamentEnd_RuntimeField3` | `0xa2df4` | German-compatible image / runtime field | +| `Cup_NationalTournamentEnd_RuntimeField4` | `0xa2df6` | German-compatible image / runtime field | +| `Cup_NationalTournamentEnd_RuntimeField5` | `0xbd390` | German-compatible image / runtime field | +| `Cup_PrepareFriendlies_RuntimeField` | `0xab68c` | German-compatible image / runtime field | +| `Cup_PrepareFriendlies_RuntimeField2` | `0xaf3c2` | German-compatible image / runtime field | +| `Cup_RemoveCompetition_RuntimeField` | `0xa25b1` | German-compatible image / runtime field | +| `Cup_RemoveCompetition_RuntimeField2` | `0xa25b7` | German-compatible image / runtime field | +| `CurrencyDivisor` | `0xa25bc` | German-compatible image / runtime field | +| `CurrencyMultiplier` | `0xa25b8` | German-compatible image / runtime field | +| `CurrencySuffixText` | `0xa1404` | German-compatible image / runtime field | +| `CurrentMatchday` | `0xbd8f4` | German-compatible image / runtime field | +| `DaysIntoSeason` | `0xbb468` | German-compatible image / runtime field | +| `DeskActions_CheckAdvertisingRenewal_TextPointer` | `0xae23c` | German-compatible image / runtime field | +| `DeskActions_CheckAdvertisingRenewal_TextPointer2` | `0xae240` | German-compatible image / runtime field | +| `DeskActions_CheckAdvertisingRenewal_TextPointer3` | `0xae244` | German-compatible image / runtime field | +| `DeskActions_CheckAdvertisingRenewal_TextPointer4` | `0xae248` | German-compatible image / runtime field | +| `DeskActions_CheckAdvertisingRenewal_TextPointer5` | `0xae24c` | German-compatible image / runtime field | +| `DeskActions_ConfigureTrainingCampData_RuntimeField` | `0xa23e1` | German-compatible image / runtime field | +| `DeskActions_ConfigureTrainingCampData_RuntimeField2` | `0xa2401` | German-compatible image / runtime field | +| `DeskActions_EditorFail_RuntimeField` | `0xaf977` | German-compatible image / runtime field | +| `DeskActions_EditorFail_RuntimeField2` | `0xbdb8c` | German-compatible image / runtime field | +| `DeskActions_EditorProject_ExecutableField` | `0xae8a0` | German-compatible image / runtime field | +| `DeskActions_EditorProject_ExecutableField2` | `0xaf320` | German-compatible image / runtime field | +| `DeskActions_EditorProject_RuntimeField` | `0xaf31c` | German-compatible image / runtime field | +| `DeskActions_NationalOpponentManager_RuntimeField` | `0xb9ad9` | German-compatible image / runtime field | +| `DeskActions_OpenTransferOfferEditorSource_RuntimeField` | `0xbbcdb` | German-compatible image / runtime field | +| `DeskActions_Reject_ExecutableField` | `0xaeecc` | German-compatible image / runtime field | +| `DeskActions_SubmitPoolsCoupon_RuntimeField` | `0xbda70` | German-compatible image / runtime field | +| `DeskActions_SubmitTransferBidImpl_ExecutableField` | `0xaf304` | German-compatible image / runtime field | +| `DeskActions_SubmitTransferBidImpl_RuntimeField` | `0xbb46f` | German-compatible image / runtime field | +| `DeskActions_SubmitTransferOfferEditorSource_ExecutableField` | `0xaf300` | German-compatible image / runtime field | +| `DeskActions_SubmitTransferOfferEditorSource_RuntimeField` | `0xaf2f0` | German-compatible image / runtime field | +| `DeskActions_SubmitTransferOfferEditorSource_TextPointer` | `0xaf2ec` | German-compatible image / runtime field | +| `DeskActions_Unsupported_ExecutableField` | `0xaf2f4` | German-compatible image / runtime field | +| `DeskActions_Unsupported_ExecutableField2` | `0xaf308` | German-compatible image / runtime field | +| `DeskActions_Unsupported_ExecutableField3` | `0xaf318` | German-compatible image / runtime field | +| `DeskActions_Unsupported_RuntimeField` | `0xbbcc8` | German-compatible image / runtime field | +| `DeskActions_Unsupported_RuntimeFieldUnsigned` | `0xbbcc8u` | German-compatible image / runtime field | +| `DeskActions_Unsupported_TextPointer` | `0xaf2f8` | German-compatible image / runtime field | +| `DeskActions_Unsupported_TextPointer2` | `0xaf2fc` | German-compatible image / runtime field | +| `DeskActions_Unsupported_TextPointer3` | `0xaf30c` | German-compatible image / runtime field | +| `DeskActions_Unsupported_TextPointer4` | `0xaf310` | German-compatible image / runtime field | +| `DeskActions_Unsupported_TextPointer5` | `0xaf314` | German-compatible image / runtime field | +| `DeskDrawers_Curve_ExecutableField` | `0xa187e` | German-compatible image / runtime field | +| `DeskDrawers_Curve_RuntimeField` | `0xa2bfb` | German-compatible image / runtime field | +| `DeskDrawers_HeadToHead_ExecutableField` | `0xa0009` | German-compatible image / runtime field | +| `DeskDrawers_Recent_ExecutableField` | `0xa0006` | German-compatible image / runtime field | +| `DeskDrawers_Recent_ExecutableField2` | `0xa0008` | German-compatible image / runtime field | +| `DeskDrawers_Recent_TextPointer` | `0xa0004` | German-compatible image / runtime field | +| `DeskPosition` | `0xbdb77` | German-compatible image / runtime field | +| `DeskRecords_FillRect_ExecutableField` | `0xa16a4` | German-compatible image / runtime field | +| `DeskRecords_FillRect_ExecutableField2` | `0xa16a6` | German-compatible image / runtime field | +| `DeskRecords_FillRect_ExecutableField3` | `0xa16aa` | German-compatible image / runtime field | +| `DeskRecords_FillRect_ExecutableField4` | `0xaec00` | German-compatible image / runtime field | +| `DeskRecords_FillRect_ExecutableField5` | `0xaec04` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer` | `0xa169f` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer2` | `0xa16a7` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer3` | `0xa16b3` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer4` | `0xaebf4` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer5` | `0xaebf8` | German-compatible image / runtime field | +| `DeskRecords_FillRect_TextPointer6` | `0xaebfc` | German-compatible image / runtime field | +| `DeskRecords_Teams_RuntimeField` | `0xbd90c` | German-compatible image / runtime field | +| `DeskState_DeskDate_RuntimeField` | `0xa24e9` | German-compatible image / runtime field | +| `DeskState_DeskFromGame_TextPointer` | `0xae744` | German-compatible image / runtime field | +| `DeskState_FormatError_ExecutableField2Unsigned` | `0xa18a3u` | German-compatible image / runtime field | +| `DeskState_FormatError_ExecutableField3` | `0xae708` | German-compatible image / runtime field | +| `DeskState_FormatError_ExecutableField4` | `0xae750` | German-compatible image / runtime field | +| `DeskState_FormatError_ExecutableFieldUnsigned` | `0xa1896u` | German-compatible image / runtime field | +| `DeskState_FormatError_RuntimeField` | `0xa18b0` | German-compatible image / runtime field | +| `DeskState_FormatError_RuntimeField2` | `0xa2505` | German-compatible image / runtime field | +| `DeskState_FormatError_RuntimeField3` | `0xa2520` | German-compatible image / runtime field | +| `DeskState_FormatError_RuntimeField4` | `0xae7d0` | German-compatible image / runtime field | +| `Desk_EnterDesk_RuntimeField` | `0xa2558` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer` | `0xaefa4` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer2` | `0xaf104` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer3` | `0xaf108` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer4` | `0xaf10c` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer5` | `0xaf110` | German-compatible image / runtime field | +| `Desk_SaveGameDraws_TextPointer6` | `0xaf114` | German-compatible image / runtime field | +| `Desktop_Copy_TextPointer` | `0xa5139` | German-compatible image / runtime field | +| `Desktop_Copy_TextPointer2` | `0xa513a` | German-compatible image / runtime field | +| `Desktop_Key_RuntimeField` | `0xa4ed5` | German-compatible image / runtime field | +| `Desktop_Render_RuntimeField` | `0xa18bc` | German-compatible image / runtime field | +| `Desktop_Render_RuntimeField2` | `0xa18be` | German-compatible image / runtime field | +| `Desktop_Render_RuntimeField3` | `0xa18c0` | German-compatible image / runtime field | +| `Desktop_Render_TextPointer` | `0xae370` | German-compatible image / runtime field | +| `Desktops` | `0xaccd8` | German-compatible image / runtime field | +| `DesktopsUnsigned` | `0xaccd8u` | German-compatible image / runtime field | +| `Difficulty` | `0xa2426` | German-compatible image / runtime field | +| `DifficultyUnsigned` | `0xa2426u` | German-compatible image / runtime field | +| `EditorList` | `0xb1ddc` | German-compatible image / runtime field | +| `EditorListUnsigned` | `0xb1ddcu` | German-compatible image / runtime field | +| `EmptyString` | `0xc0ff0` | German-compatible image / runtime field | +| `EnDataStart` | `0x6b000` | English image adapter | +| `EnglishAdditionalCupField` | `0x7d618` | English image adapter | +| `EnglishAdditionalCupResults` | `0x7d5f8` | English image adapter | +| `EnglishContractExpiryWarningText` | `0x6d921` | English image adapter | +| `EnglishFaCupField` | `0x7c670` | English image adapter | +| `EnglishFaCupProperField` | `0x7c728` | English image adapter | +| `EnglishFaCupQualifyingField` | `0x7c698` | English image adapter | +| `EnglishFaCupResults` | `0x7c5ea` | English image adapter | +| `EnglishFaCupStageResults` | `0x7c632` | English image adapter | +| `EnglishLayoutTranslation` | `0x6bcac` | English image adapter | +| `EnglishLayoutTranslation10` | `0x6be18` | English image adapter | +| `EnglishLayoutTranslation100` | `0x6d869` | English image adapter | +| `EnglishLayoutTranslation101` | `0x6d86e` | English image adapter | +| `EnglishLayoutTranslation102` | `0x6d873` | English image adapter | +| `EnglishLayoutTranslation103` | `0x6d874` | English image adapter | +| `EnglishLayoutTranslation104` | `0x6d876` | English image adapter | +| `EnglishLayoutTranslation105` | `0x6d87d` | English image adapter | +| `EnglishLayoutTranslation106` | `0x6d882` | English image adapter | +| `EnglishLayoutTranslation107` | `0x6d8b4` | English image adapter | +| `EnglishLayoutTranslation108` | `0x6d8b6` | English image adapter | +| `EnglishLayoutTranslation109` | `0x6d8b8` | English image adapter | +| `EnglishLayoutTranslation11` | `0x6be2c` | English image adapter | +| `EnglishLayoutTranslation110` | `0x6d8bb` | English image adapter | +| `EnglishLayoutTranslation111` | `0x6d8c4` | English image adapter | +| `EnglishLayoutTranslation112` | `0x6d8c6` | English image adapter | +| `EnglishLayoutTranslation113` | `0x6d8ca` | English image adapter | +| `EnglishLayoutTranslation114` | `0x6d8cc` | English image adapter | +| `EnglishLayoutTranslation115` | `0x6d8d0` | English image adapter | +| `EnglishLayoutTranslation116` | `0x6d8d4` | English image adapter | +| `EnglishLayoutTranslation117` | `0x6d8d8` | English image adapter | +| `EnglishLayoutTranslation118` | `0x6d8e1` | English image adapter | +| `EnglishLayoutTranslation119` | `0x6d8e8` | English image adapter | +| `EnglishLayoutTranslation12` | `0x6be3c` | English image adapter | +| `EnglishLayoutTranslation120` | `0x6d8f6` | English image adapter | +| `EnglishLayoutTranslation121` | `0x6d8f8` | English image adapter | +| `EnglishLayoutTranslation122` | `0x6d907` | English image adapter | +| `EnglishLayoutTranslation123` | `0x6d9e6` | English image adapter | +| `EnglishLayoutTranslation124` | `0x6d9e8` | English image adapter | +| `EnglishLayoutTranslation125` | `0x6d9ea` | English image adapter | +| `EnglishLayoutTranslation126` | `0x6d9ec` | English image adapter | +| `EnglishLayoutTranslation127` | `0x6d9ee` | English image adapter | +| `EnglishLayoutTranslation128` | `0x6d9f0` | English image adapter | +| `EnglishLayoutTranslation129` | `0x6d9f3` | English image adapter | +| `EnglishLayoutTranslation13` | `0x6be44` | English image adapter | +| `EnglishLayoutTranslation130` | `0x6d9f7` | English image adapter | +| `EnglishLayoutTranslation131` | `0x6d9fc` | English image adapter | +| `EnglishLayoutTranslation132` | `0x6da18` | English image adapter | +| `EnglishLayoutTranslation133` | `0x6da24` | English image adapter | +| `EnglishLayoutTranslation134` | `0x6da40` | English image adapter | +| `EnglishLayoutTranslation135` | `0x6da4c` | English image adapter | +| `EnglishLayoutTranslation136` | `0x6da68` | English image adapter | +| `EnglishLayoutTranslation137` | `0x6da74` | English image adapter | +| `EnglishLayoutTranslation138` | `0x6da90` | English image adapter | +| `EnglishLayoutTranslation139` | `0x6da9c` | English image adapter | +| `EnglishLayoutTranslation14` | `0x6be48` | English image adapter | +| `EnglishLayoutTranslation140` | `0x6daa1` | English image adapter | +| `EnglishLayoutTranslation141` | `0x6dab9` | English image adapter | +| `EnglishLayoutTranslation142` | `0x6dabb` | English image adapter | +| `EnglishLayoutTranslation143` | `0x6dd94` | English image adapter | +| `EnglishLayoutTranslation144` | `0x6dd96` | English image adapter | +| `EnglishLayoutTranslation145` | `0x6ddd8` | English image adapter | +| `EnglishLayoutTranslation146` | `0x6dde0` | English image adapter | +| `EnglishLayoutTranslation147` | `0x6dde4` | English image adapter | +| `EnglishLayoutTranslation148` | `0x6dde5` | English image adapter | +| `EnglishLayoutTranslation149` | `0x6df74` | English image adapter | +| `EnglishLayoutTranslation15` | `0x6be4c` | English image adapter | +| `EnglishLayoutTranslation150` | `0x6e05c` | English image adapter | +| `EnglishLayoutTranslation151` | `0x6e064` | English image adapter | +| `EnglishLayoutTranslation152` | `0x6e06c` | English image adapter | +| `EnglishLayoutTranslation153` | `0x6e074` | English image adapter | +| `EnglishLayoutTranslation154` | `0x6e07c` | English image adapter | +| `EnglishLayoutTranslation155` | `0x6e084` | English image adapter | +| `EnglishLayoutTranslation156` | `0x6e08c` | English image adapter | +| `EnglishLayoutTranslation157` | `0x6e094` | English image adapter | +| `EnglishLayoutTranslation158` | `0x6e0b8` | English image adapter | +| `EnglishLayoutTranslation159` | `0x6e0bb` | English image adapter | +| `EnglishLayoutTranslation16` | `0x6be4f` | English image adapter | +| `EnglishLayoutTranslation160` | `0x6e0d8` | English image adapter | +| `EnglishLayoutTranslation161` | `0x6e110` | English image adapter | +| `EnglishLayoutTranslation162` | `0x6e11c` | English image adapter | +| `EnglishLayoutTranslation163` | `0x6e228` | English image adapter | +| `EnglishLayoutTranslation164` | `0x6e264` | English image adapter | +| `EnglishLayoutTranslation165` | `0x6e265` | English image adapter | +| `EnglishLayoutTranslation166` | `0x6e267` | English image adapter | +| `EnglishLayoutTranslation167` | `0x6e269` | English image adapter | +| `EnglishLayoutTranslation168` | `0x6e26c` | English image adapter | +| `EnglishLayoutTranslation169` | `0x6e26f` | English image adapter | +| `EnglishLayoutTranslation17` | `0x6be58` | English image adapter | +| `EnglishLayoutTranslation170` | `0x6e272` | English image adapter | +| `EnglishLayoutTranslation171` | `0x6e274` | English image adapter | +| `EnglishLayoutTranslation172` | `0x6e277` | English image adapter | +| `EnglishLayoutTranslation173` | `0x6e27b` | English image adapter | +| `EnglishLayoutTranslation174` | `0x6e27d` | English image adapter | +| `EnglishLayoutTranslation175` | `0x6e283` | English image adapter | +| `EnglishLayoutTranslation176` | `0x6e294` | English image adapter | +| `EnglishLayoutTranslation177` | `0x6e29c` | English image adapter | +| `EnglishLayoutTranslation178` | `0x6e2a4` | English image adapter | +| `EnglishLayoutTranslation179` | `0x6e2ac` | English image adapter | +| `EnglishLayoutTranslation18` | `0x6be5c` | English image adapter | +| `EnglishLayoutTranslation180` | `0x6e300` | English image adapter | +| `EnglishLayoutTranslation181` | `0x6e304` | English image adapter | +| `EnglishLayoutTranslation182` | `0x6e308` | English image adapter | +| `EnglishLayoutTranslation183` | `0x6e374` | English image adapter | +| `EnglishLayoutTranslation184` | `0x6e378` | English image adapter | +| `EnglishLayoutTranslation185` | `0x6e380` | English image adapter | +| `EnglishLayoutTranslation186` | `0x6e388` | English image adapter | +| `EnglishLayoutTranslation187` | `0x6e390` | English image adapter | +| `EnglishLayoutTranslation188` | `0x6e394` | English image adapter | +| `EnglishLayoutTranslation189` | `0x6e398` | English image adapter | +| `EnglishLayoutTranslation19` | `0x6be60` | English image adapter | +| `EnglishLayoutTranslation190` | `0x6e39c` | English image adapter | +| `EnglishLayoutTranslation191` | `0x6e3a0` | English image adapter | +| `EnglishLayoutTranslation192` | `0x6e3a4` | English image adapter | +| `EnglishLayoutTranslation193` | `0x6e3b0` | English image adapter | +| `EnglishLayoutTranslation194` | `0x6e3b4` | English image adapter | +| `EnglishLayoutTranslation195` | `0x6e3e4` | English image adapter | +| `EnglishLayoutTranslation196` | `0x6e3fb` | English image adapter | +| `EnglishLayoutTranslation197` | `0x6e434` | English image adapter | +| `EnglishLayoutTranslation198` | `0x6e43c` | English image adapter | +| `EnglishLayoutTranslation199` | `0x6e440` | English image adapter | +| `EnglishLayoutTranslation2` | `0x6bcb0` | English image adapter | +| `EnglishLayoutTranslation20` | `0x6bea0` | English image adapter | +| `EnglishLayoutTranslation200` | `0x6e448` | English image adapter | +| `EnglishLayoutTranslation201` | `0x6e450` | English image adapter | +| `EnglishLayoutTranslation202` | `0x6e45c` | English image adapter | +| `EnglishLayoutTranslation203` | `0x6e465` | English image adapter | +| `EnglishLayoutTranslation204` | `0x6e484` | English image adapter | +| `EnglishLayoutTranslation205` | `0x6e486` | English image adapter | +| `EnglishLayoutTranslation206` | `0x6e48c` | English image adapter | +| `EnglishLayoutTranslation207` | `0x6e49c` | English image adapter | +| `EnglishLayoutTranslation208` | `0x6e4b0` | English image adapter | +| `EnglishLayoutTranslation209` | `0x6e4b8` | English image adapter | +| `EnglishLayoutTranslation21` | `0x6bea1` | English image adapter | +| `EnglishLayoutTranslation210` | `0x6e4c0` | English image adapter | +| `EnglishLayoutTranslation211` | `0x6e4c1` | English image adapter | +| `EnglishLayoutTranslation212` | `0x6e4c4` | English image adapter | +| `EnglishLayoutTranslation213` | `0x6e4cc` | English image adapter | +| `EnglishLayoutTranslation214` | `0x6e4dc` | English image adapter | +| `EnglishLayoutTranslation215` | `0x6e510` | English image adapter | +| `EnglishLayoutTranslation216` | `0x6e513` | English image adapter | +| `EnglishLayoutTranslation217` | `0x6e515` | English image adapter | +| `EnglishLayoutTranslation218` | `0x6e51f` | English image adapter | +| `EnglishLayoutTranslation219` | `0x6e535` | English image adapter | +| `EnglishLayoutTranslation22` | `0x6bea2` | English image adapter | +| `EnglishLayoutTranslation220` | `0x6e578` | English image adapter | +| `EnglishLayoutTranslation221` | `0x6e5ac` | English image adapter | +| `EnglishLayoutTranslation222` | `0x6e5b0` | English image adapter | +| `EnglishLayoutTranslation223` | `0x6e5b4` | English image adapter | +| `EnglishLayoutTranslation224` | `0x6e5e0` | English image adapter | +| `EnglishLayoutTranslation225` | `0x6e62c` | English image adapter | +| `EnglishLayoutTranslation226` | `0x6e62d` | English image adapter | +| `EnglishLayoutTranslation227` | `0x6e634` | English image adapter | +| `EnglishLayoutTranslation228` | `0x6e635` | English image adapter | +| `EnglishLayoutTranslation229` | `0x6e640` | English image adapter | +| `EnglishLayoutTranslation23` | `0x6bf14` | English image adapter | +| `EnglishLayoutTranslation230` | `0x6e644` | English image adapter | +| `EnglishLayoutTranslation231` | `0x6e64c` | English image adapter | +| `EnglishLayoutTranslation232` | `0x6e654` | English image adapter | +| `EnglishLayoutTranslation233` | `0x6e65c` | English image adapter | +| `EnglishLayoutTranslation234` | `0x6e6b4` | English image adapter | +| `EnglishLayoutTranslation235` | `0x6e6b5` | English image adapter | +| `EnglishLayoutTranslation236` | `0x6e6fc` | English image adapter | +| `EnglishLayoutTranslation237` | `0x6e703` | English image adapter | +| `EnglishLayoutTranslation238` | `0x6e704` | English image adapter | +| `EnglishLayoutTranslation239` | `0x6e70c` | English image adapter | +| `EnglishLayoutTranslation24` | `0x6bf1c` | English image adapter | +| `EnglishLayoutTranslation240` | `0x6e714` | English image adapter | +| `EnglishLayoutTranslation241` | `0x6e71c` | English image adapter | +| `EnglishLayoutTranslation242` | `0x6e723` | English image adapter | +| `EnglishLayoutTranslation243` | `0x6e724` | English image adapter | +| `EnglishLayoutTranslation244` | `0x6e72c` | English image adapter | +| `EnglishLayoutTranslation245` | `0x6e72d` | English image adapter | +| `EnglishLayoutTranslation246` | `0x6e758` | English image adapter | +| `EnglishLayoutTranslation247` | `0x6e75c` | English image adapter | +| `EnglishLayoutTranslation248` | `0x6e7a6` | English image adapter | +| `EnglishLayoutTranslation249` | `0x6e7a8` | English image adapter | +| `EnglishLayoutTranslation25` | `0x6bf24` | English image adapter | +| `EnglishLayoutTranslation250` | `0x6e7ab` | English image adapter | +| `EnglishLayoutTranslation251` | `0x6e810` | English image adapter | +| `EnglishLayoutTranslation252` | `0x6e818` | English image adapter | +| `EnglishLayoutTranslation253` | `0x6e81c` | English image adapter | +| `EnglishLayoutTranslation254` | `0x6e848` | English image adapter | +| `EnglishLayoutTranslation255` | `0x6f0ec` | English image adapter | +| `EnglishLayoutTranslation256` | `0x6f2ae` | English image adapter | +| `EnglishLayoutTranslation257` | `0x6f2d4` | English image adapter | +| `EnglishLayoutTranslation258` | `0x6f2e0` | English image adapter | +| `EnglishLayoutTranslation259` | `0x6f2fc` | English image adapter | +| `EnglishLayoutTranslation26` | `0x6bf2c` | English image adapter | +| `EnglishLayoutTranslation260` | `0x6f300` | English image adapter | +| `EnglishLayoutTranslation261` | `0x6f30c` | English image adapter | +| `EnglishLayoutTranslation262` | `0x6f315` | English image adapter | +| `EnglishLayoutTranslation263` | `0x6f31c` | English image adapter | +| `EnglishLayoutTranslation264` | `0x6f320` | English image adapter | +| `EnglishLayoutTranslation265` | `0x6f32c` | English image adapter | +| `EnglishLayoutTranslation266` | `0x6f330` | English image adapter | +| `EnglishLayoutTranslation267` | `0x6f338` | English image adapter | +| `EnglishLayoutTranslation268` | `0x6f341` | English image adapter | +| `EnglishLayoutTranslation269` | `0x6f34e` | English image adapter | +| `EnglishLayoutTranslation27` | `0x6bf34` | English image adapter | +| `EnglishLayoutTranslation270` | `0x6f354` | English image adapter | +| `EnglishLayoutTranslation271` | `0x6f356` | English image adapter | +| `EnglishLayoutTranslation272` | `0x6f358` | English image adapter | +| `EnglishLayoutTranslation273` | `0x6f35c` | English image adapter | +| `EnglishLayoutTranslation274` | `0x6f35e` | English image adapter | +| `EnglishLayoutTranslation275` | `0x6f360` | English image adapter | +| `EnglishLayoutTranslation276` | `0x6f368` | English image adapter | +| `EnglishLayoutTranslation277` | `0x6f36c` | English image adapter | +| `EnglishLayoutTranslation278` | `0x6f37c` | English image adapter | +| `EnglishLayoutTranslation279` | `0x6f390` | English image adapter | +| `EnglishLayoutTranslation28` | `0x6bf94` | English image adapter | +| `EnglishLayoutTranslation280` | `0x6f3b8` | English image adapter | +| `EnglishLayoutTranslation281` | `0x6f990` | English image adapter | +| `EnglishLayoutTranslation282` | `0x6fac4` | English image adapter | +| `EnglishLayoutTranslation283` | `0x6fbc4` | English image adapter | +| `EnglishLayoutTranslation284` | `0x6fdd4` | English image adapter | +| `EnglishLayoutTranslation285` | `0x6fe0c` | English image adapter | +| `EnglishLayoutTranslation286` | `0x6fe10` | English image adapter | +| `EnglishLayoutTranslation287` | `0x6fe18` | English image adapter | +| `EnglishLayoutTranslation288` | `0x6fe19` | English image adapter | +| `EnglishLayoutTranslation289` | `0x6fe20` | English image adapter | +| `EnglishLayoutTranslation29` | `0x6bf95` | English image adapter | +| `EnglishLayoutTranslation290` | `0x6fe5c` | English image adapter | +| `EnglishLayoutTranslation291` | `0x6fe78` | English image adapter | +| `EnglishLayoutTranslation292` | `0x6fe83` | English image adapter | +| `EnglishLayoutTranslation293` | `0x6ffc8` | English image adapter | +| `EnglishLayoutTranslation294` | `0x702dc` | English image adapter | +| `EnglishLayoutTranslation295` | `0x7039c` | English image adapter | +| `EnglishLayoutTranslation296` | `0x70455` | English image adapter | +| `EnglishLayoutTranslation297` | `0x70540` | English image adapter | +| `EnglishLayoutTranslation298` | `0x7054c` | English image adapter | +| `EnglishLayoutTranslation299` | `0x70d9a` | English image adapter | +| `EnglishLayoutTranslation3` | `0x6bcb1` | English image adapter | +| `EnglishLayoutTranslation30` | `0x6bf96` | English image adapter | +| `EnglishLayoutTranslation300` | `0x70e2d` | English image adapter | +| `EnglishLayoutTranslation301` | `0x70ebd` | English image adapter | +| `EnglishLayoutTranslation302` | `0x70ec4` | English image adapter | +| `EnglishLayoutTranslation303` | `0x70ec6` | English image adapter | +| `EnglishLayoutTranslation304` | `0x70ed8` | English image adapter | +| `EnglishLayoutTranslation305` | `0x70eea` | English image adapter | +| `EnglishLayoutTranslation306` | `0x70eef` | English image adapter | +| `EnglishLayoutTranslation307` | `0x70f0c` | English image adapter | +| `EnglishLayoutTranslation308` | `0x70f10` | English image adapter | +| `EnglishLayoutTranslation309` | `0x70f14` | English image adapter | +| `EnglishLayoutTranslation31` | `0x6bfbe` | English image adapter | +| `EnglishLayoutTranslation310` | `0x70f18` | English image adapter | +| `EnglishLayoutTranslation311` | `0x70f1c` | English image adapter | +| `EnglishLayoutTranslation312` | `0x70f20` | English image adapter | +| `EnglishLayoutTranslation313` | `0x70f24` | English image adapter | +| `EnglishLayoutTranslation314` | `0x70f28` | English image adapter | +| `EnglishLayoutTranslation315` | `0x70f2c` | English image adapter | +| `EnglishLayoutTranslation316` | `0x70f2e` | English image adapter | +| `EnglishLayoutTranslation317` | `0x70f30` | English image adapter | +| `EnglishLayoutTranslation318` | `0x70f32` | English image adapter | +| `EnglishLayoutTranslation32` | `0x6c028` | English image adapter | +| `EnglishLayoutTranslation33` | `0x6c0c0` | English image adapter | +| `EnglishLayoutTranslation34` | `0x6c0c8` | English image adapter | +| `EnglishLayoutTranslation35` | `0x6c0c9` | English image adapter | +| `EnglishLayoutTranslation36` | `0x6c0cc` | English image adapter | +| `EnglishLayoutTranslation37` | `0x6c141` | English image adapter | +| `EnglishLayoutTranslation38` | `0x6c142` | English image adapter | +| `EnglishLayoutTranslation39` | `0x6c143` | English image adapter | +| `EnglishLayoutTranslation4` | `0x6bcb8` | English image adapter | +| `EnglishLayoutTranslation40` | `0x6c1e4` | English image adapter | +| `EnglishLayoutTranslation41` | `0x6c1e8` | English image adapter | +| `EnglishLayoutTranslation42` | `0x6c1eb` | English image adapter | +| `EnglishLayoutTranslation43` | `0x6c1ec` | English image adapter | +| `EnglishLayoutTranslation44` | `0x6c2b8` | English image adapter | +| `EnglishLayoutTranslation45` | `0x6c2ba` | English image adapter | +| `EnglishLayoutTranslation46` | `0x6c2bc` | English image adapter | +| `EnglishLayoutTranslation47` | `0x6c2bf` | English image adapter | +| `EnglishLayoutTranslation48` | `0x6c2c4` | English image adapter | +| `EnglishLayoutTranslation49` | `0x6c334` | English image adapter | +| `EnglishLayoutTranslation5` | `0x6bcbc` | English image adapter | +| `EnglishLayoutTranslation50` | `0x6c520` | English image adapter | +| `EnglishLayoutTranslation51` | `0x6c568` | English image adapter | +| `EnglishLayoutTranslation52` | `0x6c610` | English image adapter | +| `EnglishLayoutTranslation53` | `0x6c684` | English image adapter | +| `EnglishLayoutTranslation54` | `0x6c700` | English image adapter | +| `EnglishLayoutTranslation55` | `0x6c734` | English image adapter | +| `EnglishLayoutTranslation56` | `0x6c740` | English image adapter | +| `EnglishLayoutTranslation57` | `0x6c74c` | English image adapter | +| `EnglishLayoutTranslation58` | `0x6d02c` | English image adapter | +| `EnglishLayoutTranslation59` | `0x6d08c` | English image adapter | +| `EnglishLayoutTranslation6` | `0x6bce1` | English image adapter | +| `EnglishLayoutTranslation60` | `0x6d14c` | English image adapter | +| `EnglishLayoutTranslation61` | `0x6d14d` | English image adapter | +| `EnglishLayoutTranslation62` | `0x6d158` | English image adapter | +| `EnglishLayoutTranslation63` | `0x6d159` | English image adapter | +| `EnglishLayoutTranslation64` | `0x6d15c` | English image adapter | +| `EnglishLayoutTranslation65` | `0x6d169` | English image adapter | +| `EnglishLayoutTranslation66` | `0x6d1b3` | English image adapter | +| `EnglishLayoutTranslation67` | `0x6d1ce` | English image adapter | +| `EnglishLayoutTranslation68` | `0x6d24f` | English image adapter | +| `EnglishLayoutTranslation69` | `0x6d26a` | English image adapter | +| `EnglishLayoutTranslation7` | `0x6be0c` | English image adapter | +| `EnglishLayoutTranslation70` | `0x6d270` | English image adapter | +| `EnglishLayoutTranslation71` | `0x6d272` | English image adapter | +| `EnglishLayoutTranslation72` | `0x6d274` | English image adapter | +| `EnglishLayoutTranslation73` | `0x6d29c` | English image adapter | +| `EnglishLayoutTranslation74` | `0x6d3b4` | English image adapter | +| `EnglishLayoutTranslation75` | `0x6d404` | English image adapter | +| `EnglishLayoutTranslation76` | `0x6d408` | English image adapter | +| `EnglishLayoutTranslation77` | `0x6d40c` | English image adapter | +| `EnglishLayoutTranslation78` | `0x6d450` | English image adapter | +| `EnglishLayoutTranslation79` | `0x6d458` | English image adapter | +| `EnglishLayoutTranslation8` | `0x6be10` | English image adapter | +| `EnglishLayoutTranslation80` | `0x6d45c` | English image adapter | +| `EnglishLayoutTranslation81` | `0x6d464` | English image adapter | +| `EnglishLayoutTranslation82` | `0x6d478` | English image adapter | +| `EnglishLayoutTranslation83` | `0x6d488` | English image adapter | +| `EnglishLayoutTranslation84` | `0x6d4d0` | English image adapter | +| `EnglishLayoutTranslation85` | `0x6d568` | English image adapter | +| `EnglishLayoutTranslation86` | `0x6d569` | English image adapter | +| `EnglishLayoutTranslation87` | `0x6d56c` | English image adapter | +| `EnglishLayoutTranslation88` | `0x6d570` | English image adapter | +| `EnglishLayoutTranslation89` | `0x6d584` | English image adapter | +| `EnglishLayoutTranslation9` | `0x6be14` | English image adapter | +| `EnglishLayoutTranslation90` | `0x6d598` | English image adapter | +| `EnglishLayoutTranslation91` | `0x6d5a4` | English image adapter | +| `EnglishLayoutTranslation92` | `0x6d6d4` | English image adapter | +| `EnglishLayoutTranslation93` | `0x6d84e` | English image adapter | +| `EnglishLayoutTranslation94` | `0x6d850` | English image adapter | +| `EnglishLayoutTranslation95` | `0x6d854` | English image adapter | +| `EnglishLayoutTranslation96` | `0x6d85e` | English image adapter | +| `EnglishLayoutTranslation97` | `0x6d860` | English image adapter | +| `EnglishLayoutTranslation98` | `0x6d864` | English image adapter | +| `EnglishLayoutTranslation99` | `0x6d867` | English image adapter | +| `EnglishLeagueCupField` | `0x7cf0a` | English image adapter | +| `EnglishLeagueCupFirstRoundField` | `0x7cf32` | English image adapter | +| `EnglishLeagueCupFirstRoundResults` | `0x7cfae` | English image adapter | +| `EnglishLeagueCupQuarterFinalField` | `0x7cf62` | English image adapter | +| `EnglishLeagueCupQuarterFinalOtherLegResults` | `0x7d004` | English image adapter | +| `EnglishLeagueCupQuarterFinalResults` | `0x7cfc6` | English image adapter | +| `EnglishLeagueCupSemiFinalField` | `0x7cfaa` | English image adapter | +| `EnglishLeagueCupSemiFinalResults` | `0x7d002` | English image adapter | +| `Environment_FormatError_RuntimeField` | `0xa50f0` | German-compatible image / runtime field | +| `Environment_FormatError_RuntimeField2` | `0xa50f6` | German-compatible image / runtime field | +| `Environment_Render_TextPointer` | `0xaeb74` | German-compatible image / runtime field | +| `Environment_SetEnvironment_ExecutableField` | `0xaf394` | German-compatible image / runtime field | +| `EuropeNameTable` | `0xae710` | German-compatible image / runtime field | +| `EventPasses` | `0xa2ba1` | German-compatible image / runtime field | +| `Field` | `0xb6adc` | German-compatible image / runtime field | +| `Field0` | `0xb60c4` | German-compatible image / runtime field | +| `FieldUnsigned` | `0xb6adcu` | German-compatible image / runtime field | +| `FinalLeagueStrengthMaximum` | `0xa2c2d` | German-compatible image / runtime field | +| `FinanceStatisticsEnabled` | `0xbdb7e` | German-compatible image / runtime field | +| `First` | `0xa3968` | German-compatible image / runtime field | +| `FixtureAdvertisingCountersEnd` | `0xbd4e0` | Test fixture location or bound | +| `FixtureAdvertisingRatingsEnd` | `0xac840` | Test fixture location or bound | +| `FixtureAdvertisingWorkspaceEnd` | `0xbda00` | Test fixture location or bound | +| `FixtureAllTimeAppearanceColumn` | `0xa396c` | Test fixture location or bound | +| `FixtureAllTimePointsColumn` | `0xa396e` | Test fixture location or bound | +| `FixtureAllTimePrimaryMetric` | `0xa3961` | Test fixture location or bound | +| `FixtureAllTimeSecondaryMetric` | `0xa3962` | Test fixture location or bound | +| `FixtureBankMemoryImageSize` | `0xc0840` | Test fixture location or bound | +| `FixtureCalendarSecondLeagueBit` | `0xa29f3` | Test fixture location or bound | +| `FixtureControllerValueByteOne` | `0xbd8ed` | Test fixture location or bound | +| `FixtureControllerValueByteThree` | `0xbd8ef` | Test fixture location or bound | +| `FixtureControllerValueByteTwo` | `0xbd8ee` | Test fixture location or bound | +| `FixtureCupFirstDrawingScriptUnsigned` | `0xa3bf0u` | Test fixture location or bound | +| `FixtureCupSecondDrawingScriptUnsigned` | `0xa3c32u` | Test fixture location or bound | +| `FixtureDesktopFirstLabelPointer` | `0xaf0f4` | Test fixture location or bound | +| `FixtureDesktopPairCases` | `0xa18b4` | Test fixture location or bound | +| `FixtureDesktopSecondLabelPointer` | `0xaf0f8` | Test fixture location or bound | +| `FixtureDriverSavedFlag` | `0xaf847` | Test fixture location or bound | +| `FixtureDriverSavedValueWord` | `0xaf838` | Test fixture location or bound | +| `FixtureExecutableStorageSize` | `0x50000` | Test fixture location or bound | +| `FixtureFifthCupPresentationOption` | `0xa25b6` | Test fixture location or bound | +| `FixtureFirstCupPresentationOption` | `0xa25b2` | Test fixture location or bound | +| `FixtureFirstTacticMaximum` | `0xa20ec` | Test fixture location or bound | +| `FixtureFourthCupPresentationOption` | `0xa25b5` | Test fixture location or bound | +| `FixtureFriendlySecondBlankLabel` | `0xadf5c` | Test fixture location or bound | +| `FixtureNationalWorkspaceEnd` | `0xbbccc` | Test fixture location or bound | +| `FixturePairingsFifthButtonText` | `0xadf8c` | Test fixture location or bound | +| `FixturePairingsFourthButtonText` | `0xadf88` | Test fixture location or bound | +| `FixturePairingsSecondDescriptor` | `0xb6282` | Test fixture location or bound | +| `FixturePairingsThirdDescriptor` | `0xb6288` | Test fixture location or bound | +| `FixturePlayerCardFlagByte` | `0xbb12e` | Test fixture location or bound | +| `FixtureRealityHandoffSignedBias` | `0xa49c0` | Test fixture location or bound | +| `FixtureRegionalLeagueLabelPointer` | `0xae6d0` | Test fixture location or bound | +| `FixtureSecondBookedFriendly` | `0xab68a` | Test fixture location or bound | +| `FixtureSecondCupPresentationOption` | `0xa25b3` | Test fixture location or bound | +| `FixtureSecondDeskCursor` | `0xbd6ce` | Test fixture location or bound | +| `FixtureSecondManagerClub` | `0xb5eb6` | Test fixture location or bound | +| `FixtureSecondSeasonEntrant` | `0xbb182` | Test fixture location or bound | +| `FixtureSecondTacticMaximum` | `0xa20ed` | Test fixture location or bound | +| `FixtureSeriesFirstMetric` | `0xa3884` | Test fixture location or bound | +| `FixtureSeriesSecondMetric` | `0xa3885` | Test fixture location or bound | +| `FixtureSettingsBlankNumericalCell` | `0xa2508` | Test fixture location or bound | +| `FixtureSettingsFirstCell` | `0xa24f8` | Test fixture location or bound | +| `FixtureSportschauAdjacentStateByte` | `0xb5d25` | Test fixture location or bound | +| `FixtureSportschauDescriptorWords` | `0xb6408` | Test fixture location or bound | +| `FixtureSportschauIndoorFooterBias` | `0xa47fa` | Test fixture location or bound | +| `FixtureSportschauOptionsBegin` | `0xa24f4` | Test fixture location or bound | +| `FixtureSportschauOutdoorFooterBias` | `0xa47f9` | Test fixture location or bound | +| `FixtureStadiumAdjacentRuntimeByte` | `0xbb12d` | Test fixture location or bound | +| `FixtureStadiumBlockLabel` | `0xaef78` | Test fixture location or bound | +| `FixtureStadiumTierLabel` | `0xae9d4` | Test fixture location or bound | +| `FixtureTeamStatisticsColumnLabels` | `0xae4f8` | Test fixture location or bound | +| `FixtureTeamStatisticsFirstLabel` | `0xae4b8` | Test fixture location or bound | +| `FixtureTextDatabaseFilename` | `0xa1677` | Test fixture location or bound | +| `FixtureThirdTacticMaximum` | `0xa20ee` | Test fixture location or bound | +| `FixtureTransferCapacityFlag` | `0xbbcb1` | Test fixture location or bound | +| `FixtureTransferSecondIdentityValue` | `0xab90c` | Test fixture location or bound | +| `FixtureTransferSecondPlayerValue` | `0xbb86e` | Test fixture location or bound | +| `Flags` | `0xbb12c` | German-compatible image / runtime field | +| `FlagsUnsigned` | `0xbb12cU` | German-compatible image / runtime field | +| `FlagsUnsignedSpelling2` | `0xbb12cu` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField` | `0xa1318` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField2` | `0xa1363` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField3` | `0xa138a` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField4` | `0xa13bb` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField5` | `0xa140a` | German-compatible image / runtime field | +| `Fltd_Layout_ExecutableField6` | `0xa163c` | German-compatible image / runtime field | +| `Fltd_Layout_TextPointer` | `0xa004e` | German-compatible image / runtime field | +| `Fltd_Layout_TextPointer2` | `0xa0051` | German-compatible image / runtime field | +| `Fltd_Layout_TextPointer3` | `0xa0054` | German-compatible image / runtime field | +| `Fltd_Layout_TextPointer4` | `0xa0056` | German-compatible image / runtime field | +| `Fltd_Layout_TextPointer5` | `0xa105c` | German-compatible image / runtime field | +| `ForeignClubStrength` | `0xbb590` | German-compatible image / runtime field | +| `ForeignPlayerLimitEnabled` | `0xa4a80` | German-compatible image / runtime field | +| `Formations` | `0xb2cfc` | German-compatible image / runtime field | +| `FreeKickTakerLabel` | `0x80cc9` | English image adapter | +| `FriendlyDays` | `0xaf3c0` | German-compatible image / runtime field | +| `FriendlyDaysUnsigned` | `0xaf3c0u` | German-compatible image / runtime field | +| `FriendlyPlanCount` | `0xa3134` | German-compatible image / runtime field | +| `FriendlyTeams` | `0xab688` | German-compatible image / runtime field | +| `FriendlyTeamsUnsigned` | `0xab688u` | German-compatible image / runtime field | +| `FundBlock` | `0xac7b0` | German-compatible image / runtime field | +| `FundBlockUnsigned` | `0xac7b0u` | German-compatible image / runtime field | +| `GameEndAlternate_FormatError_ExecutableField` | `0xa4431` | German-compatible image / runtime field | +| `GameEndTaxAnimation_LoadGameEndTaxAnimationAssets_ExecutableField` | `0xa5118` | German-compatible image / runtime field | +| `GameEnd_Copy_TextPointer` | `0xae58c` | German-compatible image / runtime field | +| `GameEnd_Copy_TextPointer2` | `0xae5a8` | German-compatible image / runtime field | +| `GameEnd_Line_TextPointer` | `0xae9e4` | German-compatible image / runtime field | +| `GameEnd_Out_TextPointer` | `0xaedc0` | German-compatible image / runtime field | +| `GameEnd_SourceHyphenator_ExecutableField` | `0xa227b` | German-compatible image / runtime field | +| `GameEnd_SourceHyphenator_RuntimeField` | `0xa228d` | German-compatible image / runtime field | +| `GameMode` | `0xbdb79` | German-compatible image / runtime field | +| `GameModeUnsigned` | `0xbdb79u` | German-compatible image / runtime field | +| `GermanDataCompatibilityEnd` | `0xab5a0` | German-compatible image / runtime field | +| `GermanDataSegmentBegin` | `0xa0000` | German-compatible image / runtime field | +| `GermanImageEnd` | `0xc1000` | German-compatible image / runtime field | +| `GermanLayoutTranslation` | `0xa1431` | German-compatible image / runtime field | +| `GermanLayoutTranslation2` | `0xa2c26` | German-compatible image / runtime field | +| `GermanLayoutTranslation3` | `0xa2c2c` | German-compatible image / runtime field | +| `GermanLayoutTranslation4` | `0xa45b4` | German-compatible image / runtime field | +| `HighscoreRuntimeField` | `0xa513b` | German-compatible image / runtime field | +| `IncomingTransfer_OutcomeFrameAt_RuntimeField` | `0xa3fc9` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_ExecutableField` | `0xa12c4` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_RuntimeField` | `0xa3fca` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer` | `0xa0040` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer10` | `0xaf2d4` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer11` | `0xaf2d8` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer12` | `0xaf2dc` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer13` | `0xaf2e0` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer14` | `0xaf2e4` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer2` | `0xae7e4` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer3` | `0xaedf8` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer3Unsigned` | `0xaedf8u` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer4` | `0xaedfc` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer4Unsigned` | `0xaedfcU` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer5` | `0xaf2ac` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer6` | `0xaf2b0` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer7` | `0xaf2b4` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer8` | `0xaf2b8` | German-compatible image / runtime field | +| `IncomingTransfer_RenderAtElapsed_TextPointer9` | `0xaf2c8` | German-compatible image / runtime field | +| `IndoorInvitationText` | `0xa1100` | German-compatible image / runtime field | +| `IndoorStandings_FormatError_TextPointer` | `0xa50a2` | German-compatible image / runtime field | +| `IndoorStandings_FormatError_TextPointer2` | `0xaf0a4` | German-compatible image / runtime field | +| `IndoorStandings_FormatError_TextPointer3` | `0xaf0a8` | German-compatible image / runtime field | +| `IndoorStandings_FormatError_TextPointer4` | `0xaf0b0` | German-compatible image / runtime field | +| `IndoorStandings_FormatError_TextPointer5` | `0xaf0b4` | German-compatible image / runtime field | +| `IndoorStandings_Render_TextPointer` | `0xa10fd` | German-compatible image / runtime field | +| `IndoorStandings_Render_TextPointer2` | `0xaf0ac` | German-compatible image / runtime field | +| `LeagueCalendarBits` | `0xa29f2` | German-compatible image / runtime field | +| `LeagueHeaderTable` | `0xae08c` | German-compatible image / runtime field | +| `LeaguePairings_DateString_TextPointer` | `0xa1070` | German-compatible image / runtime field | +| `LeaguePairings_DateString_TextPointer2` | `0xae66c` | German-compatible image / runtime field | +| `LeaguePairings_Fill_RuntimeField` | `0xa4549` | German-compatible image / runtime field | +| `LeaguePairings_Fill_RuntimeField2` | `0xa454b` | German-compatible image / runtime field | +| `LeaguePairings_Fill_TextPointer` | `0xa1469` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_ExecutableField` | `0xa146d` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer` | `0xa146b` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer10` | `0xaec90` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer11` | `0xaec94` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer12` | `0xaec98` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer13` | `0xaeca0` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer14` | `0xaf194` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer2` | `0xa1471` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer3` | `0xa1474` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer4` | `0xadf78` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer5` | `0xadf7c` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer6` | `0xae6a8` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer7` | `0xae6b8` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer8` | `0xaeb0c` | German-compatible image / runtime field | +| `LeaguePairings_FormatError_TextPointer9` | `0xaeb10` | German-compatible image / runtime field | +| `LeaguePairings_LeaguePairingsConstants_RuntimeField` | `0xa2be6` | German-compatible image / runtime field | +| `LeaguePairings_SelectorEvent_RuntimeField` | `0xa2c0e` | German-compatible image / runtime field | +| `LeaguePairings_SelectorEvent_RuntimeField2` | `0xa4561` | German-compatible image / runtime field | +| `LeaguePairings_SelectorEvent_RuntimeField3` | `0xa4563` | German-compatible image / runtime field | +| `LeaguePairings_Selector_RuntimeField` | `0xa4565` | German-compatible image / runtime field | +| `LeaguePairings_Selector_RuntimeField2` | `0xa4567` | German-compatible image / runtime field | +| `LeaguePairings_Selector_RuntimeField3` | `0xa4569` | German-compatible image / runtime field | +| `LeaguePairings_Selector_RuntimeField4` | `0xa456c` | German-compatible image / runtime field | +| `LeaguePresentationOptions` | `0xa24f7` | German-compatible image / runtime field | +| `LeaguePresentationOptionsUnsigned` | `0xa24f7u` | German-compatible image / runtime field | +| `LeagueRankHistory` | `0xba380` | German-compatible image / runtime field | +| `LeagueResults` | `0xba3c4` | German-compatible image / runtime field | +| `LeagueRoundCounters` | `0xbb4c1` | German-compatible image / runtime field | +| `LeagueSizes` | `0xa2bcd` | German-compatible image / runtime field | +| `LeagueStrengthRanges` | `0xa2c1c` | German-compatible image / runtime field | +| `LeagueTableDisplayModes` | `0xb602c` | German-compatible image / runtime field | +| `LeagueTableDisplayModesUnsigned` | `0xb602cu` | German-compatible image / runtime field | +| `LeagueTableRangeDialog_Backdrop_ExecutableField` | `0xaf240` | German-compatible image / runtime field | +| `LeagueTable_Glyph_TextPointer` | `0xa1458` | German-compatible image / runtime field | +| `LeagueTable_Glyph_TextPointer2` | `0xadf54` | German-compatible image / runtime field | +| `LeagueTable_OriginalToUtf8_RuntimeField` | `0xbdb78` | German-compatible image / runtime field | +| `LeagueTable_OriginalToUtf8_TextPointer` | `0xadf60` | German-compatible image / runtime field | +| `LeagueTable_OriginalToUtf8_TextPointer2` | `0xaec7c` | German-compatible image / runtime field | +| `Lineup_Render_TextPointer` | `0xae0dc` | German-compatible image / runtime field | +| `Lineup_Render_TextPointer2` | `0xae0e8` | German-compatible image / runtime field | +| `Lineup_Render_TextPointer3` | `0xaf134` | German-compatible image / runtime field | +| `Lineup_Render_TextPointer4` | `0xaf138` | German-compatible image / runtime field | +| `LiveDeskDisabled` | `0xa251f` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField` | `0xa11da` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField10` | `0xa3e84` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField11` | `0xa3e88` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField12` | `0xa49c2` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField13` | `0xa49f2` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField14` | `0xa4a22` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField2` | `0xa11de` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField3` | `0xa11e3` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField4` | `0xa11e6` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField5` | `0xa11e8` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField6` | `0xa3d50` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField7` | `0xa3d55` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField8` | `0xa3d5a` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_ExecutableField9` | `0xa3d6e` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField` | `0xa3d82` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField10` | `0xa3de9` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField11` | `0xa3dfd` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField12Unsigned` | `0xa3f6cu` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField13Unsigned` | `0xa3f6eu` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField14` | `0xbdb08` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField15` | `0xbdb82` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField2` | `0xa3d85` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField3` | `0xa3d96` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField4` | `0xa3d99` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField5` | `0xa3d9b` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField6` | `0xa3d9d` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField7` | `0xa3dad` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField8` | `0xa3dc1` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_RuntimeField9` | `0xa3dd5` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer` | `0xae078` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer10` | `0xaf010` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer11` | `0xaf05c` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer12` | `0xaf060` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer13` | `0xaf064` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer14` | `0xaf068` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer15` | `0xaf06c` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer2` | `0xae1a8` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer2Unsigned` | `0xae1a8u` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer3` | `0xae5c0` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer4` | `0xaeb30` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer5` | `0xaeb34` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer6` | `0xaeb38` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer7` | `0xaf004` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer8` | `0xaf008` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointer9` | `0xaf00c` | German-compatible image / runtime field | +| `LiveMatchday_FormatError_TextPointerUnsigned` | `0xae078u` | German-compatible image / runtime field | +| `LiveMatchday_LiveMatchdayFrame_TextPointer` | `0xaf014` | German-compatible image / runtime field | +| `LiveMatchday_PatternRect_RuntimeField` | `0xa3457` | German-compatible image / runtime field | +| `LiveMatchday_PatternRect_RuntimeFieldUnsigned` | `0xa3457u` | German-compatible image / runtime field | +| `LiveMatchday_RenderHeader_RuntimeFieldUnsigned` | `0xa3f34u` | German-compatible image / runtime field | +| `LiveMatchday_RenderHeader_TextPointer` | `0xa11d8` | German-compatible image / runtime field | +| `LiveMatchday_RenderSetPiece_RuntimeField` | `0xa3e45` | German-compatible image / runtime field | +| `LiveMatchday_RenderSetPiece_RuntimeField2` | `0xa3e55` | German-compatible image / runtime field | +| `LiveMatchday_Render_ExecutableField` | `0xa50a6` | German-compatible image / runtime field | +| `LiveMatchday_Render_ExecutableFieldUnsigned` | `0xa50a6u` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeField` | `0xa3d3e` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeField2` | `0xa3d42` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeField2Unsigned` | `0xa3d42u` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeField3` | `0xa3d46` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeField3Unsigned` | `0xa3d46u` | German-compatible image / runtime field | +| `LiveMatchday_Render_RuntimeFieldUnsigned` | `0xa3d3eu` | German-compatible image / runtime field | +| `LiveSceneOptions` | `0xa20f4` | German-compatible image / runtime field | +| `LiveSetPiece_Motion_ExecutableField2Unsigned` | `0xa3db9u` | German-compatible image / runtime field | +| `LiveSetPiece_Motion_ExecutableFieldUnsigned` | `0xa3dafu` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField10Unsigned` | `0xa3e69u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField11Unsigned` | `0xa3e71u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField12Unsigned` | `0xa3e79u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField13Unsigned` | `0xa3e7cu` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField2Unsigned` | `0xa3e11u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField3Unsigned` | `0xa3e2au` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField4Unsigned` | `0xa3e4du` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField5Unsigned` | `0xa3e5du` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField6Unsigned` | `0xa3e61u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField7Unsigned` | `0xa3e63u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField8Unsigned` | `0xa3e65u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableField9Unsigned` | `0xa3e67u` | German-compatible image / runtime field | +| `LiveSetPiece_Run_ExecutableFieldUnsigned` | `0xa3db5u` | German-compatible image / runtime field | +| `LiveSetPiece_Wall_ExecutableFieldUnsigned` | `0xa3e43u` | German-compatible image / runtime field | +| `LoanTitleText` | `0xae190` | German-compatible image / runtime field | +| `Loans` | `0xbd70c` | German-compatible image / runtime field | +| `LoansUnsigned` | `0xbd70cu` | German-compatible image / runtime field | +| `MailboxRecipientMask` | `0xaf8f4` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField` | `0xa432e` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField2` | `0xa4332` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField3` | `0xa4336` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField4` | `0xa433a` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField5` | `0xa433e` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField6` | `0xa4342` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField7` | `0xa4346` | German-compatible image / runtime field | +| `MailboxScreen_Click_RuntimeField8` | `0xa434a` | German-compatible image / runtime field | +| `MailboxScreen_Render_RuntimeField` | `0xa434e` | German-compatible image / runtime field | +| `MailboxScreen_Render_RuntimeField2` | `0xa4350` | German-compatible image / runtime field | +| `MailboxScreen_Render_RuntimeField3` | `0xa4352` | German-compatible image / runtime field | +| `MailboxScreen_Render_RuntimeField4` | `0xa4354` | German-compatible image / runtime field | +| `MailboxScreen_Render_TextPointer` | `0xaed9c` | German-compatible image / runtime field | +| `MailboxScreen_Render_TextPointer2` | `0xaeda0` | German-compatible image / runtime field | +| `Main_FileScreen_RuntimeField` | `0xa3f68` | German-compatible image / runtime field | +| `Main_FileScreen_RuntimeField2` | `0xa3f69` | German-compatible image / runtime field | +| `Main_FileScreen_RuntimeField3` | `0xa3f6a` | German-compatible image / runtime field | +| `Main_FormatError_ExecutableField` | `0xa24ff` | German-compatible image / runtime field | +| `Main_FormatError_ExecutableField2` | `0xa2519` | German-compatible image / runtime field | +| `Main_FormatError_ExecutableFieldUnsigned` | `0xa24ffu` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField` | `0xa2522` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField2` | `0xa252b` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField3` | `0xa2534` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField4` | `0xa253e` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField5` | `0xa2543` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField6` | `0xa256b` | German-compatible image / runtime field | +| `Main_FormatError_RuntimeField7` | `0xa2586` | German-compatible image / runtime field | +| `Main_Screen_RuntimeField` | `0xa3f6b` | German-compatible image / runtime field | +| `Main_Screen_RuntimeField2` | `0xbdb88` | German-compatible image / runtime field | +| `ManagerAutomation` | `0xa243a` | German-compatible image / runtime field | +| `ManagerCount` | `0xa24f6` | German-compatible image / runtime field | +| `ManagerCountUnsigned` | `0xa24f6u` | German-compatible image / runtime field | +| `ManagerMailbox` | `0xaf978` | German-compatible image / runtime field | +| `ManagerMatchHistory` | `0xafd04` | German-compatible image / runtime field | +| `ManagerRatings` | `0xac6c0` | German-compatible image / runtime field | +| `ManagerRecords` | `0xb6c18` | German-compatible image / runtime field | +| `ManagerSettings` | `0xb5f84` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField` | `0xa2c02` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField2` | `0xa48ad` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField3` | `0xa48b5` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField4` | `0xa48bd` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField5` | `0xa48c5` | German-compatible image / runtime field | +| `Manager_FormatError_RuntimeField6` | `0xa48cd` | German-compatible image / runtime field | +| `Manager_FormatError_TextPointer` | `0xaec28` | German-compatible image / runtime field | +| `Manager_FormatError_TextPointer2` | `0xaec70` | German-compatible image / runtime field | +| `Manager_Render_TextPointer` | `0xade48` | German-compatible image / runtime field | +| `Manager_SmallText_TextPointer` | `0xaec2c` | German-compatible image / runtime field | +| `MasterDatabaseMetadata` | `0xba384` | German-compatible image / runtime field | +| `MastersQualificationText` | `0xa1075` | German-compatible image / runtime field | +| `MastersWinnerText` | `0xa10ba` | German-compatible image / runtime field | +| `MatchEngine_EventImpl_ExecutableField` | `0xa2555` | German-compatible image / runtime field | +| `MatchEngine_EventImpl_ExecutableField2` | `0xa255e` | German-compatible image / runtime field | +| `MatchEngine_EventImpl_ExecutableField3` | `0xa2567` | German-compatible image / runtime field | +| `MatchEngine_InjurePlayer_TextPointer` | `0xaead0` | German-compatible image / runtime field | +| `MatchEngine_InjurePlayer_TextPointer2` | `0xaead4` | German-compatible image / runtime field | +| `MatchEngine_Minute_ExecutableField` | `0xaf9c7` | German-compatible image / runtime field | +| `MatchEngine_Minute_ExecutableField2` | `0xafb40` | German-compatible image / runtime field | +| `MatchEngine_Minute_ExecutableField3` | `0xafb71` | German-compatible image / runtime field | +| `MatchEngine_Minute_ExecutableField4` | `0xafb7d` | German-compatible image / runtime field | +| `MatchEngine_Side_ExecutableField` | `0xa2507` | German-compatible image / runtime field | +| `MatchEngine_Side_ExecutableField2` | `0xa2510` | German-compatible image / runtime field | +| `MatchEngine_Side_ExecutableField3` | `0xa2516` | German-compatible image / runtime field | +| `MatchEngine_Side_ExecutableField4` | `0xa2531` | German-compatible image / runtime field | +| `MatchEngine_Side_ExecutableField5` | `0xa2570` | German-compatible image / runtime field | +| `MatchEventsDisabled` | `0xa5046` | German-compatible image / runtime field | +| `MatchdayGroupDescriptors` | `0xb636c` | German-compatible image / runtime field | +| `MatchdayGroupWorkspace` | `0xb600c` | German-compatible image / runtime field | +| `MatchdayResults_CompetitionName_TextPointer` | `0xae790` | German-compatible image / runtime field | +| `MatchdaySetupRuntimeField14` | `0xbb1f0` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField` | `0xa3eba` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField2` | `0xa3eca` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField3` | `0xa3eda` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField4` | `0xa3f12` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField5` | `0xa3f16` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField6` | `0xa3f1a` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_ExecutableField7` | `0xa3f20` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_TextPointer` | `0xaeff8` | German-compatible image / runtime field | +| `MatchdaySetup_Attendance_TextPointer2` | `0xaf000` | German-compatible image / runtime field | +| `MatchdaySetup_ConsiderSportschauFixture_RuntimeField` | `0xa258d` | German-compatible image / runtime field | +| `MatchdaySetup_ConsiderSportschauFixture_RuntimeFieldUnsigned` | `0xa258du` | German-compatible image / runtime field | +| `MatchdaySetup_EvaluatePoolsCoupon_RuntimeField` | `0xaf88c` | German-compatible image / runtime field | +| `MatchdaySetup_IndoorTournamentDraw_RuntimeField` | `0xbd424` | German-compatible image / runtime field | +| `MatchdaySetup_IndoorTournamentReset_RuntimeField` | `0xa2c87` | German-compatible image / runtime field | +| `MatchdaySetup_IndoorTournamentReset_TextPointer` | `0xaf0b8` | German-compatible image / runtime field | +| `MatchdaySetup_KickOff_RuntimeField` | `0xbd90d` | German-compatible image / runtime field | +| `MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField` | `0xa2529` | German-compatible image / runtime field | +| `MatchdaySetup_SettlePoolsCoupon_TextPointer` | `0xaf234` | German-compatible image / runtime field | +| `MatchdaySetup_SetupMatchday_TextPointer` | `0xaf058` | German-compatible image / runtime field | +| `MatchdaySetup_WinterPostponements_RuntimeField` | `0xa254f` | German-compatible image / runtime field | +| `MatchdaySetup_WinterPostponements_RuntimeField2` | `0xa2582` | German-compatible image / runtime field | +| `MinuteStatistics_SourceBarColor_RuntimeField` | `0xa3aa4` | German-compatible image / runtime field | +| `MissingInfofileText` | `0xa1620` | German-compatible image / runtime field | +| `Month_BoardMonth_TextPointer` | `0xaee4c` | German-compatible image / runtime field | +| `Month_BoardMonth_TextPointer2` | `0xaee50` | German-compatible image / runtime field | +| `Month_BoardMonth_TextPointer3` | `0xaee54` | German-compatible image / runtime field | +| `Month_BoardMonth_TextPointer4` | `0xaee58` | German-compatible image / runtime field | +| `Month_MonthChange_RuntimeField` | `0xbd4d4` | German-compatible image / runtime field | +| `Month_MonthChange_TextPointer` | `0xaee28` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer` | `0xaee2c` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer2` | `0xaee30` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer3` | `0xaee34` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer4` | `0xaee38` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer5` | `0xaee3c` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer6` | `0xaee40` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer7` | `0xaee44` | German-compatible image / runtime field | +| `Month_ReturnLoans_TextPointer8` | `0xaee48` | German-compatible image / runtime field | +| `Month_SearchProfileNews_TextPointer` | `0xaedd8` | German-compatible image / runtime field | +| `Month_SearchProfileNews_TextPointer2` | `0xaf254` | German-compatible image / runtime field | +| `NationalFriendlyPayerPrefixText` | `0xa000f` | German-compatible image / runtime field | +| `NextDeskManager` | `0xbd6cc` | German-compatible image / runtime field | +| `NoClubText` | `0xaec74` | German-compatible image / runtime field | +| `NoPlayerText` | `0xaec78` | German-compatible image / runtime field | +| `NoTeamSquadStart` | `0xa2c38` | German-compatible image / runtime field | +| `OfferSlots` | `0xbb844` | German-compatible image / runtime field | +| `Opportunities_FormatError_RuntimeField` | `0xa3a6e` | German-compatible image / runtime field | +| `Opportunities_FormatError_RuntimeField2` | `0xa3a80` | German-compatible image / runtime field | +| `Opportunities_FormatError_RuntimeField3` | `0xa3a92` | German-compatible image / runtime field | +| `Opportunities_FormatError_TextPointer` | `0xadefc` | German-compatible image / runtime field | +| `Opportunities_FormatError_TextPointer2` | `0xaec6c` | German-compatible image / runtime field | +| `Opportunities_Render_ExecutableField` | `0xadee0` | German-compatible image / runtime field | +| `Opportunities_Render_ExecutableField2` | `0xadee4` | German-compatible image / runtime field | +| `Opportunities_Render_ExecutableField3` | `0xadee8` | German-compatible image / runtime field | +| `Opportunities_Render_ExecutableField4` | `0xadeec` | German-compatible image / runtime field | +| `Opportunities_Render_RuntimeField` | `0xa3a68` | German-compatible image / runtime field | +| `Opportunities_Render_RuntimeField2` | `0xa3a69` | German-compatible image / runtime field | +| `Opportunities_Render_RuntimeField3` | `0xa3a6b` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer` | `0xadef0` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer2` | `0xaec58` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer3` | `0xaec5c` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer4` | `0xaec60` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer5` | `0xaec64` | German-compatible image / runtime field | +| `Opportunities_Render_TextPointer6` | `0xaec68` | German-compatible image / runtime field | +| `Opportunities_StatisticsWindow_RuntimeField` | `0xa3a9b` | German-compatible image / runtime field | +| `OriginalManagerCount` | `0xa376f` | German-compatible image / runtime field | +| `OtherGamesState_ForeignDetail_ExecutableField` | `0xa50ae` | German-compatible image / runtime field | +| `OtherGamesState_FormatNumber_ExecutableField` | `0xa10f0` | German-compatible image / runtime field | +| `OtherGamesState_OtherGamesStateFromGame_ExecutableField` | `0xa10eb` | German-compatible image / runtime field | +| `OtherGamesState_OtherGamesStateFromGame_ExecutableField2` | `0xa10ee` | German-compatible image / runtime field | +| `OtherGamesState_ResultText_ExecutableField` | `0xa1072` | German-compatible image / runtime field | +| `OtherGames_Layout_ExecutableField` | `0xae764` | German-compatible image / runtime field | +| `OutcomeDelayDisabled` | `0xa2532` | German-compatible image / runtime field | +| `OutcomeDelayDisabledUnsigned` | `0xa2532u` | German-compatible image / runtime field | +| `OutgoingTransfer_DrawFooter_TextPointer` | `0xae198` | German-compatible image / runtime field | +| `OutgoingTransfer_Line_ExecutableField` | `0xaf2cc` | German-compatible image / runtime field | +| `OutgoingTransfer_Line_ExecutableField2` | `0xaf2d0` | German-compatible image / runtime field | +| `OutgoingTransfer_Line_RuntimeField` | `0xa3767` | German-compatible image / runtime field | +| `OutgoingTransfer_Line_TextPointer` | `0xaf2e8` | German-compatible image / runtime field | +| `PenaltyTakerLabel` | `0x80cd2` | English image adapter | +| `PendingOffer_ConstructionNoticeDialog_TextPointer` | `0xaee1c` | German-compatible image / runtime field | +| `PendingOffer_ConstructionNoticeDialog_TextPointer2` | `0xaef84` | German-compatible image / runtime field | +| `PendingOffer_FormatError_ExecutableField` | `0xaed3c` | German-compatible image / runtime field | +| `PendingOffer_FormatError_ExecutableField2` | `0xaee08` | German-compatible image / runtime field | +| `PendingOffer_FormatError_ExecutableField2Unsigned` | `0xaee08u` | German-compatible image / runtime field | +| `PendingOffer_FormatError_ExecutableField3` | `0xaee24` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField` | `0xaedec` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField10` | `0xaf150` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField2` | `0xaedf0` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField2Unsigned` | `0xaedf0u` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField3` | `0xaedf4` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField4` | `0xaee04` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField5` | `0xaf13c` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField6` | `0xaf140` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField7` | `0xaf144` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField8` | `0xaf148` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferNoticeDialog_ExecutableField9` | `0xaf14c` | German-compatible image / runtime field | +| `PendingOffer_PendingOfferOwnerTeam_RuntimeField` | `0xbd6cd` | German-compatible image / runtime field | +| `PendingOffer_TransferLastWeekDialog_ExecutableField` | `0xaedcc` | German-compatible image / runtime field | +| `Pitch_FormatError_TextPointer` | `0xaf174` | German-compatible image / runtime field | +| `Pitch_FormatError_TextPointer2` | `0xaf178` | German-compatible image / runtime field | +| `Pitch_FormatError_TextPointer3` | `0xaf17c` | German-compatible image / runtime field | +| `Pitch_Render_RuntimeField` | `0xa3cbc` | German-compatible image / runtime field | +| `Pitch_Render_TextPointer` | `0xae0e4` | German-compatible image / runtime field | +| `Pitch_Render_TextPointer2` | `0xae0ec` | German-compatible image / runtime field | +| `Pitch_Render_TextPointer3` | `0xae0f0` | German-compatible image / runtime field | +| `Pitch_Render_TextPointer4` | `0xae0f4` | German-compatible image / runtime field | +| `Pitch_Render_TextPointer5` | `0xae0f8` | German-compatible image / runtime field | +| `Placements` | `0xbd38c` | German-compatible image / runtime field | +| `PlainBackground` | `0xa2569` | German-compatible image / runtime field | +| `PlanTicketPrice` | `0xa4856` | German-compatible image / runtime field | +| `PlayerBonuses` | `0xba38c` | German-compatible image / runtime field | +| `PlayerCard_PlayerCardMarketValue_RuntimeField` | `0xa431e` | German-compatible image / runtime field | +| `PlayerCards` | `0xba3b4` | German-compatible image / runtime field | +| `PlayerConditionTechniqueForm` | `0xba35c` | German-compatible image / runtime field | +| `PlayerDevelopmentBalance` | `0xbdaf8` | German-compatible image / runtime field | +| `PlayerIdentityWords` | `0xba364` | German-compatible image / runtime field | +| `PlayerNameOffsets` | `0xbb120` | German-compatible image / runtime field | +| `PlayerSkillWords` | `0xba368` | German-compatible image / runtime field | +| `Poach_ClubAskingPercent_TextPointer` | `0xaf280` | German-compatible image / runtime field | +| `Poach_ClubAskingPercent_TextPointer2` | `0xaf284` | German-compatible image / runtime field | +| `Poach_ClubAskingPercent_TextPointer3` | `0xaf288` | German-compatible image / runtime field | +| `Poach_ClubAskingPercent_TextPointer4` | `0xaf28c` | German-compatible image / runtime field | +| `Poach_StartPoach_TextPointer` | `0xaecb8` | German-compatible image / runtime field | +| `Poach_StartPoach_TextPointer2` | `0xaf26c` | German-compatible image / runtime field | +| `Poach_StartPoach_TextPointer3` | `0xaf270` | German-compatible image / runtime field | +| `Poach_StartPoach_TextPointer4` | `0xaf274` | German-compatible image / runtime field | +| `Poach_StartPoach_TextPointer5` | `0xaf278` | German-compatible image / runtime field | +| `Postponed` | `0xb627c` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer` | `0xae6c4` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer10` | `0xaeea8` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer11` | `0xaeeac` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer12` | `0xaeeb0` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer13` | `0xaeeb4` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer14` | `0xaeeb8` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer15` | `0xaeebc` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer2` | `0xaee88` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer3` | `0xaee8c` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer4` | `0xaee90` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer5` | `0xaee94` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer6` | `0xaee98` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer7` | `0xaee9c` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer8` | `0xaeea0` | German-compatible image / runtime field | +| `Prediction_TablePrediction_TextPointer9` | `0xaeea4` | German-compatible image / runtime field | +| `ProcessTimer_FormatError_RuntimeField` | `0xa4358` | German-compatible image / runtime field | +| `PurchaseTitleText` | `0xae18c` | German-compatible image / runtime field | +| `RealityMatch_FormatError_ExecutableField` | `0xa250d` | German-compatible image / runtime field | +| `RealityMatch_FormatError_ExecutableFieldUnsigned` | `0xa250du` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField2Unsigned` | `0xa4a6au` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField3Unsigned` | `0xa4a72u` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField4Unsigned` | `0xa4c23u` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField5Unsigned` | `0xa4ef3u` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField6Unsigned` | `0xa502du` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeField7Unsigned` | `0xa5039u` | German-compatible image / runtime field | +| `RealityMotion_FormatError_RuntimeFieldUnsigned` | `0xa4a62u` | German-compatible image / runtime field | +| `RealityMotion_RealityMotion_RuntimeFieldUnsigned` | `0xa4a52u` | German-compatible image / runtime field | +| `RealityReporter_Evaluate_TextPointer` | `0xaeb28` | German-compatible image / runtime field | +| `RealityReporter_Evaluate_TextPointer2` | `0xaeb2c` | German-compatible image / runtime field | +| `RealityReporter_Font_ExecutableField` | `0xa163a` | German-compatible image / runtime field | +| `RealityReporter_FormatError_TextPointer` | `0xa2369` | German-compatible image / runtime field | +| `RealityReporter_InitializeRealityReporter_RuntimeField` | `0xaf9bb` | German-compatible image / runtime field | +| `RealityScene_AdvanceRealityScene_RuntimeFieldUnsigned` | `0xa49bfu` | German-compatible image / runtime field | +| `RealityScene_AdvanceRealityScene_TextPointer` | `0xaec30` | German-compatible image / runtime field | +| `RealityScene_GoalMouth_RuntimeFieldUnsigned` | `0xa244eu` | German-compatible image / runtime field | +| `RealitySetup_InitializeReality_RuntimeFieldUnsigned` | `0xa49b8u` | German-compatible image / runtime field | +| `RealitySpace_RealityPenaltyArea_RuntimeField` | `0xa49b4` | German-compatible image / runtime field | +| `RealitySpace_RealityPenaltyArea_RuntimeField2` | `0xa49b5` | German-compatible image / runtime field | +| `RealitySpace_RealityPenaltyArea_RuntimeField3` | `0xa49b6` | German-compatible image / runtime field | +| `RealitySpace_RealityPenaltyArea_RuntimeField4` | `0xa49b7` | German-compatible image / runtime field | +| `RefereeProperties` | `0xbb3aa` | German-compatible image / runtime field | +| `ReplayChanceMode` | `0xa2521` | German-compatible image / runtime field | +| `ReplayFixtures` | `0xbb148` | German-compatible image / runtime field | +| `ReplayProgressionMode` | `0xa2518` | German-compatible image / runtime field | +| `ReplayResults` | `0xbb2fe` | German-compatible image / runtime field | +| `RoundNameTable` | `0xae09c` | German-compatible image / runtime field | +| `RuleOptionDefaults` | `0xa3650` | German-compatible image / runtime field | +| `SaveLoad_Render_ExecutableField` | `0xa148f` | German-compatible image / runtime field | +| `SaveLoad_Render_RuntimeField` | `0xa2334` | German-compatible image / runtime field | +| `SaveLoad_Render_RuntimeField2` | `0xa233f` | German-compatible image / runtime field | +| `SaveLoad_Render_RuntimeField3` | `0xa234a` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer` | `0xa1512` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer2` | `0xae5f0` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer3` | `0xae620` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer4` | `0xae624` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer5` | `0xae644` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer6` | `0xae648` | German-compatible image / runtime field | +| `SaveLoad_Render_TextPointer7` | `0xaeaa0` | German-compatible image / runtime field | +| `SavedCompetition` | `0xaf43c` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField` | `0xa3889` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField2` | `0xafb3a` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField3` | `0xb6234` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField4` | `0xbb29c` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField5` | `0xbb466` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField6` | `0xbb833` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField7` | `0xbb854` | German-compatible image / runtime field | +| `Savestate_Layout_ExecutableField8` | `0xbdb1a` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_ExecutableField` | `0xa3ce4` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_ExecutableField2` | `0xa3cec` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_ExecutableField3` | `0xa3cf4` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_RuntimeField` | `0xa3cfa` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_TextPointer` | `0xa3d03` | German-compatible image / runtime field | +| `SeasonEntrants_FormatError_TextPointer2` | `0xae7bc` | German-compatible image / runtime field | +| `SeasonEntrants_SeasonEntrantsFromGame_TextPointer` | `0xa254e` | German-compatible image / runtime field | +| `SeasonIndex` | `0xbb46a` | German-compatible image / runtime field | +| `SeasonPromotion_FormatError_RuntimeField` | `0xa3228` | German-compatible image / runtime field | +| `SeasonPromotion_FormatError_RuntimeFieldUnsigned` | `0xa3228u` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField` | `0xa2c8c` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField2` | `0xa2e94` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField3` | `0xa2e96` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField4` | `0xa2ee4` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField5` | `0xa2f84` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField6` | `0xa2fd4` | German-compatible image / runtime field | +| `Season_CareerSeasonSetup_RuntimeField7` | `0xbdb10` | German-compatible image / runtime field | +| `Season_ClubPopularity_TextPointer` | `0xaee7c` | German-compatible image / runtime field | +| `Season_ClubPopularity_TextPointer2` | `0xaee80` | German-compatible image / runtime field | +| `Season_LicenceWithdrawals_TextPointer` | `0xaf018` | German-compatible image / runtime field | +| `Season_LicenceWithdrawals_TextPointer2` | `0xaf01c` | German-compatible image / runtime field | +| `Season_LicenceWithdrawals_TextPointer3` | `0xaf020` | German-compatible image / runtime field | +| `Season_List_RuntimeField` | `0xbdd9c` | German-compatible image / runtime field | +| `Season_Promotion_ExecutableField` | `0xa3204` | German-compatible image / runtime field | +| `Season_Promotion_ExecutableField2` | `0xa3206` | German-compatible image / runtime field | +| `Season_Promotion_TextPointer` | `0xaf024` | German-compatible image / runtime field | +| `Season_SeasonAccounts_RuntimeField` | `0xbbcc4` | German-compatible image / runtime field | +| `Season_SeasonAccounts_TextPointer` | `0xaeba0` | German-compatible image / runtime field | +| `Season_SeasonAccounts_TextPointer2` | `0xaeba4` | German-compatible image / runtime field | +| `Season_SeasonAccounts_TextPointer3` | `0xaeba8` | German-compatible image / runtime field | +| `Season_SeasonAccounts_TextPointer4` | `0xaebcc` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer` | `0xaebac` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer2` | `0xaebb0` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer3` | `0xaebb4` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer4` | `0xaebb8` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer5` | `0xaebbc` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer6` | `0xaebc0` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer7` | `0xaebc4` | German-compatible image / runtime field | +| `Season_SeasonApplyProfitTax_TextPointer8` | `0xaebc8` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer` | `0xae210` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer2` | `0xae21c` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer3` | `0xaeb7c` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer4` | `0xaeb80` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer5` | `0xaeb84` | German-compatible image / runtime field | +| `Season_SeasonAwards_TextPointer6` | `0xaeb88` | German-compatible image / runtime field | +| `Season_SeasonEndSteps_RuntimeField` | `0xaf452` | German-compatible image / runtime field | +| `Season_SeasonEndSteps_RuntimeField2` | `0xaf4b2` | German-compatible image / runtime field | +| `Season_SeasonEvent_TextPointer` | `0xae1f0` | German-compatible image / runtime field | +| `Season_SeasonEvent_TextPointer2` | `0xae200` | German-compatible image / runtime field | +| `Season_SeasonEvent_TextPointer3` | `0xaeb70` | German-compatible image / runtime field | +| `Season_SeasonPlayers_ExecutableField` | `0xb9a58` | German-compatible image / runtime field | +| `Season_SeasonPlayers_RuntimeField` | `0xbb88a` | German-compatible image / runtime field | +| `Season_SeasonPlayers_RuntimeField2` | `0xbb893` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer` | `0xaf02c` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer2` | `0xaf030` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer3` | `0xaf034` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer4` | `0xaf038` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer5` | `0xaf03c` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer6` | `0xaf040` | German-compatible image / runtime field | +| `Season_SeasonPlayers_TextPointer7` | `0xaf044` | German-compatible image / runtime field | +| `Season_SeasonTickets_TextPointer` | `0xaefec` | German-compatible image / runtime field | +| `Season_SeasonTickets_TextPointer2` | `0xaeff0` | German-compatible image / runtime field | +| `Season_SeasonTickets_TextPointer3` | `0xaeff4` | German-compatible image / runtime field | +| `Season_SeasonTransition_RuntimeField` | `0xbb83b` | German-compatible image / runtime field | +| `SeriesRecords_Render_ExecutableField` | `0xa102e` | German-compatible image / runtime field | +| `SeriesRecords_Render_ExecutableField2` | `0xa1074` | German-compatible image / runtime field | +| `SeriesRecords_Render_ExecutableField3` | `0xa169d` | German-compatible image / runtime field | +| `SeriesRecords_Render_ExecutableField4` | `0xa16ac` | German-compatible image / runtime field | +| `SeriesSelector` | `0xa3960` | German-compatible image / runtime field | +| `Settings_File_ExecutableField` | `0xa2230` | German-compatible image / runtime field | +| `Settings_File_ExecutableField2` | `0xa2246` | German-compatible image / runtime field | +| `Settings_FormatError_RuntimeField` | `0xaf443` | German-compatible image / runtime field | +| `Settings_FormatError_TextPointer` | `0xa46a8` | German-compatible image / runtime field | +| `Settings_FormatError_TextPointer2` | `0xae1b8` | German-compatible image / runtime field | +| `Settings_FormatError_TextPointer3` | `0xaeb3c` | German-compatible image / runtime field | +| `Settings_FormatError_TextPointer4` | `0xaeb40` | German-compatible image / runtime field | +| `Settings_FormatError_TextPointer5` | `0xaeb4c` | German-compatible image / runtime field | +| `Settings_Letter_TextPointer` | `0xa4796` | German-compatible image / runtime field | +| `Settings_ProjectSettingsAvailability_RuntimeField` | `0xa4798` | German-compatible image / runtime field | +| `Settings_ProjectSettingsAvailability_RuntimeField2` | `0xa479f` | German-compatible image / runtime field | +| `Settings_ProjectSettingsAvailability_RuntimeField3` | `0xa47a0` | German-compatible image / runtime field | +| `Settings_ProjectSettingsAvailability_RuntimeField4` | `0xa47a7` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField` | `0xa4804` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField10` | `0xa4838` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField11` | `0xa483a` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField2` | `0xa4808` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField3` | `0xa480c` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField4` | `0xa481c` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField5` | `0xa4824` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField6` | `0xa4828` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField7` | `0xa482c` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField8` | `0xa482f` | German-compatible image / runtime field | +| `Setup_FormatError_RuntimeField9` | `0xa4835` | German-compatible image / runtime field | +| `SolidPanelBackground` | `0xa2560` | German-compatible image / runtime field | +| `Spending` | `0xbd4c8` | German-compatible image / runtime field | +| `SportschauAwards_FinishSportschauAwards_RuntimeField` | `0xa2533` | German-compatible image / runtime field | +| `SportschauAwards_MatchdayIntroView_RuntimeField` | `0xa2572` | German-compatible image / runtime field | +| `SportschauAwards_MatchdayIntroView_TextPointer` | `0xae6d8` | German-compatible image / runtime field | +| `SportschauAwards_SportschauTeamInfoView_RuntimeField` | `0xa253c` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField` | `0xa47e0` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField2` | `0xa47e4` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField3` | `0xa47e8` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField4` | `0xa47ec` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField5` | `0xa47f0` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField6` | `0xa47f4` | German-compatible image / runtime field | +| `SportschauRating_SportschauRatingTables_RuntimeField7` | `0xa47fb` | German-compatible image / runtime field | +| `Sportschau_FormatError_RuntimeField` | `0xa231d` | German-compatible image / runtime field | +| `Sportschau_FormatError_RuntimeField2` | `0xa47f8` | German-compatible image / runtime field | +| `Sportschau_FormatError_RuntimeField3` | `0xa47ff` | German-compatible image / runtime field | +| `Sportschau_FormatError_TextPointer` | `0xaeb6c` | German-compatible image / runtime field | +| `Sportschau_Render_RuntimeField` | `0xa4768` | German-compatible image / runtime field | +| `Sportschau_Render_RuntimeField2` | `0xa476c` | German-compatible image / runtime field | +| `Sportschau_Render_RuntimeField3` | `0xa4770` | German-compatible image / runtime field | +| `Sportschau_Render_RuntimeField4` | `0xa4774` | German-compatible image / runtime field | +| `Sportschau_Render_RuntimeField5` | `0xa4778` | German-compatible image / runtime field | +| `Sportschau_Render_TextPointer` | `0xa1188` | German-compatible image / runtime field | +| `Sportschau_Render_TextPointer2` | `0xa4764` | German-compatible image / runtime field | +| `Sportschau_Render_TextPointer3` | `0xaf180` | German-compatible image / runtime field | +| `Sportschau_Result_ExecutableField` | `0xa151b` | German-compatible image / runtime field | +| `Sportschau_Result_TextPointer` | `0xa151d` | German-compatible image / runtime field | +| `Sportschau_Result_TextPointer2` | `0xae1c0` | German-compatible image / runtime field | +| `SquadSlots` | `0xbb128` | German-compatible image / runtime field | +| `StadiumBlockCapacities` | `0xa42fa` | German-compatible image / runtime field | +| `StadiumPriceTable` | `0xa3699` | German-compatible image / runtime field | +| `Stadium_CopyCrop_TextPointer` | `0xade98` | German-compatible image / runtime field | +| `Stadium_CopyCrop_TextPointer2` | `0xadea4` | German-compatible image / runtime field | +| `Stadium_CopyCrop_TextPointer3` | `0xaec48` | German-compatible image / runtime field | +| `Stadium_CopyCrop_TextPointer4` | `0xaec4c` | German-compatible image / runtime field | +| `Stadium_CopyCrop_TextPointer5` | `0xaec50` | German-compatible image / runtime field | +| `Stadium_FormatError_ExecutableField` | `0xa1375` | German-compatible image / runtime field | +| `Stadium_FormatError_ExecutableField2` | `0xa1377` | German-compatible image / runtime field | +| `Stadium_FormatError_ExecutableField3` | `0xaef1c` | German-compatible image / runtime field | +| `Stadium_FormatError_RuntimeField` | `0xaef10` | German-compatible image / runtime field | +| `Stadium_Out_ExecutableField` | `0xa137b` | German-compatible image / runtime field | +| `Stadium_Out_ExecutableField2` | `0xa42d5` | German-compatible image / runtime field | +| `Stadium_Out_ExecutableField3` | `0xa42d6` | German-compatible image / runtime field | +| `Stadium_Out_ExecutableField4` | `0xae9b4` | German-compatible image / runtime field | +| `Stadium_Out_ExecutableField5` | `0xae9d0` | German-compatible image / runtime field | +| `Stadium_Out_RuntimeField` | `0xa42b5` | German-compatible image / runtime field | +| `Stadium_Out_RuntimeField2` | `0xa42b7` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer` | `0xaef20` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer2` | `0xaef24` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer3` | `0xaef28` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer4` | `0xaef2c` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer5` | `0xaef30` | German-compatible image / runtime field | +| `Stadium_Out_TextPointer6` | `0xaef34` | German-compatible image / runtime field | +| `Stadium_PeripheryObjectAt_RuntimeField` | `0xa4275` | German-compatible image / runtime field | +| `Stadium_PeripheryObjectContains_ExecutableField` | `0xa3feb` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer` | `0xa137d` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer10` | `0xaef74` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer2` | `0xaef08` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer3` | `0xaef0c` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer4` | `0xaef14` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer5` | `0xaef18` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer6` | `0xaef5c` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer7` | `0xaef60` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer8` | `0xaef64` | German-compatible image / runtime field | +| `Stadium_RenderBlockExpansion_TextPointer9` | `0xaef70` | German-compatible image / runtime field | +| `Stadium_RenderInvestmentDialog_TextPointer` | `0xaef04` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_ExecutableField` | `0xa40e7` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_ExecutableField2` | `0xaef4c` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField` | `0xa3fed` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField2` | `0xa3fef` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField3` | `0xa3ff1` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField4` | `0xa4093` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField5` | `0xa4095` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField6` | `0xa4267` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField7` | `0xa4283` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_RuntimeField8` | `0xa4291` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer` | `0xae940` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer2` | `0xaef38` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer3` | `0xaef3c` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer4` | `0xaef40` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer5` | `0xaef44` | German-compatible image / runtime field | +| `Stadium_RenderPanorama_TextPointer6` | `0xaef48` | German-compatible image / runtime field | +| `Stadium_StadiumDataFromGame_ExecutableField` | `0xa1054` | German-compatible image / runtime field | +| `Stadium_StadiumDataFromGame_TextPointer` | `0xaec44` | German-compatible image / runtime field | +| `StatisticsRankings_FormatError_RuntimeField` | `0xa3caa` | German-compatible image / runtime field | +| `StatisticsRankings_FormatError_RuntimeField2` | `0xa3cb3` | German-compatible image / runtime field | +| `StockExchange` | `0xac888` | German-compatible image / runtime field | +| `Strengths_Fill_RuntimeField` | `0xa454a` | German-compatible image / runtime field | +| `Strengths_Fill_RuntimeField2` | `0xa454c` | German-compatible image / runtime field | +| `Strengths_Fill_RuntimeField3` | `0xa4578` | German-compatible image / runtime field | +| `Strengths_Fill_TextPointer` | `0xa1477` | German-compatible image / runtime field | +| `Strengths_PointerDown_RuntimeField` | `0xa456f` | German-compatible image / runtime field | +| `Strengths_SelectorAt_RuntimeField` | `0xa4562` | German-compatible image / runtime field | +| `Strengths_SelectorAt_RuntimeField2` | `0xa4564` | German-compatible image / runtime field | +| `Strengths_Selector_RuntimeField` | `0xa4566` | German-compatible image / runtime field | +| `Strengths_Selector_RuntimeField2` | `0xa4568` | German-compatible image / runtime field | +| `SyntheticCupAlternateResultBlock` | `0xa8280` | Test fixture location or bound | +| `SyntheticCupFifthParticipantBlock` | `0xa8080` | Test fixture location or bound | +| `SyntheticCupFifthResultBlock` | `0xa82a0` | Test fixture location or bound | +| `SyntheticCupFirstLegBegin` | `0xa4000` | Test fixture location or bound | +| `SyntheticCupFirstResultPadding` | `0xa8202` | Test fixture location or bound | +| `SyntheticCupFourthParticipantBlock` | `0xa8060` | Test fixture location or bound | +| `SyntheticCupFourthParticipantValue` | `0xa8062` | Test fixture location or bound | +| `SyntheticCupFourthResultBlock` | `0xa8260` | Test fixture location or bound | +| `SyntheticCupParticipantsBegin` | `0xa8000` | Test fixture location or bound | +| `SyntheticCupResultsBegin` | `0xa8200` | Test fixture location or bound | +| `SyntheticCupSecondLegBegin` | `0xa4200` | Test fixture location or bound | +| `SyntheticCupSecondParticipantBlock` | `0xa8020` | Test fixture location or bound | +| `SyntheticCupSecondResultBlock` | `0xa8220` | Test fixture location or bound | +| `SyntheticCupSecondResultPadding` | `0xa8204` | Test fixture location or bound | +| `SyntheticCupThirdParticipantBlock` | `0xa8040` | Test fixture location or bound | +| `SyntheticCupThirdResultBlock` | `0xa8240` | Test fixture location or bound | +| `SyntheticCupThirdResultPadding` | `0xa8242` | Test fixture location or bound | +| `SyntheticCupWorkspaceBegin` | `0xa8400` | Test fixture location or bound | +| `SystemManagerNameText` | `0xaea94` | German-compatible image / runtime field | +| `TableFlags` | `0xa3883` | German-compatible image / runtime field | +| `TableForecast_InvalidArgument_RuntimeField` | `0xbd8f7` | German-compatible image / runtime field | +| `TacticsBoards` | `0xb327c` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField` | `0xa20cb` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField2` | `0xa20d2` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField3` | `0xa20d3` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField4` | `0xa20db` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField5` | `0xa20e3` | German-compatible image / runtime field | +| `Tactics_Click_RuntimeField6` | `0xa20f2` | German-compatible image / runtime field | +| `Tactics_DrawSetting_ExecutableFieldUnsigned` | `0xa1fb4u` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField` | `0xa1fb0` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField10` | `0xa202c` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField11` | `0xa2083` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField12` | `0xa2084` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField2` | `0xa1ffc` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField3` | `0xa1ffd` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField4` | `0xa2004` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField5` | `0xa2005` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField6` | `0xa2010` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField7` | `0xa2014` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField8` | `0xa201c` | German-compatible image / runtime field | +| `Tactics_DrawSetting_RuntimeField9` | `0xa2024` | German-compatible image / runtime field | +| `Tactics_Render_TextPointer` | `0xaf24c` | German-compatible image / runtime field | +| `TeamFlags` | `0xba3c0` | German-compatible image / runtime field | +| `TeamMorale` | `0xba37c` | German-compatible image / runtime field | +| `TeamStatistics_Render_ExecutableField` | `0xa16ae` | German-compatible image / runtime field | +| `TeamStatistics_Render_RuntimeField` | `0xa3886` | German-compatible image / runtime field | +| `TeamStatistics_Render_RuntimeField2` | `0xa5116` | German-compatible image / runtime field | +| `TeamStatistics_Render_RuntimeField3` | `0xae530` | German-compatible image / runtime field | +| `TeamStatistics_Render_RuntimeField3Unsigned` | `0xae530u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer` | `0xae4a8` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer10` | `0xae550` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer10Unsigned` | `0xae550u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer11` | `0xae558` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer12` | `0xae55c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer13` | `0xae560` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer14` | `0xae564` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer15` | `0xae568` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer16` | `0xae56c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer17` | `0xae570` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer18` | `0xae574` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer18Unsigned` | `0xae574u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer19` | `0xae578` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer19Unsigned` | `0xae578u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer2` | `0xae4e8` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer20` | `0xae57c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer20Unsigned` | `0xae57cu` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer21` | `0xae588` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer22` | `0xaeb90` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer22Unsigned` | `0xaeb90u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer23` | `0xaeb94` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer24` | `0xaeb98` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer25` | `0xaeb9c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer3` | `0xae508` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer4` | `0xae514` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer5` | `0xae53c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer5Unsigned` | `0xae53cu` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer6` | `0xae540` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer6Unsigned` | `0xae540u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer7` | `0xae544` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer7Unsigned` | `0xae544u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer8` | `0xae548` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer8Unsigned` | `0xae548u` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointer9` | `0xae54c` | German-compatible image / runtime field | +| `TeamStatistics_Render_TextPointerUnsigned` | `0xae4a8u` | German-compatible image / runtime field | +| `TeamStatistics_SourceLeagueName_RuntimeField` | `0xbdb8d` | German-compatible image / runtime field | +| `Teams` | `0xb5e14` | German-compatible image / runtime field | +| `TeamsWithSquads` | `0xa2c2e` | German-compatible image / runtime field | +| `TextGradientDisabled` | `0xa2557` | German-compatible image / runtime field | +| `TextGradientMode` | `0xa3648` | German-compatible image / runtime field | +| `TextPointerTable` | `0xade00` | German-compatible image / runtime field | +| `TitleText` | `0xae194` | German-compatible image / runtime field | +| `Titles` | `0xaf450` | German-compatible image / runtime field | +| `TopScorers_MetricTextAddress_ExecutableField` | `0xae228` | German-compatible image / runtime field | +| `TopScorers_MetricTextAddress_ExecutableField2` | `0xae22c` | German-compatible image / runtime field | +| `TopScorers_MetricTextAddress_ExecutableField3` | `0xae230` | German-compatible image / runtime field | +| `TopScorers_Render_TextPointer` | `0xaeb8c` | German-compatible image / runtime field | +| `TopScorers_ScopeTextAddress_ExecutableField` | `0xae234` | German-compatible image / runtime field | +| `TopScorers_ScopeTextAddress_ExecutableField2` | `0xae238` | German-compatible image / runtime field | +| `Toto_FormatError_RuntimeField` | `0xaf884` | German-compatible image / runtime field | +| `Toto_Render_ExecutableField` | `0xa143c` | German-compatible image / runtime field | +| `Toto_Render_ExecutableField2` | `0xa143e` | German-compatible image / runtime field | +| `Toto_Render_RuntimeField` | `0xa23c1` | German-compatible image / runtime field | +| `Toto_Render_RuntimeField2` | `0xa4536` | German-compatible image / runtime field | +| `Toto_Render_TextPointer` | `0xae114` | German-compatible image / runtime field | +| `Toto_Render_TextPointer2` | `0xaf238` | German-compatible image / runtime field | +| `Toto_Render_TextPointer3` | `0xaf23c` | German-compatible image / runtime field | +| `TournamentName` | `0xae738` | German-compatible image / runtime field | +| `TrainingCamp_Click_RuntimeField` | `0xa445b` | German-compatible image / runtime field | +| `TrainingCamp_Click_RuntimeField2` | `0xa4463` | German-compatible image / runtime field | +| `TrainingCamp_FocusControls_RuntimeField` | `0xa4457` | German-compatible image / runtime field | +| `TrainingCamp_FocusControls_RuntimeField2` | `0xa446b` | German-compatible image / runtime field | +| `TrainingCamp_FocusControls_TextPointer` | `0xa4474` | German-compatible image / runtime field | +| `TrainingCamp_ResortDetails_RuntimeField` | `0xa4453` | German-compatible image / runtime field | +| `Training_Button_RuntimeField` | `0xa435f` | German-compatible image / runtime field | +| `Training_Click_RuntimeField` | `0xa43b7` | German-compatible image / runtime field | +| `Training_Click_RuntimeField2` | `0xa43bf` | German-compatible image / runtime field | +| `Training_Click_RuntimeField3` | `0xa43c7` | German-compatible image / runtime field | +| `Training_Click_RuntimeField4` | `0xa43cb` | German-compatible image / runtime field | +| `Training_Click_RuntimeField5` | `0xa43cf` | German-compatible image / runtime field | +| `Training_Click_RuntimeField6` | `0xa43d3` | German-compatible image / runtime field | +| `Training_Click_RuntimeField7` | `0xa43d7` | German-compatible image / runtime field | +| `Training_Click_RuntimeField8` | `0xa43db` | German-compatible image / runtime field | +| `Training_Click_RuntimeField9` | `0xa43df` | German-compatible image / runtime field | +| `Training_Render_RuntimeField` | `0xa43a3` | German-compatible image / runtime field | +| `Training_Render_TextPointer` | `0xa43a7` | German-compatible image / runtime field | +| `Training_Render_TextPointer2` | `0xa43af` | German-compatible image / runtime field | +| `Training_Render_TextPointer3` | `0xae2e4` | German-compatible image / runtime field | +| `Training_Render_TextPointer4` | `0xaf19c` | German-compatible image / runtime field | +| `Training_Render_TextPointer5` | `0xaf1a0` | German-compatible image / runtime field | +| `Training_Render_TextPointer6` | `0xaf1a4` | German-compatible image / runtime field | +| `TransferHistory_FormatError_RuntimeField` | `0xa39a0` | German-compatible image / runtime field | +| `TransferHistory_FormatError_TextPointer` | `0xa1048` | German-compatible image / runtime field | +| `TransferMarket_Click_RuntimeField` | `0xa211e` | German-compatible image / runtime field | +| `TransferMarket_Click_RuntimeField2` | `0xa2120` | German-compatible image / runtime field | +| `TransferMarket_Click_RuntimeField3` | `0xa2122` | German-compatible image / runtime field | +| `TransferMarket_ListedPlayers_RuntimeField` | `0xb6235` | German-compatible image / runtime field | +| `TransferMarket_Rect_ExecutableField` | `0xa0047` | German-compatible image / runtime field | +| `TransferMarket_Rect_ExecutableField2` | `0xa004a` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer` | `0xa0041` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer2` | `0xa0045` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer3` | `0xae148` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer4` | `0xae14c` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer5` | `0xae150` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer6` | `0xaecac` | German-compatible image / runtime field | +| `TransferMarket_Rect_TextPointer7` | `0xaf250` | German-compatible image / runtime field | +| `TransferMarket_Render_TextPointer` | `0xaf264` | German-compatible image / runtime field | +| `Turn_EventEnd_RuntimeField` | `0xbdb1c` | German-compatible image / runtime field | +| `Turn_FinishEvent_ExecutableField` | `0xb63dc` | German-compatible image / runtime field | +| `Week_AutoTraining_ExecutableField` | `0x6e8ca` | English image adapter | +| `Week_AutoTraining_ExecutableField2` | `0x6eac8` | English image adapter | +| `Week_AutoTraining_ExecutableField3` | `0xa86ce` | German-compatible image / runtime field | +| `Week_AutoTraining_ExecutableField4` | `0xae8c6` | German-compatible image / runtime field | +| `Weekly_AdvertisingOffers_TextPointer` | `0xaee84` | German-compatible image / runtime field | +| `Weekly_DecideBids_TextPointer` | `0xaedd0` | German-compatible image / runtime field | +| `Weekly_DecideBids_TextPointer2` | `0xaedd4` | German-compatible image / runtime field | +| `Weekly_DecideBids_TextPointer3` | `0xaeddc` | German-compatible image / runtime field | +| `Weekly_ExecuteTransfer_RuntimeField` | `0xa253b` | German-compatible image / runtime field | +| `Weekly_ExecuteTransfer_TextPointer` | `0xaee0c` | German-compatible image / runtime field | +| `Weekly_ExecuteTransfer_TextPointer2` | `0xaee10` | German-compatible image / runtime field | +| `Weekly_ExecuteTransfer_TextPointer3` | `0xaee14` | German-compatible image / runtime field | +| `Weekly_ExecuteTransfer_TextPointer4` | `0xaee18` | German-compatible image / runtime field | +| `Weekly_FacilityAgeing_TextPointer` | `0xaeef8` | German-compatible image / runtime field | +| `Weekly_FacilityDamage_TextPointer` | `0xae850` | German-compatible image / runtime field | +| `Weekly_FacilityDamage_TextPointer2` | `0xae868` | German-compatible image / runtime field | +| `Weekly_FacilityDamage_TextPointer3` | `0xae978` | German-compatible image / runtime field | +| `Weekly_FacilityDamage_TextPointer4` | `0xaeed0` | German-compatible image / runtime field | +| `Weekly_FacilityDamage_TextPointer5` | `0xaeed4` | German-compatible image / runtime field | +| `Weekly_Fail_TextPointer` | `0xaee20` | German-compatible image / runtime field | +| `Weekly_InterestedManagers_RuntimeField` | `0xa2544` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer` | `0xaef90` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer2` | `0xaef94` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer3` | `0xaef98` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer4` | `0xaef9c` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer5` | `0xaefa8` | German-compatible image / runtime field | +| `Weekly_ManagerOffers_TextPointer6` | `0xaf358` | German-compatible image / runtime field | +| `Weekly_PendingSettleHumanBuyer_RuntimeField` | `0xbdb93` | German-compatible image / runtime field | +| `Weekly_PendingSettle_TextPointer` | `0xaee00` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_RuntimeField` | `0xbb848` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_RuntimeField2` | `0xbb84c` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_RuntimeField3` | `0xbb850` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer` | `0xaefb8` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer10` | `0xaefe0` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer2` | `0xaefbc` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer3` | `0xaefc0` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer4` | `0xaefc4` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer5` | `0xaefc8` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer6` | `0xaefd0` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer7` | `0xaefd4` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer8` | `0xaefd8` | German-compatible image / runtime field | +| `Weekly_PreMatchOffer_TextPointer9` | `0xaefdc` | German-compatible image / runtime field | +| `Weekly_ProcessPendingBatch_TextPointer` | `0xaefe4` | German-compatible image / runtime field | +| `Weekly_ProcessPendingBatch_TextPointer2` | `0xaefe8` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer` | `0xaeed8` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer2` | `0xaeedc` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer3` | `0xaeee0` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer4` | `0xaeee4` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer5` | `0xaeee8` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer6` | `0xaeeec` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer7` | `0xaeef0` | German-compatible image / runtime field | +| `Weekly_SeasonTicketCompensation_TextPointer8` | `0xaeef4` | German-compatible image / runtime field | +| `Weekly_TransferListCountdown_TextPointer` | `0xaede4` | German-compatible image / runtime field | +| `Weekly_TransferListCountdown_TextPointer2` | `0xaede8` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer` | `0xae8c4` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer2` | `0xaee5c` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer3` | `0xaee60` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer4` | `0xaee64` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer5` | `0xaee68` | German-compatible image / runtime field | +| `Weekly_WeeklyProcessing_TextPointer6` | `0xaee6c` | German-compatible image / runtime field | +| `WorldCupStatistics_FormatError_RuntimeField` | `0xa3990` | German-compatible image / runtime field | +| `WorldCupStatistics_FormatError_RuntimeField2` | `0xa3994` | German-compatible image / runtime field | +| `WorldCupStatistics_FormatError_RuntimeField3` | `0xa3998` | German-compatible image / runtime field | +| `WorldCupStatistics_Render_ExecutableField` | `0xa1045` | German-compatible image / runtime field | +| `EnglishFourTeamFixtureTable` | `0x6eea0` | English image adapter | +| `EnglishSixTeamFixtureTable` | `0x6eed4` | English image adapter | +| `EnglishTwelveTeamFixtureTable` | `0x6f0bc` | English image adapter | +| `EnglishTwentyTeamFixtureTable` | `0x6ee40` | English image adapter | diff --git a/docs/formats/FBM.md b/docs/formats/FBM.md new file mode 100644 index 0000000..69ba384 --- /dev/null +++ b/docs/formats/FBM.md @@ -0,0 +1,33 @@ +# Savegame container: `.FBM` + +`src/formats/fbm.cpp` reads the outer container. `src/formats/savestate.cpp` splits the decoded state; `src/game/save.cpp` writes the normal save representation. Saving goes through `CareerSession` so the manager, phase and committed state are validated. + +## Container layout + +| Part | Size | Meaning | +|---|---|---| +| Plain header | Variable | Manager/date information for the load list | +| Signature area | 10 bytes | Eight-byte `KRON_FBM` signature and two following bytes | +| First ID | u32 | Container identifier | +| Version | 6 bytes | NUL-terminated version field, normally `V2.24` for the supported state layout | +| Second ID | u32 | Save identifier | +| Random byte | u8 | Header value | +| Initial key | u8 | Rolling-cipher seed | +| Stream | Remaining bytes except checksum | Encrypted state and name pools | +| Checksum | u8 | Initial key plus all decoded stream bytes, modulo 256 | + +The loader searches for the signature after the plain header and checks the fixed fields fit. A bad checksum is represented by `Savegame::checksum_ok`; callers must decide whether to accept the save. Neither the cipher nor this checksum provides security or authenticity. + +For each byte, decrypt with `plain = (encrypted - key) XOR key`, or encrypt with `encrypted = (plain XOR key) + key`. Reduce all byte arithmetic modulo 256, then subtract `0x29` from the key before the next byte. + +## Decoded stream + +The supported layout contains a fixed ordered block table, followed by four name pools. Blocks have no tags or encoded lengths. Their sizes depend on the layout and database counts; `kBlocks` in `src/formats/savestate.cpp` is the authoritative order. Some blocks describe fixed arrays and others hold the contents of legacy dynamically allocated tables. The final optional team-record block is present only when its saved presence field is nonzero. + +Each name pool has a u16 byte length followed by that many bytes, in club, player, referee and stadium order. These pools preserve renamed entities. The splitter rejects missing/truncated blocks or pools and requires exact stream consumption. See [STATE](STATE.md) for interpreted records and [M3D](M3D.md) for pool references. + +## Edition compatibility + +Original Football Limited V2.20 saves use a different state block list despite sharing the signature and rolling cipher. They are not interchangeable with the V2.24 layout. Reading an English installation and importing its original saves are separate features; do not edit a version string to bypass the distinction. OpenBMH's own English careers use the session's supported save representation. + +Keep a backup before using a save with another engine version. Unknown bytes retained for compatibility are not safe targets for direct client manipulation. diff --git a/docs/formats/FNT.md b/docs/formats/FNT.md new file mode 100644 index 0000000..e27e8d7 --- /dev/null +++ b/docs/formats/FNT.md @@ -0,0 +1,27 @@ +# Bitmap fonts: `.FNT` + +`src/formats/font.cpp` loads a 28-byte little-endian header followed by a bitmap and glyph tables. The layout resembles an Amiga TextFont with pointer slots stored as placeholders. + +| Offset | Type | Meaning | +|---|---|---| +| 0 | u16 | Glyph height | +| 2 | u8 | Style | +| 3 | u8 | Flags; value 2 omits the spacing table | +| 4 | u16 | Nominal advance | +| 6 | u16 | Baseline | +| 8 | u8 | First character | +| 9 | u8 | Last character | +| 10 | u16 | Reserved | +| 12 | u32 | Bitmap pointer placeholder | +| 16 | u16 | Bytes per bitmap row | +| 18 | u16 | Reserved | +| 20 | u32 | Glyph-location pointer placeholder | +| 24 | u32 | Spacing pointer placeholder | + +Let `n = last - first + 2`; the extra entry is the replacement glyph. After the header come: + +1. `height * row_bytes` bytes of one-bit bitmap, most significant bit first. +2. `n` pairs of u16 bit offset and bit width. +3. `n` signed 16-bit advances, unless flags equal 2. Fixed-width glyphs use the nominal advance instead. + +The loader requires the computed total size to match. Characters outside the supported range use the replacement glyph. Legacy character conversion is described in the [format index](README.md); use the supplied font with its matching text encoding. diff --git a/docs/formats/LE.md b/docs/formats/LE.md new file mode 100644 index 0000000..f2b680b --- /dev/null +++ b/docs/formats/LE.md @@ -0,0 +1,15 @@ +# Executable images used as data + +OpenBMH reads tables and text from the user's original executable. It does not execute that program. The file is not part of the OpenBMH distribution. + +## German LE image + +`src/formats/le.cpp` loads the DOS/4GW Linear Executable format. The DOS header's u32 field at `0x3c` locates the LE header. Object records define virtual sizes, image bases and page ranges. Page-map entries locate file data; unloaded areas are zero-filled. The image applies supported internal relocation records before consumers follow pointers. + +The reader supports the internal offset/selector forms required by the installation. External fixups are rejected. Bounds and object validation belong to the loader; arbitrary executable formats are not accepted merely because they begin with an MZ stub. String access decodes the legacy single-byte encoding. + +## English X-32 image + +Football Limited uses a different executable layout. `src/launch/fltd.cpp` prepares supported English executable data and maps the required tables into the engine's expected data view. It is not an instruction emulator or a conversion of English game rules into a separate engine. + +The [executable layout reference](EXECUTABLE_LAYOUT.md) describes supported table locations and semantic layout identifiers. A byte address is meaningful only with its edition and image layout. Application APIs should expose the table's meaning rather than an address-derived field name. diff --git a/docs/formats/M3D.md b/docs/formats/M3D.md new file mode 100644 index 0000000..7dca532 --- /dev/null +++ b/docs/formats/M3D.md @@ -0,0 +1,37 @@ +# Master database: `M3D.MAN` / `M3E.MAN` + +`load_database` in `src/formats/m3d.cpp` reads an unencrypted sequence of string pools and parallel tables. Counts are supplied by `DbCounts`, not stored in the file. Default counts are 419 clubs, 2,574 players, 168 team records and an auxiliary extent of 3,096. Readers must agree on these counts; changing a count without rebuilding dependent tables does not define a valid new database. + +Let `C`, `P`, `T` and `A` denote those counts. The stream order is: + +| Size | Content | +|---|---| +| 4 × u16 | Byte lengths of club, player, referee and stadium name pools | +| `A + 50` bytes | Player bonus/flag table and auxiliary entries | +| Sum of pool lengths | Four consecutive NUL-separated name pools | +| `C` × u16 | Club name offsets into pool 0 | +| `P` × u16 | Player name offsets into pool 1 | +| 100 bytes | Auxiliary table | +| `T` × u16 | Auxiliary team table | +| `C` × u16 | Club crest/flag words; low nine bits select a crest | +| 251 + 189 + 50 + 419 + 168 bytes | Five fixed-size auxiliary tables | +| `2 * (A - 4) + 108` bytes | Squad-list words | +| `P` × u32, three times | Three parallel player-word tables | + +The loader checks bounds and requires complete consumption. Pool references are byte offsets; they are neither club IDs nor Unicode indices. The name pools also occur in [savegame trailers](FBM.md). A career initialises and reorders parts of the database, so its runtime team IDs can differ from the master club index. + +## Player words + +A squad-list word stores a twelve-bit player ID and four flag bits. Player ID `0xfff` means no player. The `Player` accessors in `src/formats/m3d.hpp` interpret the three words in file order: + +| Word | Bits | Meaning | +|---|---|---| +| 1 | 0–6 | Form | +| 1 | 7–13 | Technique | +| 1 | 14–20 | Condition | +| 2 | 0–13 | Seven two-bit skills: teamplay, speed, shooting, passing, tackling, free kick, corner | +| 2 | 27–31 | Nationality | +| 3 | 0–1 | Position: goalkeeper, defender, midfielder, forward | +| 3 | 21–25 | Age minus 16 | + +Other bits carry additional state or remain uninterpreted by these accessors. Preserve them when changing a supported field. Display strength is `min((((form >> 3) + 94) * (technique + condition) / 100) / 2, 99)` with integer division in that order. It is a derived value, not an extra database field. diff --git a/docs/formats/M3DAT.md b/docs/formats/M3DAT.md new file mode 100644 index 0000000..bc73714 --- /dev/null +++ b/docs/formats/M3DAT.md @@ -0,0 +1,7 @@ +# Formation coordinates: `M3.DAT` + +The file is a 1,408-byte raw block containing four 352-byte manager slots. Each slot contains an outdoor and indoor set, each with eight 22-byte formation records. + +A record stores eleven horizontal coordinates followed by eleven vertical coordinates. For a formation `f` and player slot `p`, the horizontal coordinate is at `set_base + f * 22 + p`; the vertical coordinate is eleven bytes later. The indoor set begins 176 bytes into the manager slot. + +Career initialisation copies the first manager slot over the other three. Subsequently the manager-specific block is retained in [FBM](FBM.md). The semantic accessor is `GameState::formation_position` in `src/game/state.cpp`. Coordinates belong to the game's pitch grid, not directly to screen pixels. diff --git a/docs/formats/M3MEN.md b/docs/formats/M3MEN.md new file mode 100644 index 0000000..98225f9 --- /dev/null +++ b/docs/formats/M3MEN.md @@ -0,0 +1,20 @@ +# Desktop layout: `.MEN` + +A desktop layout is 864 bytes: 54 entries of 16 bytes, without a header or encryption. `src/ui/desk_state.cpp` interprets the list. New careers initialise manager slots from the installation's layout; saved careers retain their layouts in [FBM](FBM.md). + +Entry zero is the list head. Byte 5 contains the first visible entry; each following entry uses byte 5 for its successor and byte 6 for its predecessor. Index zero terminates a chain and `0xff` denotes an unlisted entry. The reader checks indices and detects cycles. + +| Offset within entry | Type | Meaning | +|---|---|---| +| 0 | u16 | Horizontal coordinate; bit `0x1000` hides the entry | +| 2 | u8 | Vertical coordinate | +| 3 | u8 | Width | +| 4 | u8 | Height | +| 5 | u8 | Next entry | +| 6 | u8 | Previous entry | +| 7–11 | bytes | Reserved | +| 12 | u8 | Item kind | +| 13 | u8 | Drawer state; bit 7 indicates open | +| 14–15 | bytes | Reserved | + +Icon kinds occupy 0–29; drawer kinds occupy 50–72. The graphical client decides which kinds it can display and which actions are available in the current mode. A kind number is not a console window ID. Unrecognised or inactive layout data must not be interpreted as an executable action. diff --git a/docs/formats/README.md b/docs/formats/README.md new file mode 100644 index 0000000..d0f5a10 --- /dev/null +++ b/docs/formats/README.md @@ -0,0 +1,25 @@ +# File formats + +OpenBMH reads files from a game installation supplied by the user. This directory documents their structure and the implementation's interfaces; it does not distribute game content or inventories of extracted text or artwork. + +Unless a page says otherwise, integer fields are little endian. Legacy strings use a single-byte encoding; the German character substitutions are handled by `iso646de_to_utf8` in `src/formats/binary.cpp`. Text presented to clients is converted to UTF-8. Do not interpret a legacy byte offset as a Unicode character index. + +| Data | Files | Documentation | Implementation | +|---|---|---|---| +| Palette | `M3PC.COL` | [COL](COL.md) | `src/formats/palette.cpp` | +| Indexed images | `KB/*.VGA`, `W/*.VGA` | [VGA](VGA.md) | `src/formats/vga.cpp` | +| Bitmap fonts | `F/*.FNT` | [FNT](FNT.md) | `src/formats/font.cpp` | +| Text database | `TEXTD.BLK`, `TEXTE.BLK` | [TEXTD](TEXTD.md) | `src/formats/textd.cpp` | +| Master database | `M3D.MAN`, `M3E.MAN` | [M3D](M3D.md) | `src/formats/m3d.cpp` | +| Desktop layout | `M3.MEN`, `*.MEN` | [M3MEN](M3MEN.md) | `src/ui/desk_state.cpp` | +| Formation coordinates | `M3.DAT` | [M3DAT](M3DAT.md) | `src/game/state.cpp` | +| Settings | `*.EIN`, saved settings block | [EIN](EIN.md) | `src/game/state.hpp` | +| Save container and state | `*.FBM` | [FBM](FBM.md), [STATE](STATE.md) | `src/formats/fbm.cpp`, `savestate.cpp` | +| Legacy configuration | `SOUND.CFG`, `PFAD.MAN` | [CONFIG](CONFIG.md) | Not used for host device configuration | +| Audio containers | `S/2000` through `S/2003` | [SOUND](SOUND.md) | `src/audio/container.cpp`, `original.cpp` | +| Executable data | German LE and English X-32 images | [LE](LE.md), [executable layout](EXECUTABLE_LAYOUT.md) | `src/formats/le.cpp`, `src/launch/fltd.cpp` | +| IFF crest template | `WAPPEN.LBM` | [WAPPEN](WAPPEN.md) | Not loaded by OpenBMH | + +German and English editions can share a physical format while differing in text, league contents, executable layout and currency. Select the edition through the supplied installation; do not rename files or patch a save header to simulate another version. Original English V2.20 save import is a separate compatibility limitation from English installation support. + +The loaders and accessors are authoritative for supported bounds and validation. Unknown fields are preserved where required by save compatibility; an unexplained value is not an extension point. File offsets and record strides here describe formats, not stable application API names. diff --git a/docs/formats/SOUND.md b/docs/formats/SOUND.md new file mode 100644 index 0000000..16a4777 --- /dev/null +++ b/docs/formats/SOUND.md @@ -0,0 +1,36 @@ +# Audio containers: `S/2000` through `S/2003` + +`src/audio/container.cpp` validates the sound containers and decodes bounded PCM samples. `src/audio/original.cpp` implements the supported music sequencer, OPL instrument path, sample channel and effect dispatch. Audio resources and instrument values come from the user's installation; none are distributed here. + +## Container structure + +| Offset | Size | Meaning | +|---|---|---| +| 0 | 4 | `FORM` signature | +| 4 | u32, little endian | Declared length | +| 8 | 8 | `ALPTRAUM` type | +| 16 | Variable | Consecutive chunks | + +Each chunk has a four-byte ID, a little-endian u32 payload length and its payload. Unlike standard padded IFF chunks, these chunks are adjacent without an alignment byte. The walker rejects overflows and requires the final chunk to end at the file boundary. + +Music banks contain `HEDR`, `SONG`, `TRCK`, `PART`, `INST` and `SAMP` chunks. The effects bank uses `HEDR`, `SEFX`, `INST` and `SAMP`. The usual FORM length excludes the first eight bytes. The supported effects variant instead declares the whole file size; this exception is accepted only with its validated fixed chunk layout. + +## PCM samples + +A `SAMP` payload starts with two u16 words: a header field and the sample count. Each sample has a 16-byte descriptor followed by a shared unsigned eight-bit mono data area. Within a descriptor: + +| Offset | Type | Meaning | +|---|---|---| +| 0 | u16 | Start relative to the sample-data area | +| 2 | u16 | Length in bytes | +| 8 | u16 | Sample rate | + +`decode_sample` checks the descriptor table and sample bounds, rejects empty samples and validates the rate. Conversion to signed sixteen-bit PCM is `(value - 128) * 256`. + +## Sequencing and effects + +`SONG`, `TRCK` and `PART` provide sequence order and timed note events; `INST` supplies instrument records. `OriginalSynth` schedules the supported register and sample operations using a deterministic audio tick. Nuked OPL3 renders the OPL-compatible register stream. This audio clock is separate from career random generators and match time. + +The effects table has a four-byte prefix and sixteen-byte records. Instrument-backed effects and sample-backed effects use separate paths. `decode_original_cue` alone supports the direct sample-backed subset; this does not mean the full synthesiser lacks the instrument path. Music and effects settings control playback, while actual device availability belongs to the frontend. English audio compatibility remains subject to the release's experimental edition limits. + +Sample-domain output checks establish decoder behaviour, not the timing or audible quality of a physical audio device. Platform listening and device checks are separate validation work. diff --git a/docs/formats/STATE.md b/docs/formats/STATE.md new file mode 100644 index 0000000..ba7c396 --- /dev/null +++ b/docs/formats/STATE.md @@ -0,0 +1,27 @@ +# Interpreting saved game state + +The [FBM container](FBM.md) contains fixed-order state blocks rather than a self-describing object graph. `src/formats/savestate.cpp` defines the physical layout; `src/game/state.hpp` and `state.cpp` provide semantic accessors. Keep those implementations as the single source of truth when adding a field. + +## Manager records + +Five compatibility slots use 2,828-byte records. Not every slot represents a playable manager. Important offsets within each record include: + +| Record offset | Type | Meaning | +|---|---|---| +| `0x0a8` | Fixed character area | Manager name | +| `0x290` | i16 | Runtime team ID; a sentinel represents no club | +| `0x314` | i32 | Cash balance in the engine's currency units | +| `0x748` | i32 array | First income accounting table | +| `0x85c` | i32 array | Second income accounting table | + +Financial projections can include computed expenses; raw accounting tables do not by themselves reproduce the complete balance screen. A displayed currency conversion is not a change to saved arithmetic. + +Other blocks retain desktop layouts, settings, formation coordinates, tactics, transfers, loan ledgers, calendar state, results, player words and name offsets. Loan duration is kept separately from a player's contract-byte sentinel; a sentinel must not be read as a real multi-century contract. + +## Identity and schedule + +Master club indices, club-name pool offsets, runtime team IDs, player IDs and squad rows are distinct identifiers. Initialisation can shuffle clubs between runtime positions. Promotion and relegation can change those positions again. Use a session's current projections to resolve identity rather than holding a runtime row across a season boundary. + +The base league structure contains five eighteen-team and four twelve-team ranges. A result byte packs home goals in the high nibble and away goals in the low nibble; `0xcc` denotes an unplayed result. The schedule combines round templates with current calendar and competition state. Tables additionally incorporate deductions and selected competition rules; clients should request a table projection instead of deriving one from raw results alone. + +Do not serialise frontend capabilities, pointers, callback owners or request IDs into this compatibility state. Session staging and rollback must include the associated runtime state and both [random streams](../RNG.md), not just selected byte arrays. diff --git a/docs/formats/TEXTD.md b/docs/formats/TEXTD.md new file mode 100644 index 0000000..88ec55d --- /dev/null +++ b/docs/formats/TEXTD.md @@ -0,0 +1,16 @@ +# Text database: `TEXTD.BLK` / `TEXTE.BLK` + +`src/formats/textd.cpp` reads a seven-byte header followed by consecutive NUL-terminated legacy strings. + +| Offset | Type | Meaning | +|---|---|---| +| 0 | u8 | Edition-specific identifier | +| 1 | u16 | Declared buffer size | +| 3 | u32 | Header field with no application-level interpretation | +| 7 | bytes | String buffer | + +The loader indexes the first 1,382 strings and rejects a shorter database. Declared buffer size can differ from the actual payload; the loader takes the remaining file bytes rather than trusting it as a stream length. Each stored offset is relative to the start of the string buffer, not to the file or a UTF-8 result. + +Strings are converted through the legacy character decoder when displayed. Currency labels and other edition content come from the installation. The text database is not copied into a savegame; the name pools stored in [FBM](FBM.md) are separate. + +This document intentionally describes structure only. A distributable replacement must provide independently licensed text; copying or translating the supplied game's text database does not create a new license for it. diff --git a/docs/formats/VGA.md b/docs/formats/VGA.md new file mode 100644 index 0000000..3ea8d69 --- /dev/null +++ b/docs/formats/VGA.md @@ -0,0 +1,16 @@ +# Indexed bitmap: `.VGA` + +`src/formats/vga.cpp` decodes eight-bit palette indices from a continuous run-length stream. Coordinates use a top-left origin. + +| Offset | Type | Meaning | +|---|---|---| +| 0 | u16 | Width | +| 2 | u16 | Height | +| 4 | u32 | Encoded length, including one trailing byte | +| 8 | bytes | Encoded pixel stream | + +For a control byte `c >= 0x80`, repeat the following byte `c - 0x7f` times. Otherwise copy the next `c + 1` literal bytes. Decoding continues across row boundaries until `width * height` indices have been produced. The loader rejects truncated data and requires exactly one byte to remain within the declared stream afterwards. A run exceeding the pixel count is clipped by the decoder. + +The default colours come from [M3PC.COL](COL.md). Certain full-screen resources append a 768-byte palette after the encoded stream; callers loading those resources must select that palette separately. `decode_vga` itself returns indices and does not interpret appended palette data. + +Crest sheets use 38 by 38 pixel cells, eight per sheet. For a nine-bit crest ID, the file number is `id >> 3` and the horizontal cell is `id & 7`. This describes the lookup scheme rather than any particular copyrighted crest or sheet content. diff --git a/docs/formats/WAPPEN.md b/docs/formats/WAPPEN.md new file mode 100644 index 0000000..65f8ea5 --- /dev/null +++ b/docs/formats/WAPPEN.md @@ -0,0 +1,7 @@ +# IFF crest templates: `WAPPEN.LBM` + +OpenBMH does not load this file. Its crest renderer uses indexed [VGA](VGA.md) sheets. No authorship or redistribution permission for templates found alongside a game installation is implied by their filename. + +An IFF `FORM` of type `PBM ` can contain a `BMHD` bitmap header, an eight-bit RGB `CMAP`, optional application chunks and a `BODY` with chunky pixel indices. IFF lengths and header integers are big endian; chunks are padded to even boundaries. + +For ByteRun1-compressed data, controls 0–127 copy the next `n + 1` bytes, controls 129–255 repeat the next byte `257 - n` times, and 128 is a no-op. This encoding differs from the game's VGA run-length stream. Adding a loader would require its own input validation and independently licensed test fixture. diff --git a/docs/licenses/LGPL-2.1.txt b/docs/licenses/LGPL-2.1.txt new file mode 100644 index 0000000..8000a6f --- /dev/null +++ b/docs/licenses/LGPL-2.1.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/docs/licenses/LZMA-SDK.txt b/docs/licenses/LZMA-SDK.txt new file mode 100644 index 0000000..242a7e8 --- /dev/null +++ b/docs/licenses/LZMA-SDK.txt @@ -0,0 +1,7 @@ +LZMA SDK +-------- + +This package also contains some files from LZMA SDK +You can download LZMA SDK from: + http://www.7-zip.org/sdk.html +LZMA SDK is written and placed in the public domain by Igor Pavlov. diff --git a/docs/licenses/Nuked-OPL3-notices.txt b/docs/licenses/Nuked-OPL3-notices.txt new file mode 100644 index 0000000..e6288c3 --- /dev/null +++ b/docs/licenses/Nuked-OPL3-notices.txt @@ -0,0 +1,31 @@ +/* Nuked OPL3 + * Copyright (C) 2013-2020 Nuke.YKT + * + * This file is part of Nuked OPL3. + * + * Nuked OPL3 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 + * of the License, or (at your option) any later version. + * + * Nuked OPL3 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Nuked OPL3. If not, see . + + * Nuked OPL3 emulator. + * Thanks: + * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): + * Feedback and Rhythm part calculation information. + * forums.submarine.org.uk(carbon14, opl3): + * Tremolo and phase generator calculation information. + * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): + * OPL2 ROMs. + * siliconpr0n.org(John McMaster, digshadow): + * YMF262 and VRC VII decaps and die shots. + * + * version: 1.8 + */ diff --git a/docs/licenses/README.md b/docs/licenses/README.md new file mode 100644 index 0000000..258cfdb --- /dev/null +++ b/docs/licenses/README.md @@ -0,0 +1,14 @@ +# Included license texts + +These files preserve upstream license and attribution wording. They are not a grant covering original game content. OpenBMH's GPL-3.0-only notice and the full GPLv3 text are in the root [README](../../README.md) and [LICENSE](../../LICENSE). + +- [SDL2](SDL2.txt): SDL 2.32.10 `LICENSE.txt`. +- SDL2's bundled HIDAPI: [license options](SDL2-HIDAPI-options.txt), [BSD-3-Clause](SDL2-HIDAPI-BSD.txt), [original license](SDL2-HIDAPI-original.txt). +- [SDL2 yuv2rgb](SDL2-yuv2rgb.txt): BSD-3-Clause notice for that included source component. +- [miniz](miniz.txt): the MIT license shipped with the 3.0.2 amalgamation. [Additional verbatim source notices](miniz-source-notices.txt), including the additional copyright attribution and public-domain dedication, are also retained. +- [LZMA SDK](LZMA-SDK.txt): the public-domain declaration from the 7-Zip 24.09 documentation. Only individually marked public-domain decoder files are used. +- [nativefiledialog-extended](nativefiledialog-extended.txt): version 1.2.1 zlib license. +- [Nuked OPL3 copyright and license notice](Nuked-OPL3-notices.txt): unchanged leading notice from its vendored implementation. +- [LGPL version 2.1](LGPL-2.1.txt): full license supplied with Nuked OPL3. Its source notices permit version 2.1 or any later version. + +[THIRD_PARTY_NOTICES.md](../../THIRD_PARTY_NOTICES.md) identifies the upstream versions and distribution requirements. Include this directory, that notice file and the root LICENSE with release packages. Preserve upstream attribution within these verbatim texts. diff --git a/docs/licenses/SDL2-HIDAPI-BSD.txt b/docs/licenses/SDL2-HIDAPI-BSD.txt new file mode 100644 index 0000000..538cdf9 --- /dev/null +++ b/docs/licenses/SDL2-HIDAPI-BSD.txt @@ -0,0 +1,26 @@ +Copyright (c) 2010, Alan Ott, Signal 11 Software +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Signal 11 Software nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/licenses/SDL2-HIDAPI-options.txt b/docs/licenses/SDL2-HIDAPI-options.txt new file mode 100644 index 0000000..e1676d4 --- /dev/null +++ b/docs/licenses/SDL2-HIDAPI-options.txt @@ -0,0 +1,13 @@ +HIDAPI can be used under one of three licenses. + +1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt +2. A BSD-Style License, in LICENSE-bsd.txt. +3. The more liberal original HIDAPI license. LICENSE-orig.txt + +The license chosen is at the discretion of the user of HIDAPI. For example: +1. An author of GPL software would likely use HIDAPI under the terms of the +GPL. + +2. An author of commercial closed-source software would likely use HIDAPI +under the terms of the BSD-style license or the original HIDAPI license. + diff --git a/docs/licenses/SDL2-HIDAPI-original.txt b/docs/licenses/SDL2-HIDAPI-original.txt new file mode 100644 index 0000000..e3f3380 --- /dev/null +++ b/docs/licenses/SDL2-HIDAPI-original.txt @@ -0,0 +1,9 @@ + HIDAPI - Multi-Platform library for + communication with HID devices. + + Copyright 2009, Alan Ott, Signal 11 Software. + All Rights Reserved. + + This software may be used by anyone for any reason so + long as the copyright notice in the source files + remains intact. diff --git a/docs/licenses/SDL2-yuv2rgb.txt b/docs/licenses/SDL2-yuv2rgb.txt new file mode 100644 index 0000000..a76efd7 --- /dev/null +++ b/docs/licenses/SDL2-yuv2rgb.txt @@ -0,0 +1,27 @@ +Copyright (c) 2016, Adrien Descamps +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of yuv2rgb nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/licenses/SDL2.txt b/docs/licenses/SDL2.txt new file mode 100644 index 0000000..23abb73 --- /dev/null +++ b/docs/licenses/SDL2.txt @@ -0,0 +1,18 @@ +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/docs/licenses/miniz-source-notices.txt b/docs/licenses/miniz-source-notices.txt new file mode 100644 index 0000000..4faeb9d --- /dev/null +++ b/docs/licenses/miniz-source-notices.txt @@ -0,0 +1,83 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ + +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ diff --git a/docs/licenses/miniz.txt b/docs/licenses/miniz.txt new file mode 100644 index 0000000..b6ff45a --- /dev/null +++ b/docs/licenses/miniz.txt @@ -0,0 +1,22 @@ +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/docs/licenses/nativefiledialog-extended.txt b/docs/licenses/nativefiledialog-extended.txt new file mode 100644 index 0000000..3ab103c --- /dev/null +++ b/docs/licenses/nativefiledialog-extended.txt @@ -0,0 +1,16 @@ +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..ca3b888 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,72 @@ +# JSON Lines request protocol + +`openbmh_cli` without `--console` offers a small JSON request adapter for a single `app::CareerSession`. It reads one JSON object per line and writes one response per line. `--text` is an interactive shorthand for this adapter. The broader window-oriented console and its `--json` output are a separate interface; use the [console reference](CLI_CONCEPT/README.md) for interactive questions, live matches and multiple manager clients. + +```sh +openbmh_cli --data "path/to/game" --seed 1 --json +openbmh_cli --data "path/to/game" --seed 1 --json --log session.jsonl +openbmh_cli --replay session.jsonl --json +``` + +A request has `cmd` and the fields accepted for that command. Mutations carry an integer `manager` and the current `revision`. Responses contain `ok` and `revision`; errors add a stable `error` code and can include diagnostic `detail`. A rejected stale or foreign action must not mutate the projected state. Seed values are unsigned 32-bit decimal or hexadecimal values. + +## Commands + +| Command | Fields | Behavior | +|---|---|---| +| `help` | — | Machine-readable command and parameter list. | +| `new` | `options`, `managers` | Creates a career. This adapter accepts exactly one manager. `options` supports `duration` (0–5), `difficulty` (0–9), `mode` (0–3), `league`, `world`, and `managers:1`. The single manager has `name`, `master_club`, optional `start_league`, `strength` (0–2), and `portrait` (0–11). | +| `load` | `path` | Loads through `CareerSession`; a failed load leaves the current career active. | +| `save` | `manager`, `revision`, `path`, optional `overwrite` | Saves through the Session after checking the current manager and revision. | +| `status`, `desk` | — | Read the desktop projection and a compact status object. | +| `kickoff` | `manager`, `revision` | Calls the existing turn driver through `dispatch_kickoff`, advancing to the next desk. Returns state and available desk/audio event metadata. | +| `results` | — | Reads the owned results of the last completed event; `kickoff` also returns this object. A manager handoff or empty event has no new results. | +| `tactics`, `training` | — | Read current preparation values. Reading training does not initialize or recalculate it. | +| `tactics.set` | envelope, `index` (0–7), `value` | Sets a supported tactic; index 0 also disables the attitude assistant. | +| `training.initialize` | envelope | Performs the normal first-open initialization only when needed. | +| `training.type`, `training.area` | envelope, `index`, `value` (1–3) | Changes one of 4 types or 9 areas, validating supported plan limits and automation flags. | +| `training.intensity` | envelope, `row`, `value` (1–3) | Changes the player currently occupying the selected squad row. | +| `training.focus` | envelope, `row` | Cycles that player's training focus. | +| `training.auto` | envelope, `index` (0–4), `value` (0–1) | Toggles a training automation bit, validating the expected value and visible context. | +| `table` | `manager`, `league` (0–8) | Reads the selected full-season overall table in Engine rank order, with point deductions. Requires the active manager. | +| `mail` | `manager` (0–3) | Reads the selected existing manager's mailbox, sorted by date and physical slot. Does not mark, keep or delete messages. | +| `camp.focus` | envelope, `focus` (4 integers) | Dispatches a training-camp focus change. | +| `camp.book` | envelope, `resort` (0–7) | Books the selected camp. | +| `bank.deposit`, `bank.withdraw` | envelope, positive `amount` | Moves funds through the bank dispatch API. | +| `bank.shares.buy`, `bank.shares.sell`, `bank.tip` | envelope, `asset` (0–11), optional `count` | Uses the bank dispatch API. | +| `bank.fund.buy`, `bank.fund.sell` | envelope, `asset` (0–5), `count` (1–10) | Uses the bank dispatch API. | +| `stadium.open` | envelope | Opens the existing stadium projection/action. | +| `stadium.offer` | envelope, `object` (0–13) | Requests the existing periphery quote. | +| `stadium.build`, `stadium.decline` | envelope, `object` (0–13), `price` | Uses the existing stadium dispatch API. | +| `toto.submit` | envelope, `stake`, `tips` (11 values, each 0–2) | Submits through the existing Toto dispatch API. | +| `quit` | — | Ends the input loop. | + +The `envelope` above means integer `manager` and `revision`. This adapter uses one manager, +slot 0; a different manager or stale revision is rejected. A failed `new` does not +create a Session. A successful `load` starts a new CLI revision sequence. + +The text mode is intentionally narrower: `help`, `new +[strength]`, `load `, `save `, `status`, `desk`, `kickoff`, +`camp.book `, `results`, `tactics`, `tactics.set `, `training`, +`training.initialize`, `training.type `, `training.area `, +`training.intensity `, `training.focus `, +`training.auto `, `table `, `mail `, +bank deposit/withdraw/share/fund/tip actions, and `quit`. `help` +prints parameter hints. Use JSON mode for all option fields, camp focus, stadium and Toto +requests, and for machine clients. + +## Errors and scope + +Malformed JSON, unexpected fields and invalid field types return `invalid_request`. Unknown operations return `unsupported_command`; recognised operations without a session adapter return `career_session_api_unavailable`. `help` describes the command set implemented by this adapter. An operation can also be rejected by its normal phase, mode, manager or rule checks. These outcomes must not be converted into successful client-side approximations. + +This adapter does not expose the console's full squad, calendar, finance, live-match, question/answer or multi-seat interfaces. Its `new` operation requires one manager. A loaded career is subject to the session's actual continuation and revision checks; a successful read alone is not a claim that every later action is available in this adapter. + +`table` returns owned club names, a club identity key, runtime team ID, ranks, games, wins/draws/losses, goals and points. Identity keys, runtime positions and master database indices are distinct. `mail` returns a snapshot of mailbox slots and recipient/keep masks. Keeping is not the same as marking read. Slot references can change when messages are compacted and are not persistent message IDs. + +## Log and replay + +`--log FILE` writes a header with protocol version, data location and seed, then canonical request/response records. `--replay FILE` repeats those requests and reports a mismatch. Replay can overwrite a path recorded by a save operation, so use an isolated writable save directory. Keep the same compatible binary and data when comparing a run. + +The log contains supplied values and game responses, potentially including proprietary text or personal paths. It is not a distributable substitute for game data, nor a complete serialisation of every hidden session mechanism. Do not attach a full game log or save to a public issue; prepare minimal independently written reproduction steps. + +Text errors use `ERROR : `; successful text replies use `OK`. JSON mode emits one JSON response per request line. Transport framing and field names are part of this adapter's API; executable table addresses are not. diff --git a/docs/release/0.1/LIESMICH.txt b/docs/release/0.1/LIESMICH.txt new file mode 100644 index 0000000..5919f58 --- /dev/null +++ b/docs/release/0.1/LIESMICH.txt @@ -0,0 +1,44 @@ +OpenBMH v0.1.0 +=============== + +OpenBMH ist eine eigenstaendige Neuumsetzung der Engine von Bundesliga Manager +Hattrick und der englischen Fassung Football Limited. Die englische Unterstuetzung +ist experimentell. Originale Spielinhalte sind nicht enthalten; du benoetigst eine +eigene unterstuetzte Installation. Originale V2.20-Spielstaende der englischen +Fassung sind nicht mit dem unterstuetzten Speicherlayout austauschbar. + +Start +----- +Paket in einen eigenen Ordner oder neben die Installation entpacken. +openbmh_play starten (unter Windows openbmh_play.exe). Der Dateidialog nimmt einen +Spielordner, die Programmdatei oder ZIP/7z mit einer einzelnen Installation an. + +Aus einem Terminal: + openbmh_play --data "path/to/game" --save-directory "path/to/saves" + openbmh_cli --console --data "path/to/game" --saves "path/to/saves" + +Unter Windows den Programmnamen um .exe ergaenzen. Ein beschreibbarer separater +Spielstandordner wird empfohlen. Vorhandene Spielstaende vorher sichern. +Tonoptionen: --mute, --no-music, --volume 0.5. --version zeigt die Programmversion. +In der Konsole zeigt ListOptions die aktuellen Befehle; eine eigene Zeile go. +fuehrt den eingegebenen Block aus. Help beschreibt die Parameter. + +Dokumentation und Rueckmeldungen +------------------------------- +README.md enthaelt die Bauanleitungen fuer Windows, Linux und macOS. +Die Releasehinweise beschreiben den Umfang und die bekannten Grenzen. +Linux benoetigt je nach Paket Systembibliotheken, insbesondere GTK3 fuer den +Standard-Dateidialog. Plattform-Bauhinweise sind kein Nachweis eines nativen Tests. + +Fehler mit Programmversion, Spielfassung und kurzen eigenen Schritten melden. +Keine Originaldateien, Spielbilder, Aufnahmen, Textlisten oder Spielstaende in +oeffentliche Issues hochladen. + +Lizenz +------ +Eigener OpenBMH-Code und Dokumentation: GNU GPL Version 3 ausschliesslich +(GPL-3.0-only). LICENSE enthaelt den vollstaendigen Text. Drittanbieter behalten +ihre Lizenzen; siehe THIRD_PARTY_NOTICES.md und docs/licenses/. +Diese Lizenzen gelten nicht fuer die separat benoetigten Originalinhalte. +OpenBMH ist ein unabhaengiges Projekt ohne Verbindung oder Billigung durch die +urspruenglichen Rechteinhaber, DFL oder Bundesliga. diff --git a/docs/release/0.1/RELEASE_NOTES.md b/docs/release/0.1/RELEASE_NOTES.md new file mode 100644 index 0000000..0d08c16 --- /dev/null +++ b/docs/release/0.1/RELEASE_NOTES.md @@ -0,0 +1,32 @@ +# OpenBMH v0.1.0 + +OpenBMH reconstructs the Bundesliga Manager Hattrick engine in C++20. The graphical client uses SDL2; the console provides command batches and local manager-client transports over the same career session. This release needs a supported game installation supplied by the player. No original executable, artwork, music, text database, manual or saved game is included. + +## Scope + +The engine includes career management, leagues and cups, transfers and contracts, finances, training and camps, stadium management, live match interventions, audio playback and normal saves. Supported actions remain subject to mode, manager and phase restrictions; an unimplemented path reports an explicit error rather than an invented result. The project aims for recognisable behaviour and plausible results, not a promise that every original version produces identical events. + +German game editions are the primary compatibility target. **Football Limited support is experimental.** English installation loading and edition-specific text/layout data are supported paths, while original V2.20 save import, English audio and remaining competition/interface differences have limitations. Check current issues before relying on a particular English workflow. + +## Compatibility decisions + +OpenBMH uses shared rule values across supported German editions, with installation-specific content read from the selected data. It includes safety handling around invalid input, calendar boundaries, capacity checks and suspended operations. See [compatibility decisions](../../COMPATIBILITY.md) and [architecture](../../architecture.md). This is an independent reconstruction, not an official update to the original game. + +## Running + +Extract the package to a separate directory or alongside your installation. `openbmh_play` can select a game directory, executable or a ZIP/7z containing one supported installation. Use an explicit writable save directory when the original directory is read-only, and keep backups. + +```sh +openbmh_play --data "path/to/game" --save-directory "path/to/saves" +openbmh_cli --console --data "path/to/game" --saves "path/to/saves" +``` + +Packages and their native platform results are listed with the release assets. The [build instructions](../../BUILDING.md) cover Windows, Linux and macOS source builds; an instruction is not a claim of native acceptance. Linux's default file dialog backend requires GTK3 system libraries. A macOS terminal executable is distinct from a signed application bundle. + +## License + +The matching application source tag is [v0.1.0](https://github.com/rezmer/openbmh/tree/v0.1.0). Source/build and relinking materials for linked components must also accompany or be offered with binary releases under their licenses. + +OpenBMH-owned code and documentation use GPL-3.0-only. Third-party components retain their licenses; the full texts accompany the package. Read [LICENSE](../../../LICENSE) and [THIRD_PARTY_NOTICES](../../../THIRD_PARTY_NOTICES.md). These licenses do not grant rights to original game content. + +For reports, include the OpenBMH version, data edition, independently written steps and the observed result. Do not upload original files, game screenshots, recordings, text collections or saved games to public issues. diff --git a/src/app/action_transaction.hpp b/src/app/action_transaction.hpp new file mode 100644 index 0000000..e1a8ba9 --- /dev/null +++ b/src/app/action_transaction.hpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "app/career_session.hpp" + +namespace bmh::app::detail { + +template +bool apply_window(CareerSession& session, uint64_t& revision, Checkpoint before, + Restore restore_checkpoint, const std::function& action) { + const auto game = session.game(); + const auto rand = session.rand(); + const auto old_revision = revision; + const auto restore = [&] { + session.game() = game; + session.rand() = rand; + // Some owners reconstruct their saved RNG identity during restore. + restore_checkpoint(std::move(before)); + revision = old_revision; + }; + try { + if (action()) return true; + } catch (...) { + restore(); + throw; + } + restore(); + return false; +} + +inline bool apply_native(CareerSession& session, uint64_t& revision, const std::function& action) { + return apply_window(session, revision, session.state(), + [&](GameState before) { session.state() = std::move(before); }, action); +} + +} // namespace bmh::app::detail diff --git a/src/app/audio.hpp b/src/app/audio.hpp new file mode 100644 index 0000000..134692e --- /dev/null +++ b/src/app/audio.hpp @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once + +#include "audio/playback.hpp" +#include "formats/le.hpp" +#include "game/state.hpp" +#include "ui/setup.hpp" + +namespace bmh::app { + +inline openbmh::audio::OriginalAssets original_audio_assets( + const std::filesystem::path& directory, const LeImage& exe) { + openbmh::audio::OriginalAssets assets; + for (unsigned i = 0; i < 4; ++i) + assets.containers[i] = read_file(ui::asset_path(directory / "S", std::to_string(2000 + i))); + for (unsigned i = 0; i < assets.tables.frequencies.size(); ++i) + assets.tables.frequencies[i] = exe.u16(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField2 + 2 * i); + for (unsigned i = 0; i < assets.tables.operators.size(); ++i) + assets.tables.operators[i] = exe.u8(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField + 16 * i); + return assets; +} + +inline openbmh::audio::OriginalAudioOptions original_audio_options(const GameState& state, bool music) { + const auto on = [&](std::uint32_t address) { + return !state.memory.has(address) || (state.memory.u8(address) & 0x7f) == 0; + }; + // A5 governs match presentation and is checked by the match observer. It + // must not mute menu clicks. A6/A7 are independent saved music/click switches. + return {music && on(::bmh::layout::Audio_OriginalAudioOptions_ExecutableField), true, on(::bmh::layout::Audio_OriginalAudioOptions_ExecutableField2)}; +} +inline bool match_sound_enabled(const GameState& state) { + return !state.memory.has(::bmh::layout::Audio_MatchSoundEnabled_RuntimeField) || (state.memory.u8(::bmh::layout::Audio_MatchSoundEnabled_RuntimeField) & 0x7f) == 0; +} +inline void original_audio_command(openbmh::audio::Playback& playback, std::uint8_t id) { + if (!playback.original_ready() || !playback.available()) return; + std::string error; + playback.play_original_id(id, error); +} +inline void original_match_audio_command(openbmh::audio::Playback& playback, + const GameState& state, std::uint8_t id) { + if (match_sound_enabled(state)) original_audio_command(playback, id); + else if (id == 3) original_audio_command(playback, 8); // Match entry still stops desk music. +} + +// One callback per actual SDL mouse event, including nested modal loops. No +// rendering/hover polling, no scene inference, and no application/GameState access +// from a possible SDL event thread. Source OriginalMouseSound maps left2/right8 to10/11. +class OriginalMouseSound { +public: + explicit OriginalMouseSound(openbmh::audio::Playback& p) : playback_(p) { + SDL_AddEventWatch(watch, this); + } + ~OriginalMouseSound() { detach(); } + void detach() noexcept { + if (!attached_) return; + SDL_DelEventWatch(watch, this); + attached_ = false; + } + OriginalMouseSound(const OriginalMouseSound&) = delete; + OriginalMouseSound& operator=(const OriginalMouseSound&) = delete; +private: + static int watch(void* data, SDL_Event* event) { + if (event->type == SDL_MOUSEBUTTONDOWN) { + auto& self = *static_cast(data); + if (event->button.button == SDL_BUTTON_LEFT) original_audio_command(self.playback_, 10); + if (event->button.button == SDL_BUTTON_RIGHT) original_audio_command(self.playback_, 11); + } + return 1; + } + openbmh::audio::Playback& playback_; + bool attached_ = true; +}; + +} // namespace bmh::app diff --git a/src/app/career_session.cpp b/src/app/career_session.cpp new file mode 100644 index 0000000..0edd23b --- /dev/null +++ b/src/app/career_session.cpp @@ -0,0 +1,8375 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "app/career_session.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" + +namespace bmh::app { +namespace { +std::atomic next_session_id{1}; + +constexpr uint32_t kSavedCalendar = ::bmh::layout::CompetitionCalendar; +constexpr uint32_t kSavedCompetitionBits = ::bmh::layout::SavedCompetition; +constexpr uint8_t kBlockSeat = 1; +constexpr uint8_t kBlockRoof = 2; +constexpr uint8_t kBlockFeatures = kBlockSeat | kBlockRoof; + +bool is_block_expansion_action(ui::StadiumRequestKind kind) { + return kind == ui::StadiumRequestKind::expansion_select || + kind == ui::StadiumRequestKind::expansion_set_total || + kind == ui::StadiumRequestKind::expansion_toggle_feature || + kind == ui::StadiumRequestKind::expansion_cancel || + kind == ui::StadiumRequestKind::expansion_confirm || + kind == ui::StadiumRequestKind::expansion_answer_tip; +} + +int national_opportunities_rank(const 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>=138?9:0; +} + +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; +} +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; +} + +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; +} + +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; +} + +uint32_t saved_group_u32(const Bytes& bytes, size_t offset) { + return uint32_t(bytes.at(offset)) | (uint32_t(bytes.at(offset + 1)) << 8) | + (uint32_t(bytes.at(offset + 2)) << 16) | (uint32_t(bytes.at(offset + 3)) << 24); +} + +void initialize_saved_match_group(MatchGroup& group, const GameState& state, size_t index, + int league) { + group.desc = group_descriptor(state, index); + if (group.desc.size() != 0xd0 || group.desc[0] != 0 || + saved_group_u32(group.desc, 0xcc) != uint32_t(league)) + throw std::runtime_error("saved turn cursor: league descriptor does not match the active calendar"); + const int round = state.league_rounds.at(size_t(league)); + const auto fixtures = league_fixtures(league, round + 1); + if (group.desc[2] != fixtures.size()) + throw std::runtime_error("saved turn cursor: league fixture count is incomplete"); + for (const Fixture& fixture : fixtures) { + group.fixtures.push_back(fixture.home); + group.fixtures.push_back(fixture.away); + } + const size_t result_at = size_t(league) * 0x17c + size_t(round) * 10; + if (result_at + fixtures.size() > state.results.size()) + throw std::runtime_error("saved turn cursor: league result block is incomplete"); + group.results.assign(state.results.begin() + long(result_at), + state.results.begin() + long(result_at + fixtures.size())); + // Assign2 and the match loop read exactly one mask bit per descriptor + // match. Before kickoff, a saved desk can retain high bits from the previous + // larger group; those padding bits are not fixture identities and are ignored + // by the original. Keep the saved descriptor intact and validate actual + // fixture count, result range, and active league above. + // These per-match arrays are transient runtime data. kick_off rebuilds them from + // the authoritative saved lineups; no setup/event replay belongs in the loader. + group.records.assign(fixtures.size() * 18, 0); + group.end_minute.assign(fixtures.size(), 0); + group.spectators.assign(fixtures.size(), 0); +} + +void initialize_saved_cup_group(MatchGroup& group, const GameState& state, size_t index, + int cup_id, int entry_index) { + const StaticMemory& mem = state.memory; + group.desc = group_descriptor(state, index); + const uint32_t guest_entry = saved_group_u32(group.desc, 0xcc); + if (group.desc.size() != 0xd0 || group.desc[0] != cup_id + 1 || + guest_entry < kGuestDataBase || (guest_entry - kGuestDataBase) != cup_entry_address(entry_index)) + throw std::runtime_error("cup descriptor mismatch group=" + std::to_string(index) + + " type=" + std::to_string(group.desc[0]) + + " guest=" + std::to_string(guest_entry) + + " stage=" + std::to_string(entry_index)); + const uint32_t entry = cup_entry_address(entry_index); + // In memory the descriptor stores a guest pointer; MatchGroup carries the data-object + // address, as setup_cup_groups does before store_group_descriptors adds the guest base. + for (int i = 0; i < 4; ++i) group.desc.at(0xcc + size_t(i)) = uint8_t(entry >> (i * 8)); + const uint8_t flags = mem.u8(entry + 0x14); + const bool knockout = (flags & 4) != 0; + const int teams = mem.u8(entry + 0x1a); + if (int16_t(mem.u16(entry + 0x18)) != cup_id || teams < 2 || (teams & 1) || + group.desc[2] == 0 || group.desc[2] > (knockout ? 32 : 18)) + throw std::runtime_error("saved turn cursor: cup descriptor has invalid stage or match count"); + const int round = cup_round(mem, entry_index); + int first = 0; + int expected_matches = 0; + if (knockout) { + if (round < 0 || round >= 8 || (1 << (round + 1)) > teams) + throw std::runtime_error("saved turn cursor: cup knockout round is outside the stage"); + expected_matches = teams / (1 << (round + 1)); + first = uint8_t(cup_round_offset(mem, entry_index, round)); + } else { + if (teams / 2 > 18) throw std::runtime_error("saved turn cursor: cup group is too large"); + expected_matches = teams / 2; + // Group-stage fixtures are stored in descriptor +0x88; KO descriptors do not + // contain fixture IDs there. Their IDs come from the stage's round-indexed list. + first = uint8_t(expected_matches * mem.u8(entry + 0x1d) * 2); + } + if (expected_matches != group.desc[2]) + throw std::runtime_error("saved turn cursor: cup round match count disagrees with its descriptor"); + const size_t fixture_count = size_t(group.desc[2]) * 2; + // As in Assign2, only bits [0, group.desc[2]) are read. The descriptor + // can carry stale high padding bits from the preceding event; preserve them + // in the copy rather than treating them as corrupt fixture references. + const uint32_t list = mem.pointer(entry); + if (list == 0 || (knockout + ? !mem.has(list + uint32_t(first + expected_matches * 2) * 2 - 1) + : !mem.has(list + uint32_t(teams) * 2 - 1))) + throw std::runtime_error("saved turn cursor: cup team list is missing"); + auto valid_team = [&](int team) { + return team >= 0 && size_t(team) < state.team_flags.size(); + }; + std::vector cup_teams; + cup_teams.reserve(size_t(teams)); + for (int i = 0; !knockout && i < teams; ++i) { + const int team = int16_t(mem.u16(list + uint32_t(i) * 2)); + if (!valid_team(team) || + std::find(cup_teams.begin(), cup_teams.end(), team) != cup_teams.end()) + throw std::runtime_error("saved turn cursor: cup team list contains an invalid or duplicate team"); + cup_teams.push_back(team); + } + if (!knockout) { + int table_teams = 0; + switch (mem.pointer(entry + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break; + default: throw std::runtime_error("saved turn cursor: cup group has unknown round strings"); + } + const int rounds = mem.u8(entry + 0x1b) / ((flags & 1) + 1); + const std::vector expected = generate_fixtures(table_teams, round + 1, rounds, 0); + if (expected.size() < fixture_count / 2) + throw std::runtime_error("saved turn cursor: cup group round is incomplete"); + std::vector expected_fixture_ids; + expected_fixture_ids.reserve(fixture_count); + for (size_t i = 0; i < fixture_count / 2; ++i) { + if (expected[i].home < 0 || expected[i].home >= teams || + expected[i].away < 0 || expected[i].away >= teams) + throw std::runtime_error("saved turn cursor: cup round exceeds the saved team list"); + const int home = int16_t(mem.u16(list + uint32_t(expected[i].home) * 2)); + const int away = int16_t(mem.u16(list + uint32_t(expected[i].away) * 2)); + if (!valid_team(home) || !valid_team(away) || home == away || + std::find(cup_teams.begin(), cup_teams.end(), home) == cup_teams.end() || + std::find(cup_teams.begin(), cup_teams.end(), away) == cup_teams.end()) + throw std::runtime_error("saved turn cursor: generated cup fixture references an invalid team"); + expected_fixture_ids.push_back(home); + expected_fixture_ids.push_back(away); + } + for (size_t i = 0; i < fixture_count; ++i) { + const size_t at = 0x88 + i * 2; + const int team = int16_t(uint16_t(group.desc.at(at)) | (uint16_t(group.desc.at(at + 1)) << 8)); + if (team != expected_fixture_ids[i]) + throw std::runtime_error("saved turn cursor: cup fixture IDs disagree with the saved round"); + group.fixtures.push_back(team); + } + } else { + // SetupCupGroups derives KO fixtures from the stage team list and + // cup_round_offset; descriptor +0x88 is not populated for KO stages. + std::vector active_teams; + for (int i = 0; i < expected_matches * 2; ++i) { + const int team = int16_t(mem.u16(list + uint32_t(first + i) * 2)); + if (!valid_team(team) || std::find(active_teams.begin(), active_teams.end(), team) != active_teams.end()) + throw std::runtime_error("saved turn cursor: knockout fixture references an invalid team"); + active_teams.push_back(team); + group.fixtures.push_back(team); + } + for (int m = 0; m < expected_matches; ++m) + if (group.fixtures[size_t(m) * 2] == group.fixtures[size_t(m) * 2 + 1]) + throw std::runtime_error("saved turn cursor: knockout fixture contains the same team twice"); + } + + for (int leg = 0; leg < 2; ++leg) { + if (leg == 1 && !(flags & 1)) break; + const uint32_t address = mem.pointer(entry + 0x0c + uint32_t(leg) * 4); + // setup_cup_groups leaves the corresponding result vector empty when this stage + // has no result-array pointer; the match engine initializes its runtime scores. + if (address == 0) continue; + const uint32_t result_at = address + uint32_t(first / 2) * 2; + if (!mem.has(result_at + uint32_t(group.matches()) * 2 - 1)) + throw std::runtime_error("saved turn cursor: cup result array is missing"); + if (leg == 0) group.cup_result_address[0] = result_at; + else group.cup_result_address[1] = result_at; + std::vector& results = leg == 0 ? group.cup_results : group.cup_other_leg; + for (int m = 0; m < group.matches(); ++m) + results.push_back(mem.u16(result_at + uint32_t(m) * 2)); + } + group.records.assign(fixture_count * 9, 0); + group.end_minute.assign(size_t(group.matches()), 0); + group.spectators.assign(size_t(group.matches()), 0); +} + +int current_cup_stage(const StaticMemory& mem, int cup_id) { + int entry = find_cup(mem, cup_id); + if (entry < 0) return -1; + for (int guard = 0; guard < kCupEntries; ++guard) { + const uint32_t address = cup_entry_address(entry); + if (cup_round(mem, entry) < mem.u8(address + 0x1b)) return entry; + const int next = int8_t(mem.u8(address + 0x16)); + if (next < 0 || next >= kCupEntries) return -1; + entry = next; + } + return -1; +} + +void initialize_saved_replay_group(MatchGroup& group, GameState& state, size_t index, + int entry_index, int day) { + constexpr uint32_t kPostponed = ::bmh::layout::Postponed; + constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; + constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; + constexpr uint8_t kPostponedMark = 0xcd; + constexpr int kMaxReplayMatches = 9; // AddBlock clears 0x12 result bytes. + StaticMemory& mem = state.memory; + const uint32_t entry = cup_entry_address(entry_index); + group.desc = group_descriptor(state, index); + const uint32_t saved_entry = saved_group_u32(group.desc, 0xcc); + const uint8_t flags = mem.u8(entry + 0x14); + if (group.desc.size() != 0xd0 || group.desc[0] != 10 || + saved_entry != kGuestDataBase + entry || group.desc[1] != flags || + int16_t(mem.u16(entry + 0x18)) != 9 || flags != 6 || + mem.u8(entry + 0x1d) != 0 || (mem.u8(entry + 0x1e) & 0x0f) != 1 || + mem.pointer(entry) != kReplayFixtures || mem.pointer(entry + 0x0c) != kReplayResults || + mem.pointer(entry + 0x10) != 0) + throw std::runtime_error("saved replay descriptor or stage is inconsistent"); + + std::vector replay_fixtures; + std::vector replay_keys; + replay_fixtures.reserve(kMaxReplayMatches); + for (int i = 0; i < 0x28; ++i) { + const uint32_t record = kPostponed + uint32_t(i) * 6; + if (mem.u16(record) != day) continue; + const int round = mem.u8(record + 2); + const int league = mem.u8(record + 3); + const int match = mem.u8(record + 4); + if (league < 0 || league >= kLeagueCount || round < 0 || + round >= league_matchdays(league) || + match >= int(kLeagueSizes[league] / 2)) + throw std::runtime_error("saved replay record is outside the league schedule"); + const std::vector fixtures = generate_fixtures( + league_table_teams(league), round + 1, league_matchdays(league) / 2, + league_first_team(league)); + if (match >= int(fixtures.size())) + throw std::runtime_error("saved replay record has no corresponding fixture"); + const size_t result = size_t(league) * 0x17c + size_t(round) * 10 + size_t(match); + if (result >= state.results.size() || state.results[result] != kPostponedMark) + throw std::runtime_error("saved replay record has no postponed result marker"); + const uint32_t key = (uint32_t(league) << 16) | (uint32_t(round) << 8) | uint32_t(match); + if (std::find(replay_keys.begin(), replay_keys.end(), key) != replay_keys.end()) + throw std::runtime_error("saved replay records contain a duplicate schedule key"); + const Fixture fixture = fixtures[size_t(match)]; + replay_keys.push_back(key); + replay_fixtures.push_back(fixture); + if (replay_fixtures.size() > kMaxReplayMatches) + throw std::runtime_error("saved replay day exceeds its result buffer"); + } + if (replay_fixtures.empty() || group.desc[2] != replay_fixtures.size() || + mem.u8(entry + 0x1a) != replay_fixtures.size() * 2) + throw std::runtime_error("saved replay match count disagrees with its records"); + // Neither transient address is in SaveState's serialized block layout; a loaded + // GameState therefore has no valid prior runtime buffer to reuse. + if (mem.has(kReplayFixtures) || mem.has(kReplayResults)) + throw std::runtime_error("saved replay transient blocks are unexpectedly present"); + + // The original rebuilds these two non-savegame buffers in AddBlock. Recreate + // only their current values, leaving the saved replay records/stage counters intact. + mem.add_block(kReplayFixtures, 0x50); + mem.add_block(kReplayResults, 0x12); + for (int i = 0; i < kMaxReplayMatches; ++i) + mem.set16(kReplayResults + uint32_t(i) * 2, 0xcccc); + for (size_t i = 0; i < replay_fixtures.size(); ++i) { + mem.set16(kReplayFixtures + uint32_t(i) * 4, uint16_t(replay_fixtures[i].home)); + mem.set16(kReplayFixtures + uint32_t(i) * 4 + 2, uint16_t(replay_fixtures[i].away)); + group.fixtures.push_back(replay_fixtures[i].home); + group.fixtures.push_back(replay_fixtures[i].away); + group.cup_results.push_back(0xcccc); + } + group.cup_result_address[0] = kReplayResults; + for (int i = 0; i < 4; ++i) group.desc.at(0xcc + size_t(i)) = uint8_t(entry >> (i * 8)); + group.records.assign(replay_fixtures.size() * 18, 0); + group.end_minute.assign(replay_fixtures.size(), 0); + group.spectators.assign(replay_fixtures.size(), 0); +} + +void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Database& db, + uint64_t session_id, uint64_t revision, + std::string& unsupported_continuation) { + // Original DailyInterest's resume path skips new-event preparation. Rebind its saved + // desk position and event data directly; replaying prepare_event here would draw RNG, + // reshuffle managers, and rewrite saved team state. + if (revision == 0 || session_id == 0 || state.manager_teams.empty()) + throw std::runtime_error("saved turn cursor: invalid session identity or manager roster"); + const int manager_count = int(state.manager_teams.size()); + if (manager_count > 4 || !state.memory.has(::bmh::layout::ActiveManager) || !state.memory.has(::bmh::layout::DeskPosition)) + throw std::runtime_error("saved turn cursor: manager continuation fields are missing"); + const int position = int(state.memory.u8(::bmh::layout::DeskPosition)); + const int active = int(state.memory.u8(::bmh::layout::ActiveManager)); + if (position < 0 || position >= manager_count) + throw std::runtime_error("saved turn cursor: manager position is outside the saved roster"); + if (manager_count == 1) { + if (position != 0 || active != 0) + throw std::runtime_error("saved turn cursor: single-manager slot does not match the saved desk"); + } else { + if (!state.memory.has(::bmh::layout::NextDeskManager + uint32_t(manager_count) * 2 - 1)) + throw std::runtime_error("saved turn cursor: manager order is missing"); + std::vector seen(size_t(manager_count), false); + for (int i = 0; i < manager_count; ++i) { + const int slot = int(state.memory.u16(::bmh::layout::NextDeskManager + uint32_t(i) * 2)); + if (slot < 0 || slot >= manager_count || seen[size_t(slot)]) + throw std::runtime_error("saved turn cursor: manager order is sparse or duplicated"); + seen[size_t(slot)] = true; + } + if (active != int(state.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2))) + throw std::runtime_error("saved turn cursor: active manager disagrees with saved order"); + } + + if (state.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && state.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) { + driver.stage = TurnDriver::Stage::SeasonEndDesk; + driver.loaded_matchday_resume = true; + driver.manager_position = position; + driver.revision = revision; + driver.session_id = session_id; + driver.referee_source = db.raw_referee_properties; + driver.referees = driver.referee_source; + return; + } + const int day = state.season_day(); + if (day < 0 || day >= 0x16d || !state.memory.has(kSavedCalendar + uint32_t(day) * 2 + 1) || + !state.memory.has(kSavedCompetitionBits + 3)) + throw std::runtime_error("saved turn cursor: current calendar entry is missing"); + const uint16_t entry = state.memory.u16(kSavedCalendar + uint32_t(day) * 2); + const uint32_t calendar_competitions = day_competitions(state, entry); + const uint32_t saved_competitions = state.memory.u32(kSavedCompetitionBits); + // AdvanceTurn maps the national-team-only marker national-only flag to saved + // SavedCompetition=0 before it creates the no-fixture desk. Resume must compare + // against that canonical saved value, not treat the calendar marker as a cup. + const uint32_t competitions = calendar_competitions == 0x800000 && saved_competitions == 0 + ? 0 : calendar_competitions; + if (competitions != saved_competitions) + throw std::runtime_error("saved turn cursor: current calendar and saved competition flags disagree"); + if (competitions & ~0x7ffffu) + unsupported_continuation = "Dieser Spieltag kann mit den verfügbaren Wettbewerbsdaten derzeit nicht fortgesetzt werden."; + if (!unsupported_continuation.empty()) return; + + std::vector active_leagues; + // DayCompetitions2's competition bits expand to group leagues in this original order; + // bit 2 owns both league 2 and 3. The stale descriptors after the active group count + // are intentionally ignored. + static constexpr int first_league[8] = {0, 1, 2, 4, 5, 6, 7, 8}; + static constexpr int league_count[8] = {1, 1, 2, 1, 1, 1, 1, 1}; + for (int bit = 0; bit < 5; ++bit) { + if (!((competitions >> bit) & 1u)) continue; + const int first = bit, last = bit < 4 ? bit + 1 : 8; + for (int k = first; k < last; ++k) + for (int league = first_league[k]; league < first_league[k] + league_count[k]; ++league) + active_leagues.push_back(league); + } + if (active_leagues.size() > 6) + throw std::runtime_error("saved turn cursor: too many league fixtures are active"); + + std::vector groups; + groups.reserve(active_leagues.size()); + for (size_t i = 0; i < active_leagues.size(); ++i) { + MatchGroup group; + initialize_saved_match_group(group, state, i, active_leagues[i]); + groups.push_back(std::move(group)); + } + // Rebind saved cup descriptors and their current stage fixtures/results. Group-stage + // IDs live at descriptor +0x88; KO IDs live in the stage list. Replays reconstruct + // only missing transient buffers. Calling setup_cup_groups would replay event work. + bool has_empty_cup = false; + try { + for (int bit = 5; bit < 0x13; ++bit) { + if (!((competitions >> bit) & 1u)) continue; + const int cup_id = bit - 5; + int entry = current_cup_stage(state.memory, cup_id); + if (entry < 0) throw std::runtime_error("cup stage is missing"); + const uint32_t first_entry = cup_entry_address(entry); + const int type = int16_t(state.memory.u16(first_entry + 0x18)); + // Type 9's daily fixtures can be reconstructed from the saved postponed-match + // records. Other special competitions need preparation hooks and stay guarded. + if (type < 0 || (type > 9 && type != 10 && type != 11 && type != 13)) + throw std::runtime_error("this cup type requires event preparation"); + // SetupCupGroups creates a group only inside its per-stage `teams != 0` + // branch. A validated type-8 stage with zero teams is therefore a valid + // no-group cup day. On FBM load, competition_pointers() rebinds the native + // null list pointer to its runtime address; the team-count gate is the + // stable Source behavior across both representations. + if (type == 8 && state.memory.u8(first_entry + 0x1a) == 0) { + has_empty_cup = true; + continue; + } + // SetupCupGroups sets CareerSessionRuntimeField while projecting competition 11. + // This runtime-only mode is absent from the saved byte stream, so infer + // it from the authoritative active cup while rebuilding its MatchGroup. + if (type == 11) state.indoor = true; + const int parallel = state.memory.u8(first_entry + 0x1e) & 0x0f; + if (parallel == 0) throw std::runtime_error("cup stage has no saved parallel groups"); + const size_t groups_before_cup = groups.size(); + for (int k = 0; k < parallel; ++k, ++entry) { + if (entry < 0 || entry >= kCupEntries) + throw std::runtime_error("cup stage points outside the saved cup table"); + if (state.memory.u8(cup_entry_address(entry) + 0x1a) == 0) continue; + if (groups.size() >= 6) + throw std::runtime_error("too many saved match groups"); + MatchGroup group; + if (type == 9) + initialize_saved_replay_group(group, state, groups.size(), entry, day); + else + initialize_saved_cup_group(group, state, groups.size(), cup_id, entry); + groups.push_back(std::move(group)); + } + if (groups.size() == groups_before_cup) + throw std::runtime_error("cup stage has no saved fixture group"); + } + if (competitions != 0 && groups.empty() && !has_empty_cup) + throw std::runtime_error("active matchday has no saved fixture groups"); + } catch (const std::exception& e) { + (void)e; // Do not expose internal parser/descriptor details to the player. + unsupported_continuation = "Der Pokalspieltag kann mit den gespeicherten Paarungen nicht sicher fortgesetzt werden."; + return; + } + if (!groups.empty() && db.raw_referee_properties.empty()) + throw std::runtime_error("saved turn cursor: referee source is missing"); + std::vector referees = db.raw_referee_properties; + for (uint8_t& ref : referees) ref &= 0x7f; + for (const MatchGroup& group : groups) + for (int m = 0; m < group.matches(); ++m) { + const uint8_t ref = group.desc.at(0x10 + size_t(m)); + if (ref > 0 && ref < referees.size()) referees[ref] |= 0x80; + } + std::string error; + if (!begin_turn_driver(driver, state, std::move(groups), entry, db.raw_referee_properties, + session_id, revision, error)) + throw std::runtime_error("saved turn cursor: " + error); + driver.referees = std::move(referees); + // Runtime provenance belongs to this successfully restored Native desk loop. + // It is not inferred from a nonzero cursor, and does not select a policy. + driver.loaded_matchday_resume = true; +} +} + +// The league structure of the loaded game (schedule.hpp): sizes LeagueSizes (German +// 18 18 18 18 18 12 12 12 12, English 20 20 20 20 10 12 12 12 12) and calendar groups. +static void install_league_sizes(const LeImage& exe) { + uint8_t sizes[kLeagueCount]; + for (int l = 0; l < kLeagueCount; ++l) sizes[l] = exe.u8(::bmh::layout::LeagueSizes + uint32_t(l)); + set_league_sizes(sizes); + install_fixture_tables(exe); + kEnglishCompetitions = sizes[0] == 20; + // the calendar groups (CalendarFirstLeague first league, CalendarLeagueCounts league count per bit) + uint8_t first[8], count[8]; + for (uint32_t b = 0; b < 8; ++b) first[b] = exe.u8(::bmh::layout::CalendarFirstLeague + b), count[b] = exe.u8(::bmh::layout::CalendarLeagueCounts + b); + set_league_groups(first, count); + // the promotion ladder (schedule.hpp) + for (uint32_t l = 0; l < uint32_t(kLeagueCount); ++l) { + kLeagueRelegation[l] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField2 + l); + kLeagueEurope[l] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField + l); + kLeagueSuffix[l] = char(l < 5 ? exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField3 + l * 2) : 0); + } + for (uint32_t g = 0; g < 8; ++g) kGroupBelow[g] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField5 + g), kGroupBelowCount[g] = exe.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField4 + g); + kNewcomerFirst = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField); + kNewcomerCount = exe.u16(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField6); + // EXE strings the engine posts (messages.hpp) + kContractEndsSoonText = exe.cstring(kEnglishCompetitions ? ::bmh::layout::EnglishContractExpiryWarningText : ::bmh::layout::ContractExpiryWarningText); + kMastersQualificationText = kEnglishCompetitions ? "Masters entry confirmed. Your participation bonus has been credited." : exe.cstring(::bmh::layout::MastersQualificationText); + kMastersWinnerText = kEnglishCompetitions ? "Masters title won. Your prize money has been credited." : exe.cstring(::bmh::layout::MastersWinnerText); + kIndoorInvitationText = kEnglishCompetitions ? "Indoor event entry bonus credited for " : exe.cstring(::bmh::layout::IndoorInvitationText); + kChampionshipBonusText = kEnglishCompetitions ? "League title bonus credited." : exe.cstring(::bmh::layout::ChampionshipBonusText); + kFriendlyPayerPrefixText = kEnglishCompetitions ? "Your share: " : exe.cstring(::bmh::layout::NationalFriendlyPayerPrefixText); +} + +CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed) + : data_directory_(data), exe_(load_le(data / "BMH.exe")), + db_(load_database(data / "M3D.MAN")), + texts_(load_textd(data / "TEXTD.BLK")), + rand_(watcom_seed) { + install_league_sizes(exe_); + turn_driver_.alternate_match_event_roll = exe_.u8(::bmh::layout::AlternateEventRoll) != 0; + turn_driver_.disable_match_events = exe_.u8(::bmh::layout::MatchEventsDisabled) != 0; + turn_driver_.transfer_allocator_context = exe_.u8(::bmh::layout::MatchEventsDisabled) == 0 + ? TransferAllocatorContext::zero : TransferAllocatorContext::blocked; + session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed); + initialize_club_modal_runtime(); + g_ = startup_state(exe_, db_, read_file(data / "M3.MEN"), read_file(data / "M3.DAT")); + g_.texts = &texts_; + g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText + configure_training_camp_data(g_, exe_); + for (size_t i = 0; i < g_.credit_rate_table.size(); ++i) g_.credit_rate_table[i] = exe_.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + g_.credit_divisor = std::bit_cast(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32); + g_.credit_rate_table_available = true; + install_default_hooks(); + startup_players(g_, game_, rand_); // CareerFirstSteps2 + MinuteReport report; + if (!new_career_before_dialog(g_, game_, rand_, report)) // InitializeCareer up to the dialog + throw std::runtime_error("career start: " + report.reason); +} + +CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed, + const std::filesystem::path& save_path) + : data_directory_(data), exe_(load_le(data / "BMH.exe")), db_(load_database(data / "M3D.MAN")), + texts_(load_textd(data / "TEXTD.BLK")), rand_(watcom_seed) { + install_league_sizes(exe_); + turn_driver_.alternate_match_event_roll = exe_.u8(::bmh::layout::AlternateEventRoll) != 0; + turn_driver_.disable_match_events = exe_.u8(::bmh::layout::MatchEventsDisabled) != 0; + turn_driver_.transfer_allocator_context = exe_.u8(::bmh::layout::MatchEventsDisabled) == 0 + ? TransferAllocatorContext::zero : TransferAllocatorContext::blocked; + session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed); + initialize_club_modal_runtime(); + const Savegame file = load_savegame(save_path); + if (!file.checksum_ok || file.version != "V2.24") throw std::runtime_error("savegame: unsupported or damaged FBM"); + const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)}; + const SaveState save(file.stream, counts); + g_ = GameState::from_save(save, counts); + // CompetitionPointers2, after DeskDate2: these are process statics, not FBM fields. + // Resuming within this month must not count it as a newly elapsed month. + g_.autosave_months = 0; + g_.autosave_month = month_code(g_.date); + // Original CompetitionPointers2 calls CompetitionPointers after loading the stream. This + // rebinds pointer fields in the saved competition table before any resume + // path dereferences them (the serialized values may point into the old process). + competition_pointers(g_.memory, exe_); + g_.texts = &texts_; + g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText + configure_training_camp_data(g_, exe_); + for (size_t i = 0; i < g_.credit_rate_table.size(); ++i) g_.credit_rate_table[i] = exe_.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + g_.credit_divisor = std::bit_cast(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32); + g_.credit_rate_table_available = true; + install_default_hooks(); + national_coach_after_load(g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again) + if (g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)) game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField))); + restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_); + capture_source_desk_callargs(); +} + +int CareerSession::runtime_club(int master) const { return runtime_club(g_, master); } + +int CareerSession::runtime_club(const GameState& state, int master) const { + // ClubsChangePlaces moves a club together with its name: the club whose name offset is the + // master entry's is the one the manager chose + const uint16_t offset = uint16_t(db_.raw_club_name_offsets.at(size_t(master) * 2) | db_.raw_club_name_offsets.at(size_t(master) * 2 + 1) << 8); + for (size_t t = 0; t < state.club_ids.size(); t++) + if (state.club_ids[t] == offset) return int(t); + return -1; +} + +ui::SelectionContext CareerSession::selection_context(uint64_t revision) const { return selection_context_for(g_, revision); } + +ui::SelectionContext CareerSession::selection_context_for(const GameState& state, uint64_t revision) const { + ui::SelectionContext c; + c.revision = revision; + c.source = "engine"; + for (size_t t = 0; t < state.club_ids.size(); t++) { + int master = int(t); + for (size_t m = 0; m * 2 + 1 < db_.raw_club_name_offsets.size(); m++) + if (uint16_t(db_.raw_club_name_offsets[m * 2] | db_.raw_club_name_offsets[m * 2 + 1] << 8) == state.club_ids[t]) { + master = int(m); + break; + } + c.club_order.push_back(master); + } + return c; +} + +std::vector CareerSession::manager_choices(uint64_t revision) const { + const auto context = selection_context(revision); + std::vector choices; + for (size_t slot = 0; slot < g_.manager_teams.size(); ++slot) { + const int team = g_.manager_teams[slot]; + if (team < 0 || size_t(team) >= context.club_order.size()) throw FormatError("join: invalid existing club"); + ui::ManagerChoice c; + c.slot = int(slot); c.selection_club = team; c.master_club = context.club_order[size_t(team)]; + c.roster_revision = revision; + const size_t at = slot * 0xb0c; + for (size_t i = 0; i < 25 && g_.manager_records.at(at + 0xa8 + i); ++i) + c.name.push_back(char(g_.manager_records[at + 0xa8 + i])); + c.start_league = g_.manager_records.at(at + 0x210); + c.portrait = g_.manager_records.at(at + 0x221); + choices.push_back(std::move(c)); + } + return choices; +} + +bool CareerSession::begin_manager_join(const ui::DeskRequest& origin, const ui::SetupOptions& options, + uint64_t revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + try { + const auto desk = desktop_projection(revision); + const auto& current = desk.options; + if (manager_join_ || origin.kind != ui::DeskRequestKind::open_menu || origin.menu_kind != 29 || + origin.revision != revision || origin.manager_slot != desk.manager_slot || desk.national_team || + revision > std::numeric_limits::max() - 4 || + options.managers < current.managers || options.managers > 4 || + options.difficulty < 0 || options.difficulty > 9 || + (current.difficulty == 0 && options.difficulty != 0) || + options.duration != current.duration || options.mode != current.mode || + options.league != current.league || options.world != current.world) + throw FormatError("join: options or origin no longer match the running career"); + ManagerJoinDraft draft; + draft.state = g_; draft.rand = rand_; draft.game = game_; + draft.options = options; draft.origin = origin; draft.choices = manager_choices(revision); + draft.original_stream = save_stream(g_); draft.original_rand_seed = rand_.seed(); + draft.original_game_seed = game_.seed(); draft.original_rand_calls = rand_.calls(); + draft.original_game_calls = game_.calls(); draft.context_revision = revision; + auto& mem = draft.state.memory; + mem.set8(::bmh::layout::Difficulty, uint8_t(options.difficulty)); draft.state.level = options.difficulty; + mem.set8(::bmh::layout::ManagerCount, uint8_t(options.managers)); + const uint16_t signature = uint16_t(options.mode + options.duration * 4 + options.difficulty * 0x40); + mem.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField7, 2); + mem.set16(::bmh::layout::CareerSession_FormatError_RuntimeField7, mem.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == signature ? signature : 0); + mem.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); mem.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + if (mem.u32(::bmh::layout::CompetitionSelection) == 1) + for (int slot = current.managers; slot < options.managers; ++slot) + draft.state.manager_options.at(size_t(slot) * 5 + 4) = 1; + career_managers_begin(draft.state, true); + manager_join_ = std::move(draft); + return true; + } catch (const std::exception& e) { error = e.what(); return false; } +} + +ui::SelectionContext CareerSession::manager_join_context() const { + if (!manager_join_) throw FormatError("join: no draft"); + return selection_context_for(manager_join_->state, manager_join_->context_revision); +} + +bool CareerSession::manager_join_complete() const { + return manager_join_ && manager_join_->choices.size() == size_t(manager_join_->options.managers); +} + +bool CareerSession::confirm_manager_join(const ui::ManagerChoice& choice, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!manager_join_ || manager_join_complete()) { error = "join: no pending manager"; return false; } + auto before = *manager_join_; + try { + auto& draft = *manager_join_; + const auto context = manager_join_context(); + if (choice.slot != int(draft.choices.size()) || choice.roster_revision != context.revision || + choice.name.empty() || choice.name.size() > 24 || choice.name.find('\0') != std::string::npos || + choice.start_league < 0 || choice.start_league > 4 || choice.strength < 0 || choice.strength > 2 || + choice.portrait < 0 || choice.portrait > 11 || choice.selection_club < 0 || + size_t(choice.selection_club) >= context.club_order.size() || + context.club_order[size_t(choice.selection_club)] != choice.master_club || + std::any_of(draft.choices.begin(), draft.choices.end(), [&](const auto& old) { + return old.master_club == choice.master_club || old.portrait == choice.portrait; + })) throw FormatError("join: invalid or stale manager choice"); + CareerManager selected; + selected.name = choice.name; selected.team = runtime_club(draft.state, choice.master_club); + selected.league = choice.start_league; selected.strength = choice.strength; selected.portrait = choice.portrait; + if (selected.team < 0) throw FormatError("join: club not found"); + MinuteReport report; + if (!career_add_manager(draft.state, exe_, choice.slot, selected, true, draft.game, draft.rand, report)) + throw FormatError(report.reason); + draft.choices.push_back(choice); ++draft.context_revision; + return true; + } catch (const std::exception& e) { manager_join_ = std::move(before); error = e.what(); return false; } +} + +bool CareerSession::commit_manager_join(ui::CareerInitializationResult& result, uint64_t& revision, + std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!manager_join_complete()) { error = "join: selection incomplete"; return false; } + auto before = manager_join_checkpoint(); + const auto previous_revision = revision; + try { + const auto& draft = *manager_join_; + if (draft.origin.revision != revision || save_stream(g_) != draft.original_stream || + rand_.seed() != draft.original_rand_seed || game_.seed() != draft.original_game_seed || + rand_.calls() != draft.original_rand_calls || game_.calls() != draft.original_game_calls) + throw FormatError("join: career changed during selection"); + g_ = draft.state; rand_ = draft.rand; game_ = draft.game; + career_managers_end(g_, true); + managers_.clear(); + for (const auto& c : draft.choices) + managers_.push_back({c.slot, c.master_club, g_.manager_teams.at(size_t(c.slot))}); + // ConfirmManager retains the current desk/cursor. Weiter performs the later handoff. + const auto next_revision = revision + 1; + turn_driver_.revision = next_revision; + ui::CareerInitializationResult next; + next.desktop = desktop_projection(next_revision); next.managers = managers_; + next.preparation = preparation_projection(next_revision); + ui::validate_preparation_context(next.preparation); + result = std::move(next); revision = next_revision; manager_join_.reset(); + return true; + } catch (const std::exception& e) { + restore_manager_join_checkpoint(std::move(before)); revision = previous_revision; + error = e.what(); return false; + } +} + +void CareerSession::apply_options(const ui::SetupOptions& o) { + // SetupScreen2 takes the four numbers over when the options dialog is left + StaticMemory& mem = g_.memory; + mem.set8(::bmh::layout::CareerDuration, uint8_t(o.duration)); + mem.set8(::bmh::layout::Difficulty, uint8_t(o.difficulty)); + g_.level = o.difficulty; // (the typed copy) + mem.set8(::bmh::layout::ManagerCount, uint8_t(o.managers)); + mem.set8(::bmh::layout::GameMode, uint8_t(o.mode)); + mem.set32(::bmh::layout::CompetitionSelection, (o.league ? 1u : 0u) | (o.world ? 2u : 0u)); + // The end of SetupScreen2 at a new game (param_1 = 0, the first manager): + // - a one-manager game flags its manager as Bundestrainer (record +0x21c, CareerSessionRuntimeField2); + // - without the league game every calendar day (CompetitionCalendar, 0x16e words) except the + // World Cup finals (0x4006) loses its low byte and keeps only the international bits + // 0x1e of its high byte; + // - without the World Cup game the international bits go: the high byte keeps 0x61 only. + // So the national team plays (and its manager takes over, SwapManagerSlots2 on 0x1e00 + // days) only when the World Cup mode is on, as the manual says (Handbuch 2, p. 11); + // - the league-only game sets option byte 4 (CareerSessionRuntimeField3) of every manager. + if (managers_.empty() && o.managers == 1 && g_.manager_records.size() >= 0xb0c) + g_.manager_records.at(0x21c) = 1; + if (mem.has(kSavedCalendar + 0x16e * 2 - 1)) + for (uint32_t day = 0; day < 0x16e; ++day) { + const uint32_t at = kSavedCalendar + day * 2; + uint16_t word = mem.u16(at); + if (!o.league && word != 0x4006) word = uint16_t(word & 0x1e00); + if (!o.world) word = uint16_t(word & 0x61ff); + mem.set16(at, word); + } + if (o.league && !o.world) + for (int m = 0; m < o.managers && size_t(m) * 5 + 4 < g_.manager_options.size(); ++m) + g_.manager_options.at(size_t(m) * 5 + 4) = 1; + career_managers_begin(g_); + options_applied_ = true; +} + +bool CareerSession::confirm_manager(const ui::SetupOptions& options, const ui::ManagerChoice& choice, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + if (!options_applied_) apply_options(options); + const int m = int(managers_.size()); + if (m >= options.managers) { + error = "more managers than chosen in the options"; + return false; + } + CareerManager c; + c.name = choice.name; + c.team = runtime_club(choice.master_club); + c.league = choice.start_league; + c.strength = choice.strength; + c.portrait = choice.portrait; + if (c.team < 0) { + error = "club not found"; + return false; + } + MinuteReport report; + if (!career_add_manager(g_, exe_, m, c, false, game_, rand_, report)) { + error = report.reason; + return false; + } + managers_.push_back({choice.slot, choice.master_club, g_.manager_teams.at(size_t(m))}); + return true; +} + +std::optional 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; } +} + +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; } +} + +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; + } +} + +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; + } +} + +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; + } +} + +void CareerSession::initialize_club_modal_runtime() { + // LE object4 has bb cdd/de/e1 in its zero-initialized virtual tail; + // CareerSession_InitializeClubModalRuntime_ExecutableField is file-backed zero. These are explicit process-start values, + // carried by this runtime owner across modal entry/return, not FBM bytes. + for(uint32_t address:{::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchPoachUi_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2Unsigned,::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableFieldUnsigned}) + club_modal_runtime_.emplace(address,exe_.u8(address)); +} + +SportschauSourceOptions 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_)}; +} + +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; +} + +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 { +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)); +} + +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; +} + +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)); + } + } + } + } +} + +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; +} + +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); +} + +int8_t source_byte(int value) { return static_cast(uint8_t(value)); } + +std::string source_table_range_label(const TextDb& texts,int first,int end) { + // DE50860 patches offsets 4/7 of its nine-byte TEXTD82 buffer. EN1e83f + // patches 0/3 of the full " 0-34 only" string instead (the final y is live). + const auto fixed=texts.raw(82,9); + auto raw=kEnglishCompetitions ? texts[82] : std::string(fixed.begin(),fixed.end()); + const size_t start=kEnglishCompetitions ? 0 : 4; + const size_t finish=kEnglishCompetitions ? 3 : 7; + if(raw.size()=int(game.league_rounds.size())) + throw FormatError("league table: missing Source round byte"); + const int8_t raw_end=source_byte(table.end_round); + const int8_t raw_first=source_byte(table.first_round); + const uint8_t raw_round=game.league_rounds[size_t(league)]; + const int max_round=bmh::league_matchdays(league); + if(max_round3||id.league<0||id.league>=bmh::kLeagueCount|| + !game.memory.has(::bmh::layout::ActiveManager)||game.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + size_t(id.manager)>=game.manager_teams.size()||game.manager_teams[size_t(id.manager)]!=id.runtime_club|| + game.date!=id.day_counter||id.runtime_club<0||size_t(id.runtime_club)>=game.club_ids.size()|| + int(game.club_ids[size_t(id.runtime_club)])!=id.club_identity|| + id.league_group>1) return false; + const size_t record=size_t(id.manager)*0xb0c; + if(record+0x212>game.manager_records.size()|| + id.manager_default_league!=int(game.manager_records[record+0x210])) return false; + const uint32_t settings=::bmh::layout::ManagerSettings+uint32_t(id.manager)*2; + const uint32_t family=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + return game.memory.has(settings+1)&&game.memory.has(family+1)&& + game.memory.u16(settings)==id.expected_settings_word&& + game.memory.u16(family)==id.expected_family_word; +} + +bool canonical_table_envelope(const ui::LeagueFamilyRequest& request,int control_index=-1, + bool allow_selector_league=false) { + return request.target_child==0&&request.runtime_team==-1&&request.expected_club_identity==-1&& + request.table_row_index==-1&&(allow_selector_league||request.league_id==-1)&& + request.control_index==control_index&& + !request.table_dialog_reply; +} + +void source_table_apply_entry_flags(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); +} + +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; +} +} + +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; +} + +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; +} + +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>=168||request->identity.source_param2|| + league_family_owner_||strengths_owner_||league_pairings_draft_) { + error="friendly table: unavailable club entry";return {}; + } + const auto checkpoint=league_family_checkpoint(); + try { + auto identity=request->identity; + // Desktop case6 initializes these before its direct FriendlyMatchScreen(2,0). + const uint32_t word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2; + const auto mode=exe_.u8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField+uint32_t(identity.league)); + uint16_t word=uint16_t((g_.memory.u16(word_at)&0xfc0f)|0x0170); + if(mode)word|=0x80; + g_.memory.set16(word_at,word); + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2]=uint8_t(identity.league); + club_modal_runtime_[::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField]=0;identity.league_group=0; + club_modal_runtime_[::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField]=mode;club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField]=0; + club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0; + identity.expected_family_word=word; + const auto bound=begin_league_family(identity,1,revision,error); + if(!bound)throw FormatError(error.empty()?"friendly table: owner entry rejected":error); + league_family_owner_->friendly_opponent=true; + return bound; + } catch(const std::exception& e) { + restore_league_family_checkpoint(checkpoint);error=e.what();return {}; + } +} + +std::optional 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>=168|| + size_t(normal.runtime_team_id)>=g_.club_ids.size()|| + normal.club_identity_key!=int(g_.club_ids[size_t(normal.runtime_team_id)])) { + error="friendly table: opponent row identity changed";return {}; + } + // After a forecast Present FriendlyMatchScreen resolves TableRuntimeField6's restored normal ranks. + return normal.runtime_team_id; +} + +std::optional 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; +} + +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 {}; + } +} + +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; +} + +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))); +} + +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 {};} +} + +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; +} + +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; +} + +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; +} + +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; + struct Reset { const PhaseResultRequest*& request; ~Reset() { request = nullptr; } } reset{phase_result_request_}; + hook(request, groups, state); + if (live_overview_owner_ && live_overview_owner_->phase_result) + throw FormatError("phase results: viewer must close before the engine ACK"); + }; +} + +std::optional 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)*0x17c + size_t(entered.league_rounds.at(id))*10; + for (size_t m = 0; m < group.results.size(); ++m) + entered.results.at(at+m) = group.results[m]; + } else store_cup_results(entered, group); + } + const int manager = entered.memory.u8(::bmh::layout::ActiveManager); + if (manager < 0 || size_t(manager) >= entered.manager_teams.size()) + throw FormatError("phase results: unavailable active Source manager"); + LiveOverviewRequest request; + request.key_slot = 1; request.minute = phase_result_request_->phase_end_minute; + request.group_index = int(phase_result_request_->group_index); + request.manager_slot = manager; request.runtime_team = entered.manager_teams[size_t(manager)]; + request.revision = revision; request.sequence = next_live_overview_scope_; + const auto checkpoint = g_; + g_ = std::move(entered); + MatchEngine context{g_, turn_driver_.groups, game_, rand_, turn_driver_.referees}; + auto page = open_running_overview(request, context, revision, underlay, error, true); + if (!page) g_ = checkpoint; + return page; + } catch (const std::exception& e) { error = e.what(); return {}; } +} + +std::optional 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); +} + +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); +} + +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 {}; + } + + + 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 { + 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(); + live_overview_owner_->kind=live.kind; + live_overview_owner_->family_identity=live.family_identity; + live_overview_owner_->request.revision=next_revision; + ++next_live_overview_scope_; + revision=next_revision; + return result; + } catch(const std::exception& e) { + restore_league_family_checkpoint(family_checkpoint); + restore_league_pairings_checkpoint(pairings_checkpoint); + restore_other_games_checkpoint(other_checkpoint); + live_overview_owner_.reset(); + next_live_overview_scope_=scope_checkpoint; + error=e.what(); + return {}; + } +} + +std::optional 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 {};} +} + +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); + }; + 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 {};} +} + +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 {};} +} + +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; + 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; + if(!live_unchanged||!accepted||(poach_selection?entry_calls<1:entry_calls!=1)) + throw FormatError("league family: TeamInfo presenter changed owner or did not enter the selected club"); + const size_t record=size_t(id.manager)*0xb0c; + if(next.date!=g_.date||next.manager_teams!=g_.manager_teams|| + !next.memory.has(::bmh::layout::ActiveManager)||next.memory.u8(::bmh::layout::ActiveManager)!=id.manager||record+0x292>next.manager_records.size()|| + (int(next.manager_records[record+0x290])|int(next.manager_records[record+0x291])<<8)!=id.runtime_club|| + size_t(id.runtime_club)>=next.club_ids.size()||int(next.club_ids[size_t(id.runtime_club)])!=id.club_identity|| + record+0x212>next.manager_records.size()|| + int(next.manager_records[record+0x210])!=id.manager_default_league) + throw FormatError("league family: TeamInfo changed active manager or date"); + auto refreshed=id;refreshed.revision=revision+1;refreshed.family_sequence=id.family_sequence+1; + refreshed.expected_settings_word=next.memory.u16(::bmh::layout::ManagerSettings+uint32_t(id.manager)*2); + const uint32_t family_word_at=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(poach_selection && *poach_selection) { + const auto chosen=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 {};} +} + +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; +} + +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; + if(league_family_teaminfo_active_||strengths_dispatch_active_||revision==UINT64_MAX||id.revision!=revision||id.sequence==UINT64_MAX|| + id.manager<0||id.manager>3||!g_.memory.has(::bmh::layout::ActiveManager)||g_.memory.u8(::bmh::layout::ActiveManager)!=id.manager|| + size_t(id.manager)>=g_.manager_teams.size()||id.runtime_club!=g_.manager_teams[size_t(id.manager)]|| + id.runtime_club<0||size_t(id.runtime_club)>=g_.club_ids.size()|| + id.club_identity!=int(g_.club_ids[size_t(id.runtime_club)])||id.day_counter!=g_.date|| + id.league<0||id.league>8||career_complete()|| + (turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks&&turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk)|| + pending_offer_dispatch_active_||market_dispatch_active_||calendar_advance_active_||league_pairings_draft_|| + league_pairings_dispatch_active_||transfer_offer_editor_||manager_join_||contract_quote_|| + stadium_.investment||stadium_.tip||stadium_.periphery_quote||top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_) { + error="strengths: stale or unavailable owner";return {}; + } + const size_t rec=size_t(id.manager)*0xb0c; + const uint32_t setting=::bmh::layout::ManagerSettings+uint32_t(id.manager)*2,family=::bmh::layout::LeagueTableDisplayModes+uint32_t(id.manager)*2; + if(rec+0xb0c>g_.manager_records.size()|| + (int(g_.manager_records[rec+0x290])|int(g_.manager_records[rec+0x291])<<8)!=id.runtime_club|| + !g_.memory.has(setting+1)||!g_.memory.has(family+1)|| + id.expected_settings_word!=g_.memory.u16(setting)||id.expected_family_word!=g_.memory.u16(family)) { + error="strengths: inconsistent manager or saved settings";return {}; + } + if(opening) { + const int initial=id.runtime_club>356?0:team_league(id.runtime_club); + if(strengths_owner_||id.scope||id.sequence||(!family_transition&&id.league!=initial)|| + (family_transition&&((id.source_param2!=0&&!live_source_identity(id))||id.league_group>1||id.manager_default_league<0||id.manager_default_league>8))|| + next_strengths_scope_==UINT64_MAX|| + request.value!=-1||request.control!=ui::StrengthsControl::condition) { + error="strengths: invalid entry";return {}; + } + } else if(!strengths_owner_||id!=strengths_owner_->page.identity|| + save_stream(g_)!=strengths_owner_->native|| + rand_.seed()!=strengths_owner_->rand_seed||rand_.calls()!=strengths_owner_->rand_calls|| + game_.seed()!=strengths_owner_->game_seed||game_.calls()!=strengths_owner_->game_calls) { + error="strengths: stale modal snapshot";return {}; + } + // The process timer's automatic Source event8 belongs to an unported modal + // context. Ordinary desk entry initializes this runtime timer to zero. + const auto byte=[&](uint32_t at) {if(g_.memory.has(at))return g_.memory.u8(at); + const auto found=club_modal_runtime_.find(at);return found==club_modal_runtime_.end()?uint8_t(0):found->second;}; + const uint32_t start=uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2))|uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField3))<<8| + uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField4))<<16|uint32_t(byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField5))<<24; + if(opening&&start!=0&&byte(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField)<200) { + error="strengths: active process-timer context unsupported";return {}; + } + if(request.kind==ui::StrengthsAction::pairings||request.kind==ui::StrengthsAction::table) { + error="strengths: navigation target not implemented";return {}; + } + if(request.kind==ui::StrengthsAction::team_info&&!team_info) { + error="strengths: TeamInfo presenter unavailable";return {}; + } + strengths_dispatch_active_=true; + struct Reset { bool& active; ~Reset(){active=false;} } reset{strengths_dispatch_active_}; + try { + StrengthsDispatch result; + if(request.kind==ui::StrengthsAction::team_info) { + if(request.control!=ui::StrengthsControl::condition||request.value<0) + throw FormatError("strengths: malformed TeamInfo target"); + // Keep an owned value copy across the external callback; callbacks + // can re-enter the public API and replace/reset modal ownership. + const auto current=strengths_owner_->page; + const auto target=std::find_if(current.projection.rows.begin(),current.projection.rows.end(), + [&](const auto& row){return row.runtime_team==request.value;}); + if(target==current.projection.rows.end()) + throw FormatError("strengths: TeamInfo target is not a visible team"); + + // Reset2 opens ClubInfoFromGame from the selected runtime row and + // resumes this same Strengths loop after the nested modal returns. + // Stage the presenter against the live page, then commit only if it + // did not re-enter or mutate the retained Strengths owner. + 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 {};} +} + +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 >= 138) { + 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 {}; + } +} + +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 >= 138 || + 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 {}; + } +} + +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; +} + +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!=0x165||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=kLeagueSizes[league];page.underlay=underlay; + page.gradient_text=g_.memory.has(::bmh::layout::TextGradientDisabled)&&g_.memory.u8(::bmh::layout::TextGradientDisabled)==0&&g_.memory.has(::bmh::layout::TextGradientMode)&&g_.memory.u8(::bmh::layout::TextGradientMode)==2; + page.current_rank=national_source_case?national_opportunities_rank(g_,team,page.ranks):table_prediction(g_,team,mode,page.ranks,nullptr); + opportunities_owner_=OpportunitiesOwner{page,save_stream(g_),game_,rand_,national_source_case};++next_opportunities_scope_; + return page; + } catch(const std::exception& e){error=e.what();return {};} +} + +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!=0x165|| + 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 {};} +} + +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 {}; + } +} + +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"); + 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; + 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 {}; + } +} + +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 {};} +} + +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=club==0x0fff||(club>89&&club<138)||(club>167&&club<357); + 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 {};} +} + +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;} +} + +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; +} + +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(); + 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 { +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; +} +} + +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); +} + +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); +} + +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; } +} + +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; } +} + +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; +} + +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; + } +} + +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; } +} + +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; + } +} + +std::optional CareerSession::dispatch_transfer_market( + const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters, + uint64_t& revision, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; } + error.clear(); + if (transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ || + request.revision != revision || revision == std::numeric_limits::max() || + request.manager_slot < 0 || request.manager_slot >= 4 || + size_t(request.manager_slot) >= g_.manager_teams.size() || + !g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + request.runtime_club != g_.manager_teams[size_t(request.manager_slot)]) { + error = "transfer market: stale or nested request"; + return std::nullopt; + } + if (request.kind == ui::TransferMarketRequestKind::submit_bid) { + if (request.bid.manager != request.manager_slot || request.squad_row != -1 || + request.expected_player != -1 || + std::any_of(request.bid.bonuses.begin(), request.bid.bonuses.end(), + [](uint32_t value) { return value > 255; })) { + error = "transfer market: invalid buyer request"; + return std::nullopt; + } + } else if (request.kind == ui::TransferMarketRequestKind::list_player) { + const auto range = squad_range(request.runtime_club); + if (request.squad_row < 0 || size_t(request.squad_row) >= range.count || + range.first + size_t(request.squad_row) >= g_.squad_slots.size() || + request.expected_player < 0 || request.expected_player >= 0xfff || + (g_.squad_slots[range.first + size_t(request.squad_row)] & 0xfff) != request.expected_player) { + error = "transfer market: stale seller row"; + return std::nullopt; + } + } else { + error = "transfer market: unsupported action"; + return std::nullopt; + } + // Reset sends an owned marked player through the same Size2 + // listing for both VER-KAUFEN and VER-LEIHEN. Only a buyer's OpenTransferEditor + // offer owns the actual loan term; listing does not create a loan record. + if ((request.offer_is_loan && request.kind != ui::TransferMarketRequestKind::list_player) || + request.selected_players.size() > 1) { + error = "transfer market: this caller does not own buyer loan or marked batch processing"; + return std::nullopt; + } + if (!request.selected_players.empty()) { + const auto& selected = request.selected_players.front(); + const bool matches = request.kind == ui::TransferMarketRequestKind::list_player + ? selected.squad_row == request.squad_row && selected.player == request.expected_player && + selected.seller == request.runtime_club && + selected.source_slot == int(squad_range(request.runtime_club).first + size_t(request.squad_row)) + : selected.list_entry == request.bid.list_entry && selected.source_slot == request.bid.source_slot && + selected.player == request.bid.player && selected.squad_row == -1; + if (!matches) { + error = "transfer market: mismatched marked selection"; + return std::nullopt; + } + } + + auto next_state = g_; + auto next_game = game_; + auto next_rand = rand_; + auto hooks = presenters; + // A presenter cannot supply the allocator gate or insert the special + // pending caller's severance/ACK/news sequence into a direct purchase. + switch (turn_driver_.transfer_allocator_context) { + case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + // Reset -> OpenTransferEditor establishes DeskActions_EditorFail_RuntimeField2=0 at LAB1b67e before + // resolving the AI seller. This explicitly selected App entry supplies + // that transient ownership; a missing FBM byte is never the observation. + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + hooks.before_accounts = {}; + hooks.after_paid_accounts = {}; + market_dispatch_active_ = true; + struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_}; + MinuteReport report; + try { + const auto before = save_stream(g_); + TransferActionResult result; + 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; + } +} + +bool CareerSession::finish(ui::CareerInitializationResult& result, std::string& error) { + if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; } + const bool previous_advance = calendar_advance_active_; + calendar_advance_active_ = true; + struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } + advance_reset{calendar_advance_active_, previous_advance}; + MinuteReport report; + career_managers_end(g_, false); + const auto season_pause = [this](const char* checkpoint) { + if (turn_driver_.season_pause) turn_driver_.season_pause(checkpoint, g_); + }; + if (!career_season_setup(g_, game_, rand_, report, season_pause, turn_driver_.season_cup_draw) || + !career_first_steps(g_, game_, rand_, report)) { + error = report.reason; + return false; + } + // DailyInterest's loop: the event of season day 0 (AdvanceTurn) and the first desk + std::vector referees = db_.raw_referee_properties; + MatchdayContext ctx; + ctx.month = month_code(g_.date); + ctx.season_day = g_.season_day(); + ctx.weekday = weekday_code(g_.date); + ctx.referees = &referees; + const uint16_t entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(g_.season_day()) * 2); + std::vector groups = prepare_event(g_, entry, ctx, game_, rand_, report); + enter_event_desk(g_, 0, groups, game_, rand_, report, true, turn_driver_.desk_autosave); + if (report.unsupported) { + error = report.reason; + return false; + } + if (!begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties, + session_id_, 1, error)) + return false; + capture_source_desk_callargs(); + // Both UI projections must reflect the freshly initialized driver cursor. + // Reuse its prepared groups; these projections do not prepare an event or draw RNG. + result.desktop = desktop_projection(1); + result.preparation = preparation_projection(1); + for (size_t m = 0; m < managers_.size(); ++m) + managers_[m].runtime_club = g_.manager_teams.at(m); + result.managers = managers_; + return true; +} + +TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request, uint64_t& revision, + std::string& error) { + error.clear(); + if (strengths_owner_ || strengths_dispatch_active_ || balance_draft_ || balance_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_ || league_pairings_draft_ || league_pairings_dispatch_active_ || transfer_offer_editor_ || pending_offer_dispatch_active_ || market_dispatch_active_) { + error = "pending_offer_decision_active"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (career_complete()) { + error = "career_complete"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = -1; + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (!saved_turn_error_.empty()) { + error = saved_turn_error_; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (request.kind != ui::DeskRequestKind::advance_turn || request.revision != revision) { + error = "stale_manager_or_revision"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + if (request.manager_slot != int(g_.memory.u8(::bmh::layout::ActiveManager))) { + error = "stale_manager_or_revision"; + TurnAdvanceResult result; + result.kind = TurnDeskKind::Failed; + result.manager_slot = int(g_.memory.u8(::bmh::layout::ActiveManager)); + result.date = g_.date; + result.revision = revision; + result.reason = error; + return result; + } + const auto remain_at_desk = [&](TurnDeskKind kind, std::string reason) { + if (reason.empty()) reason = "post-desk pending presenter stopped"; + error = std::move(reason); + TurnAdvanceResult out; + out.kind = kind; + out.manager_slot = request.manager_slot; + out.date = g_.date; + out.revision = revision; + out.reason = error; + return out; + }; + if (revision == std::numeric_limits::max() || + (turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk)) + return remain_at_desk(TurnDeskKind::Failed, "stale_or_exhausted_turn_cursor"); + + // Pending decisions and their cursor checks must complete together or + // restore the previous desk. Once simulation starts, its terminal failure + // cursor must stay claimed: external presentation cannot be rolled back. + struct KickoffTransaction { + CareerSession& session; + uint64_t& revision; + std::optional before; + void restore() { + if (!before) return; + auto checkpoint = std::move(*before); + before.reset(); + revision = checkpoint.revision; + session.restore_advertising_session_checkpoint(std::move(checkpoint)); + } + ~KickoffTransaction() { restore(); } + } transaction{*this, revision, advertising_session_checkpoint(revision)}; + const auto stop_at_desk = [&](TurnDeskKind kind, std::string reason) { + transaction.restore(); + return remain_at_desk(kind, std::move(reason)); + }; + const bool previous_advance = calendar_advance_active_; + calendar_advance_active_ = true; + struct AdvanceReset { bool& active; bool previous; ~AdvanceReset() { active = previous; } } + advance_reset{calendar_advance_active_, previous_advance}; + if ((turn_driver_.stage == TurnDriver::Stage::MatchdayDesks || + turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk) && + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive) { + // AdvanceTurn resolves this manager before the next desk or simulation. + // An unsupported decision must leave the driver unclaimed and retryable. + pending_offer_dispatch_active_ = true; + struct PendingReset { bool& active; ~PendingReset() { active = false; } } + pending_reset{pending_offer_dispatch_active_}; + try { + const auto modal_baseline = advertising_session_checkpoint(revision); + auto next_state = g_; + auto next_game = game_; + auto next_rand = rand_; + const auto hooks = pending_hooks_for_dispatch(pending_offer_hooks_); + MinuteReport pending_report; + // Explicit supported interactive runtime policy, not reconstructed + // Original transient bytes or an answer inferred from missing data. + const PendingOfferDeskRequest pending_request{ + PendingOfferDeskRuntimeMode::normal_interactive, + int(g_.manager_teams.size()), turn_driver_.manager_position}; + // A nomination desk has one temporary national manager but retains + // the original order prefix. Its Source post-return owner can differ + // from the runtime desk owner, so ordinary permutation checks do not apply. + const auto pending = turn_driver_.national_nomination_desk + ? process_national_nomination_pending_after_desk( + next_state, pending_request, next_game, next_rand, hooks, pending_report) + : process_natural_pending_offers_after_desk( + next_state, pending_request, next_game, next_rand, hooks, pending_report); + // This existing fingerprint covers Native and its qualified + // runtime/owners, RNG and revision, not arbitrary memory writes. + if (!advertising_session_unchanged(modal_baseline, revision) || + turn_driver_.manager_position != modal_baseline.driver.manager_position || + turn_driver_.revision != modal_baseline.driver.revision || + turn_driver_.calendar_entry != modal_baseline.driver.calendar_entry) + return stop_at_desk(TurnDeskKind::Failed, "pending_offer_reentrant_state"); + if (pending_report.unsupported || !pending.completed) + return stop_at_desk(TurnDeskKind::WaitingAtDesk, + pending_report.reason.empty() ? "post-desk pending decision incomplete" : pending_report.reason); + // Even a batch without owned offers performs Source's last-manager + // cleanup and completed-loop cursor write. No intermediate revision. + g_ = std::move(next_state); + game_ = next_game; + rand_ = next_rand; + } catch (const std::exception& e) { + return stop_at_desk(TurnDeskKind::WaitingAtDesk, e.what()); + } + } + // Resolve names before advancing: next_event can reorder clubs at a season + // transition. The result view must keep the identities of the played event. + std::vector names; + names.reserve(g_.club_ids.size()); + for (size_t team = 0; team < g_.club_ids.size(); ++team) + names.push_back(ui::original_to_utf8(g_.club_name(int(team)))); + const bool had_results = turn_driver_.last_results.valid; + const uint32_t previous_result_date = turn_driver_.last_results.date; + const uint32_t previous_day = g_.date; + const uint16_t previous_calendar_entry = turn_driver_.calendar_entry; + // Desk actions legitimately advance the app's projection revision between turns. + // Adopt that already-validated current revision before handing off the kickoff. + // AdvanceTurn(param1=1) skips only later pre-match offer generation in this + // already prepared loop. Legacy/headless callers retain their explicit path. + // Select it after a complete staged batch so Waiting cannot alter the cursor. + turn_driver_.suppress_remaining_pre_match_offers = + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive && + turn_driver_.loaded_matchday_resume; + // Select the complete nomination-desk lifecycle only for the interactive + // controller, after the staged outgoing batch has completed successfully. + turn_driver_.enable_national_nomination_desks = + pending_offer_entry_policy_ == PendingOfferEntryPolicy::normal_interactive; + turn_driver_.revision = revision; + MinuteReport report; + // Contract expiry can also be reached by a headless/unpresented session. + // Keep the checkpoint from before the complete pending decision batch so a + // missing decision owner cannot commit its Native cursor cleanup or leave + // an expired player partially advanced. + std::optional contract_expiry_checkpoint = transaction.before; + transaction.before.reset(); // claim the completed decision batch before simulation callbacks + turn_driver_.reality_rules = &exe_; + turn_driver_.sportschau_source = sportschau_source_options(); + TurnAdvanceResult result = advance_to_next_desk(turn_driver_, g_, + TurnAdvanceRequest{request.manager_slot, request.revision}, game_, rand_, report); + if (result.kind == TurnDeskKind::Failed || result.kind == TurnDeskKind::WaitingAtDesk) { + if (contract_expiry_checkpoint && (result.reason.find("month change: a contract ends") != std::string::npos || + result.reason.find("month change: human-owner loan record is incomplete") != std::string::npos || + result.reason.find("month change: human-owner loan cannot be restored safely") != std::string::npos || + result.reason.find("month change: expiring human-borrower loan") != std::string::npos || + result.reason.find("month change: human-borrower loan return dialog") != std::string::npos || + result.reason.find("month change: OpenTransferEditor return-offer editor") != std::string::npos)) { + const uint64_t checkpoint_revision = contract_expiry_checkpoint->revision; + restore_advertising_session_checkpoint(std::move(*contract_expiry_checkpoint)); + revision = checkpoint_revision; + return remain_at_desk(result.kind, result.reason); + } + return stop_at_desk(result.kind, result.reason); + } + revision = result.revision; + if (g_.date != previous_day || turn_driver_.calendar_entry != previous_calendar_entry) + capture_source_desk_callargs(); + lineup_entry_manager_ = -1; + lineup_entry_club_ = -1; + completed_results_.reset(); + const auto& snapshot = turn_driver_.last_results; + if (snapshot.valid && !snapshot.groups.empty() && + (!had_results || snapshot.date != previous_result_date)) { + completed_results_ = ui::matchday_results_from_snapshot(snapshot, [&](int team) { + const size_t id = size_t(team & 0x0fff); + return id < names.size() ? names[id] : std::string(); + }, exe_, g_); + } + return result; +} + + +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; +} + +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); +} + +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; +} + +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) { + // Inventory of actual current consumers: direct match-engine buttons, + // matchday/season flags and the live-scene switch. Other cells are not + // made writable merely because the Original UI displayed a cell. + // Tie the write whitelist to the concrete consumer ranges. League + // remapping reads rows 0..4, columns 0..3; matchday display kinds 1/2 + // map to columns 0..2 and rows 0..4 or 17..19. + const bool consumed = (sound_cell && sound_capabilities_.has_value()) || + (request.row == 0 && request.column == 4) || // A5: match/Sportschau sound + ((request.row <= 4 && request.column <= 3) || + ((request.row <= 4 || request.row >= 17) && request.column <= 2)) || + ((request.row == 5 || (request.row >= 9 && request.row <= 12)) && request.column == 0) || + (request.row == 1 && request.column == 4) || // B5 live-scene option + (request.row == 2 && request.column == 4) || // C5: Reality player numbers (RealityMatch_FormatError_ExecutableField) + (request.row == 5 && request.column == 5) || // F6: Source manager-match desk gate (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField) + (request.row == 6 && request.column == 5) || // G6: transfer confirmation wait (OutcomeDelayDisabled) + (request.row == 16 && request.column == 6) || // Q7: own-club Sportschau preference (MatchdaySetup_ConsiderSportschauFixture_RuntimeField) + (request.row == 13 && request.column == 6) || // N7: Source kickoff competition list (SportschauAwards_MatchdayIntroView_RuntimeField) + (request.row == 1 && request.column == 6) || // B7: SportschauIntro intro gate (Controller_FormatError_RuntimeField) + (request.row == 2 && request.column == 6) || // C7: SportschauIntro intro-animation gate (Controller_FormatError_RuntimeField2) + (request.row == 3 && request.column == 6) || // D7: selected report progression (ReplayProgressionMode) + (request.row == 4 && request.column == 6) || // E7: Source-owned Sportschau scenes (ReplayChanceMode) + (request.row == 5 && request.column == 6) || // F7: SportschauIntro fixture-report gate (Controller_FormatError_RuntimeField3) + (request.row == 6 && request.column == 6) || // G7: MatchdayIntro player/award rating (SportschauAwards_FinishSportschauAwards_RuntimeField) + (request.row == 7 && request.column == 6) || // H7: SportschauTeamInfo competition totals (SportschauAwards_SportschauTeamInfoView_RuntimeField) + (request.row == 2 && request.column == 5) || // C6 drawer-handle behavior (CareerSession_DispatchDesktopLayout_RuntimeField) + (request.row == 3 && request.column == 5) || // D6 native desktop drag raster (CareerSession_DispatchDesktopLayout_RuntimeField2) + (request.row == 4 && request.column == 5) || // E6 always-visible shortcut bar (DeskState_FormatError_RuntimeField3) + (request.row == 7 && request.column == 5) || // H6 transfer option + (request.row == 8 && (request.column == 5 || request.column == 6)) || // I6/I7 + (request.row >= 10 && request.row <= 13 && request.column == 4) || // K5:N5 match buttons + (request.row >= 10 && request.row <= 12 && request.column == 6) || // K7:M7 presentation + (request.row == 9 && request.column == 6) || // J7 season-entrant visibility (SeasonEntrants_SeasonEntrantsFromGame_TextPointer) + (request.row == 15 && request.column == 4) || // P5 + (request.row == 16 && request.column == 4) || // Q5 + (request.row == 17 && request.column == 4); // R5: secondary leagues (CalendarState_FormatError_RuntimeField2) + if (!consumed || (old != 0 && old != 1)) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + if (request.row == 16 && request.column == 4 && + g_.season_day() >= 110 && g_.season_day() <= 230) { + error = ui::original_to_utf8(message_text(g_, ::bmh::layout::CareerSession_DispatchSettings_TextPointer)); + return false; + } + // SettingsSourceRefusal only permits re-enabling R5 while CareerSessionRuntimeField4 is zero. + // LeagueRoundCounters is the saved league_rounds block; CareerSessionRuntimeField4 is its sixth byte. + // Turning the leagues off remains possible after they have started. + if (request.row == 17 && request.column == 4 && old != 0 && + (g_.league_rounds.size() <= 5 || g_.league_rounds[5] != 0)) { + error = ui::original_to_utf8(message_text(g_, ::bmh::layout::CareerSession_DispatchSettings_TextPointer2)); + return false; + } + next = old ^ 1; + } else { + // Column8: existing presentation speeds B8:F8, H8 process budget, + // J8 postponed limit and K8 autosave. Column9 only exposes values + // already read by Main's Source live presenters or CupDrawScreen. + const bool consumed = (request.column == 7 && + ((request.row <= 6) || request.row == 7 || request.row == 9 || request.row == 10 || + (scoped_settings && request.row == 8))) || + // B9:C9 chance result; D9:E9 bookings; F9:G9 rolling ball; + // I9 cup draw; K9 Reality report; M9 preview/shootout; P9 shot. + (request.column == 8 && ((request.row >= 1 && request.row <= 6) || + request.row == 7 || request.row == 8 || request.row == 10 || request.row == 12 || request.row == 15)); + if (!consumed || old >= 200) { + error = "Diese Einstellung ist noch nicht verfügbar."; + return false; + } + if (request.column == 8) { + // SettingsSourceRefusal's ninth column is stored doubled for display. Its + // Source edit step is two raw units; decrement is enabled only + // above 1 and increment only below 0xc6 (198). Preserve odd raw + // values exactly, as the original does. + if (request.operation == ui::SettingsEdit::decrement) { + if (old <= 1) { error = "Der Zahlenwert ist bereits am Originalminimum."; return false; } + next = uint8_t(old - 2); + } else { + if (old >= 198) { error = "Der Zahlenwert ist bereits am Originalmaximum."; return false; } + next = uint8_t(old + 2); + } + } else if (request.column == 7) { + if (request.operation == ui::SettingsEdit::decrement) { + if (old == 0) { error = "Der Zahlenwert ist bereits am Originalminimum."; return false; } + next = uint8_t(old - 1); + } else { + const uint8_t limit = exe_.u8(::bmh::layout::CareerSession_DispatchSettings_RuntimeField + request.row); + if (old >= limit) { error = "Der Zahlenwert ist bereits am Originalmaximum."; return false; } + next = uint8_t(old + 1); + } + } + } + if (next == old) { error = "Die Einstellung hat sich nicht geändert."; return false; } + mem.set8(address, next); + ++revision; + return true; +} + +std::optional 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_; + 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(desk_settings_owner_->owner) : std::nullopt, + desk_settings_owner_ ? desk_settings_owner_->initial_h8 : uint8_t(0), + next_desk_settings_scope_,revision}; +} + +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; +} + +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; +} + +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; + } + 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 {}; + } +} + +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; +} + +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; +} + + + +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; +} + +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); +} + +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; +} + +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; + } +} + +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; + } +} + +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); +} + +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; }); +} + +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; +} + +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; } + 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; +} + +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; +} + +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; +} + +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; +} + +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; +} + +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; + const bool price = request.kind == ui::DeskRequestKind::change_ticket_price; + if (!price && request.kind != ui::DeskRequestKind::change_option) { + error = "unsupported_desk_widget"; return false; + } + // Keep SDL requests bound to a visible, open and enabled MEN drawer/item. + const auto desk = desktop_projection(revision); + const int expected_kind = price ? 55 : 64; + const auto item = std::find_if(desk.items.begin(), desk.items.end(), [&](const ui::DeskItem& item) { + return item.id == request.item_id && item.kind == expected_kind && item.open && !item.disabled; + }); + if (request.menu_kind != expected_kind || item == desk.items.end()) { + error = "stale_or_closed_desk_widget"; return false; + } + int value = request.value; + if (!price) { + if (request.value < 0 || request.value > 4) { error = "invalid_automation_index"; return false; } + const size_t at = size_t(active) * 5 + size_t(request.value); + if (request.value == 0) { + if (g_.manager_options[at] > 8) { error = "invalid_saved_formation_automation"; return false; } + value = g_.manager_options[at]; + const uint8_t mask = g_.manager_records[size_t(active) * 0xb0c + 0x218 + size_t(g_.indoor)]; + do { value = (value + 1) % 9; } while (value != 0 && !(mask & (1u << (value - 1)))); + } else value = (g_.manager_options[at] ^ 1) & 1; + } + if (!apply_desk_setting(active, price, request.value, value, error)) return false; + ++revision; + return true; +} + +bool 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; + } + switch(request.layout_operation) { + case ui::DeskLayoutOperation::move_item: { + if(request.layout_target_item!=-1 || expected[at+12]==72) { error="invalid_desk_layout_move_target"; return false; } + for(size_t i=0;imax_x || + moved_y<1 || moved_y>max_y || + (snap && ((source_x%5)!=0 && source_x!=max_x || (moved_y%5)!=0 && moved_y!=max_y))) { + error="desk_layout_move_outside_source_bounds"; return false; + } + write16(expected,at,moved_x); expected[at+2]=moved_y; + break; + } + case ui::DeskLayoutOperation::toggle_quickbar_drawer: { + const int id=request.item_id; + const int kind=expected[at+12]; + if(request.layout_target_item!=id || id<1 || id>=54 || kind<50 || kind>71 || + kind!=request.menu_kind || (request.value!=2 && request.value!=8)) { + error="invalid_desk_quickbar_drawer"; return false; + } + if(expected[at+5]==0xff) { + int tail=0; + size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain"; return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0 || tail>=int(kItems)) { error="invalid_desk_layout_links"; return false; } + } + expected[at+5]=0; expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(id); + const bool opened=!(request.value==8 && id>2); + expected[at+13]=uint8_t((expected[at+13]&0x7f)|(opened?0x80:0)); + } else { + const uint8_t previous=expected[at+6],next=expected[at+5]; + if(previous>=kItems || (next!=0 && next>=kItems)) { error="invalid_desk_layout_links"; return false; } + expected[size_t(previous)*kStride+5]=next; + if(next!=0) expected[size_t(next)*kStride+6]=previous; + expected[at+5]=expected[at+6]=0xff; + } + break; + } + case ui::DeskLayoutOperation::return_folder_child: { + const int folder=request.layout_target_item; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]!=0xff||expected[at+6]!=0xff||(expected[at+1]&0x10)!=0|| + (expected[at+13]&0x7f)!=folder||expected[at+12]>=50) { + error="invalid_desk_folder_child_return"; return false; + } + bool owner_open=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_open) break; + } + if(!owner_open) { error="desk_folder_child_owner_closed"; return false; } + const int max_x=std::max(1,319-int(expected[at+3])),max_y=std::max(1,239-int(expected[at+4])); + const int source_x=int(moved_x&0xefff); + const bool snap=g_.memory.has(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField2)&&g_.memory.u8(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField2)==0; + if((moved_x&0x1000)!=(read16(expected,at)&0x1000)||source_x<1||source_x>max_x||moved_y<1||moved_y>max_y|| + (snap&&(((source_x%5)!=0&&source_x!=max_x)||((moved_y%5)!=0&&moved_y!=max_y)))) { + error="desk_folder_child_return_outside_source_bounds";return false; + } + int tail=0;size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain";return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0||tail>=int(kItems)) { error="invalid_desk_layout_links";return false; } + } + expected[at]=request.layout_after[at];expected[at+1]=request.layout_after[at+1];expected[at+2]=moved_y; + expected[at+5]=0;expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(request.item_id); + break; + } + case ui::DeskLayoutOperation::send_to_folder: { + const int folder=request.layout_target_item; + const uint8_t previous=expected[at+6],next=expected[at+5]; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]==0xff||expected[at+12]>=50||expected[at+12]==12|| + (expected[at+13]&0x7f)!=folder||previous>=kItems||(next!=0&&next>=kItems)|| + expected[size_t(previous)*kStride+5]!=request.item_id|| + (next!=0&&expected[size_t(next)*kStride+6]!=request.item_id)) { + error="invalid_desk_bin_send";return false; + } + expected[size_t(previous)*kStride+5]=next; + if(next!=0)expected[size_t(next)*kStride+6]=previous; + expected[at+5]=expected[at+6]=0xff; + break; + } + case ui::DeskLayoutOperation::restore_folder_child: { + const int folder=request.layout_target_item; + if(request.item_id<1||request.item_id>30||folder<0||folder>=3|| + expected[at+5]!=0xff||expected[at+6]!=0xff||(expected[at+1]&0x10)!=0|| + (expected[at+13]&0x7f)!=folder||expected[at+12]>=50) { + error="invalid_desk_bin_restore";return false; + } + bool owner_open=false; + for(size_t item=1;item=int(kItems)) break; + cursor=next; + } + if(owner_open)break; + } + if(!owner_open) { error="desk_bin_restore_folder_closed";return false; } + int tail=0;size_t guard=0; + while(expected[size_t(tail)*kStride+5]!=0) { + if(++guard>=kItems) { error="invalid_desk_layout_chain";return false; } + tail=expected[size_t(tail)*kStride+5]; + if(tail<0||tail>=int(kItems)) { error="invalid_desk_layout_links";return false; } + } + expected[at+5]=0;expected[at+6]=uint8_t(tail); + expected[size_t(tail)*kStride+5]=uint8_t(request.item_id); + break; + } + case ui::DeskLayoutOperation::set_folder: { + const int target=request.layout_target_item; + const int kind=expected[at+12]; + if(kind>=50 || request.item_id>30 || (expected[at+1]&0x10)!=0 || target<1 || target>=int(kItems) || expected[size_t(target)*kStride+12]<50 || + expected[size_t(target)*kStride+12]>52) { error="invalid_desk_folder_drop"; return false; } + const size_t target_at=size_t(target)*kStride; + const uint8_t folder=uint8_t(expected[target_at+12]-50); + int folder_count=0; + for(int child=1;child<=30;++child) { + const size_t child_at=size_t(child)*kStride; + if(expected[child_at+5]==0xff && (expected[child_at+1]&0x10)==0 && + (expected[child_at+13]&0x7f)==folder) ++folder_count; + } + const bool already_in_folder=expected[at+5]==0xff&&(expected[at+13]&0x7f)==folder; + if(folder_count-(already_in_folder?1:0)>=12) { error="desk_folder_source_capacity"; return false; } + const int previous=expected[at+6], next=expected[at+5]; + if((previous!=0xff && previous>=int(kItems)) || (next!=0xff && next>=kItems)) { error="invalid_desk_layout_links"; return false; } + if(previous!=0xff) expected[size_t(previous)*kStride+5]=uint8_t(next); + if(next>0 && next<0xff) expected[size_t(next)*kStride+6]=uint8_t(previous); + expected[at+13]=uint8_t((expected[at+13]&0x80)|folder); + expected[at+5]=expected[at+6]=0xff; + write16(expected,at,moved_x); expected[at+2]=moved_y; + break; + } + case ui::DeskLayoutOperation::none: + error="unsupported_desk_layout_operation"; return false; + } + if(expected!=request.layout_after) { error="desk_layout_after_state_not_source_derived"; return false; } + 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; +} + +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; + } + if (request.kind != ui::LineupRequestKind::swap_players || + lineup_entry_manager_ != active || lineup_entry_club_ != request.runtime_club || + request.first_row < 0 || request.second_row < 0 || request.first_row == request.second_row || + size_t(request.first_row) >= range.count || size_t(request.second_row) >= range.count) { + error = "Der Spielerwechsel ist nicht freigegeben."; + return false; + } + const size_t first = range.first + size_t(request.first_row); + const size_t second = range.first + size_t(request.second_row); + const uint16_t first_slot = g_.squad_slots.at(first), second_slot = g_.squad_slots.at(second); + const int first_id = (first_slot & 0x0fff) == 0x0fff ? -1 : first_slot & 0x0fff; + const int second_id = (second_slot & 0x0fff) == 0x0fff ? -1 : second_slot & 0x0fff; + if (first_slot != request.first_slot || second_slot != request.second_slot || + first_id != request.first_player || second_id != request.second_player || + first_id < 0 || second_id < 0 || size_t(first_id) >= g_.players.size() || size_t(second_id) >= g_.players.size()) { + error = "Die Kaderzeilen wurden inzwischen geändert."; + return false; + } + // SizeT3 requires injury/foreign-rule confirmations for special + // swaps. Until those dialogs exist, reject that path before any writes. + if (((g_.players[size_t(first_id)].w364 >> 16) & 0x1f) != 0 || + ((g_.players[size_t(second_id)].w364 >> 16) & 0x1f) != 0) { + error = "Ein verletzter Spieler kann hier noch nicht eingewechselt werden."; + return false; + } + if ((request.first_row < 11) != (request.second_row < 11) && exe_.u8(::bmh::layout::ForeignPlayerLimitEnabled) != 0) { + error = "Dieser Wechsel benötigt eine Bestätigung der Ausländerregel."; + return false; + } + const size_t board_base = size_t(active) * 0x840; + auto* a = g_.tactics.data() + board_base + size_t(request.first_row) * 0x58; + auto* b = g_.tactics.data() + board_base + size_t(request.second_row) * 0x58; + const uint8_t ax = a[0x41], ay = a[0x42], bx = b[0x41], by = b[0x42]; + // Original SquadSlotsBoardEntriesChangePlaces moves the player/tactics entry, then restores + // the 0xc000 role bits to their roster rows. Preserve bit 12 and the + // player id with the entry; keep the starter/bench flags with the slot. + g_.squad_slots[first] = uint16_t((second_slot & 0x1fff) | (first_slot & 0xc000)); + g_.squad_slots[second] = uint16_t((first_slot & 0x1fff) | (second_slot & 0xc000)); + std::swap_ranges(a, a + 0x58, b); + a[0x41] = ax; a[0x42] = ay; b[0x41] = bx; b[0x42] = by; + // GatedByParamLive is applied to every marked row, not just the two swapped + // players. Keep card-side row identity synchronized with the roster. + for (size_t row = 0; row < range.count; ++row) { + const uint16_t slot = g_.squad_slots[range.first + row]; + if ((slot & 0xc000) == 0) continue; + const size_t id = slot & 0x0fff; + if (id >= g_.players.size()) continue; + g_.player_cards[id] = uint16_t((g_.player_cards[id] & 0xffe0) | uint16_t(row)); + } + g_.manager_options.at(size_t(active) * 5) = 0; // source manual mode selects DispatchLiveOverview + ++revision; + return true; +} + +std::optional 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_; + 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; + struct RestoreObserverScope { bool& flag; bool previous; explicit RestoreObserverScope(bool& f):flag(f),previous(f){flag=true;} ~RestoreObserverScope(){flag=previous;} } observer_scope(calendar_advance_active_); + return dispatch_live_overview(LiveOverviewAction{navigation},engine,revision,error,team_info); + } + if(strengths->kind==ui::StrengthsAction::close) { + ui::LeagueFamilyRequest close;close.identity=live.family_identity; + close.kind=ui::LeagueFamilyRequestKind::close;close.from_child=3;close.target_child=0; + auto preparation=close_league_family(close,revision,error); + if(!preparation)throw FormatError(error.empty()?"live overview: Source Strengths close rejected":error); + result.closed=true;result.preparation=std::move(*preparation);live_overview_owner_.reset();return result; + } + const auto prior=live.family_identity; + auto page=dispatch_strengths(*strengths,revision,error,team_info,false); + if(!page || page->closed)throw FormatError(error.empty()?"live overview: Source Strengths action rejected":error); + if(!refresh_family_after_child(prior,3,page->page.identity,revision,error)) + throw FormatError(error.empty()?"live overview: Source Strengths ACK rejected":error); + result.strengths=page->page;result.preparation=page->preparation; + result.family_identity=page->page.identity; + live_overview_owner_->family_identity=result.family_identity; + live_overview_owner_->request.revision=revision; + return result; + } + if(const auto* pairings=std::get_if(&action)) { + if(live.kind!=LiveOverviewKind::league_pairings || !league_pairings_draft_ || + pairings->identity!=league_pairings_draft_->identity || pairings->identity.revision!=revision) + throw FormatError("live overview: mismatched Source Pairings owner"); + if(pairings->event.kind==LeaguePairingsAction::close) { + ui::LeagueFamilyRequest close;close.identity=live.family_identity; + close.kind=ui::LeagueFamilyRequestKind::close;close.from_child=2;close.target_child=0; + auto preparation=close_league_family(close,revision,error); + if(!preparation)throw FormatError(error.empty()?"live overview: Source Pairings close rejected":error); + result.closed=true;result.preparation=std::move(*preparation);live_overview_owner_.reset();return result; + } + auto page=dispatch_league_pairings(*pairings,revision,error,team_info); + if(!page)throw FormatError(error.empty()?"live overview: Source Pairings action rejected":error); + result.closed=page->closed;result.pairings=page->page;result.preparation=page->preparation; + if(result.closed) { + // The Source Move return is completed by the outer G/T wrapper. + live_overview_owner_.reset();league_family_owner_.reset(); + } else { + live_overview_owner_->request.revision=revision; + if(league_family_owner_) { + live_overview_owner_->family_identity=league_family_owner_->identity; + result.family_identity=league_family_owner_->identity; + } + } + return result; + } + const auto* cup=std::get_if(&action); + if(!cup || live.kind!=LiveOverviewKind::cup_other_games || !other_games_owner_ || + cup->identity!=other_games_owner_->page.identity || cup->identity.revision!=revision) + throw FormatError("live overview: mismatched Source cup overview owner"); + auto page=dispatch_other_games(*cup,revision,error,team_info); + if(!page)throw FormatError(error.empty()?"live overview: Source cup overview action rejected":error); + result.closed=page->closed;result.cup=page->page;result.preparation=page->preparation; + if(result.closed)live_overview_owner_.reset(); + else live_overview_owner_->request.revision=revision; + return result; + } catch(const std::exception& e) { + error=e.what();return {}; + } +} + +bool 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; +} + +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; +} + +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; +} + +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; +} + +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(); +} + +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; +} + +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)}; +} + +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; +} + +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. + const bool live_context = live_intervention_ && live_intervention_->source_mode == 2 && + request.manager_slot == live_intervention_->manager && + request.runtime_club == live_intervention_->team && + request.revision == live_intervention_->current_revision && request.revision == revision; + const bool desk_phase = turn_driver_.stage == TurnDriver::Stage::MatchdayDesks || + turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk; + const bool initial_lineup_phase = turn_driver_.stage == TurnDriver::Stage::Empty && + lineup_entry_manager_ == request.manager_slot && lineup_entry_club_ == request.runtime_club; + if (!desk_phase && !initial_lineup_phase && !live_context) { error = "desk_setting_unavailable"; return false; } + if (!live_context && (pending_offer_dispatch_active_ || market_dispatch_active_ || calendar_advance_active_ || + transfer_offer_editor_ || manager_join_ || contract_quote_ || stadium_.investment || + stadium_.tip || stadium_.periphery_quote)) { + error = "desk_setting_unavailable"; return false; + } + if (live_context) { + const int manager = live_intervention_->manager; + const int team = live_intervention_->team; + const size_t rec = size_t(manager) * 0xb0c; + if (request.indoor != g_.indoor || manager < 0 || manager >= int(g_.manager_teams.size()) || + g_.manager_teams[size_t(manager)] != team || g_.manager_of(team) != manager || + size_t(team) >= g_.club_ids.size() || rec + 0xb0c > g_.manager_records.size() || + (int(g_.manager_records[rec + 0x290]) | int(g_.manager_records[rec + 0x291]) << 8) != team) { + error = "Die Spielfeldaktion gehört nicht zum aktiven Live-Manager."; return false; + } + } else if (!validate_desk_setting_owner(identity, revision, error, false)) return false; + const size_t badge = size_t(request.runtime_club) * 2; + const int mode = g_.memory.has(::bmh::layout::GameMode) ? int(g_.memory.u8(::bmh::layout::GameMode)) : int(exe_.u8(::bmh::layout::GameMode)); + if (request.runtime_club >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) || g_.lineups_frozen || + mode < 1 || mode > 3 || g_.manager_options[size_t(request.manager_slot) * 5] > 8 || + request.indoor != g_.indoor || + (!live_context && (lineup_entry_manager_ != request.manager_slot || + lineup_entry_club_ != request.runtime_club)) || badge + 1 >= g_.club_heap_78.size()) { + error = "Diese Spielfeldaktion ist nicht für die vorbereitete Aufstellung freigegeben."; + return false; + } + if ((request.kind == ui::PitchRequestKind::apply_formation || + request.kind == ui::PitchRequestKind::save_formation) && request.new_weights != request.old_weights) { + error = "Die Gewichtung der Aufstellungsanfrage wurde geändert."; + return false; + } + const auto selected_live_opponent = [&](int opponent) { + if (!live_context || opponent < 0 || opponent >= int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField))) return false; + return std::any_of(live_intervention_->groups.begin(), live_intervention_->groups.end(), + [&](const MatchGroup& group) { + for (int match = 0; match < group.matches(); ++match) { + const uint32_t bit = uint32_t(1) << match; + if ((group.kickoff_void_mask & bit) || (group.void_mask() & bit)) continue; + const int home = group.fixtures.at(size_t(match) * 2); + const int away = group.fixtures.at(size_t(match) * 2 + 1); + if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) != g_.live_matches.end() && + ((home == request.runtime_club && away == opponent) || + (away == request.runtime_club && home == opponent))) return true; + } + return false; + }); + }; + const auto selected_source_opponent = [&](int opponent) { + if (live_context) return selected_live_opponent(opponent); + const auto prepared = prepared_lineup_opponent(request.manager_slot, + request.runtime_club, request.revision); + return prepared && *prepared == opponent; + }; + if (request.kind == ui::PitchRequestKind::select_pitch_page && request.page_control == 4 && + (request.indoor || g_.indoor || !selected_source_opponent(request.opponent_team))) { + error = "Die Manndeckungsseite ist für diese Partie nicht verfügbar."; + return false; + } + if (request.kind == ui::PitchRequestKind::set_player_marking && + (request.indoor || g_.indoor || !selected_source_opponent(request.opponent_team))) { + error = "Die Manndeckung gehört nicht zur aktuellen Außenspielpartie."; + return false; + } + try { + 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; +} + +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); +} + +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)}; +} + +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); +} + +ui::PreparationState CareerSession::preparation_projection(uint64_t revision) const { + return preparation_projection(g_, revision); +} + +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) * 0x17c + size_t(round) * 10 + size_t(match); + if (round >= 0 && result_at < g_.results.size()) { + has_result = true; + raw_result = g_.results[result_at]; + } + } + if (has_result && raw_result != 0xcc) valid = false; + } + // MatchdayNeedsManagerDesks overwrites the per-manager callargs in group order. + // The last matching pair therefore decides whether this exact + // callarg is still a supported, unplayed fixture. + current_pair = valid; + } + } + return current_pair ? std::optional(opponent) : std::nullopt; +} + +ui::PreparationState 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; +} + +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; + } +} + +void CareerSession::capture_source_desk_callargs() { + source_desk_callargs_.clear(); + const auto stage = turn_driver_.stage; + if (stage != TurnDriver::Stage::MatchdayDesks && + stage != TurnDriver::Stage::SeasonEndDesk) + return; + uint32_t competitions = 0; + int default_competition = 32; + const std::vector* groups = nullptr; + if (stage == TurnDriver::Stage::MatchdayDesks) { + competitions = day_competitions(g_, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + default_competition = competitions != 0 ? 34 : 33; + groups = &turn_driver_.groups; + } + // DayCompetitions2 initializes the full four-slot callarg arrays before joining + // any manager desk: FF opponents, competition 33/34 (or 32 at season end). + source_desk_callargs_.assign(4, ui::DeskMatchCallargs{default_competition, -1}); + for (size_t slot = 0; slot < g_.manager_teams.size(); ++slot) { + if (slot >= source_desk_callargs_.size()) + throw FormatError("desk: too many manager slots while capturing Source callargs"); + if (!groups) continue; + GameState manager_view = g_; + if (!manager_view.memory.has(::bmh::layout::ActiveManager)) + throw FormatError("desk: active manager field is missing while capturing Source callargs"); + manager_view.memory.set8(::bmh::layout::ActiveManager, uint8_t(slot)); + const ui::DeskState source = ui::desk_from_game( + manager_view, exe_, turn_driver_.revision, groups, default_competition); + source_desk_callargs_[slot] = {source.next_competition.value_or(default_competition), + source.next_opponent.value_or(-1)}; + } +} + +ui::DeskState CareerSession::desktop_projection(uint64_t revision) const { + return desktop_projection(g_, revision); +} + +ui::DeskState CareerSession::desktop_projection(const GameState& state, uint64_t revision) const { + std::optional source_default; + if (turn_driver_.stage == TurnDriver::Stage::SeasonEndDesk) { + source_default = 32; + } else if (turn_driver_.stage == TurnDriver::Stage::MatchdayDesks) { + uint32_t competitions = day_competitions(state, turn_driver_.calendar_entry); + if (competitions == 0x800000) competitions = 0; + source_default = competitions != 0 ? 34 : 33; + } else { + // An unsupported/empty saved cursor is not evidence that the Source + // dispatcher produced its no-fixture default. Keep those fields unknown. + return ui::desk_from_game(state, exe_, revision); + } + const int slot = int(state.memory.u8(::bmh::layout::ActiveManager)); + const ui::DeskMatchCallargs defaults{source_default.value_or(34), -1}; + const ui::DeskMatchCallargs* callargs = &defaults; + if (slot >= 0 && size_t(slot) < source_desk_callargs_.size()) + callargs = &source_desk_callargs_[size_t(slot)]; + return ui::desk_from_game(state, exe_, revision, &turn_driver_.groups, source_default, callargs); +} + +void CareerSession::configure_autosave_directory(const std::filesystem::path& directory) { + if (autosave_directory_ && *autosave_directory_ == directory) return; + if (calendar_advance_active_) throw FormatError("autosave directory change during active turn"); + autosave_directory_ = directory; + turn_driver_.desk_autosave = [this](const GameState& state, WatcomRandom& random) { + write_desk_autosave(state, random); + }; +} + +std::string CareerSession::take_autosave_error() { + return std::exchange(autosave_error_, {}); +} + +void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& random) { + std::filesystem::path temporary; + try { + if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_)) + throw FormatError("autosave directory unavailable"); + // CareerSession_Name_TextPointer is the Original TEXTD filename, not the manual browser name. + const std::filesystem::path name(texts_.strings.at((::bmh::layout::CareerSession_Name_TextPointer - ::bmh::layout::TextPointerTable) / 4)); + if (name.empty() || name != name.filename() || name.extension() != ".FBM") + throw FormatError("invalid Original autosave filename"); + const auto target = *autosave_directory_ / name; + if (std::filesystem::is_symlink(std::filesystem::symlink_status(target)) || + std::filesystem::is_directory(target)) throw FormatError("autosave target unavailable"); + WatcomRandom staged = random; + const auto saved = make_savegame(state, staged); + temporary = target; + temporary += ".tmp-" + std::to_string(saved.id2); + if (std::filesystem::exists(std::filesystem::symlink_status(temporary))) { + temporary.clear(); + throw FormatError("autosave temporary target already exists"); + } + write_savegame(temporary, saved); + if (std::filesystem::is_symlink(std::filesystem::symlink_status(target)) || + std::filesystem::is_directory(target)) throw FormatError("autosave target changed"); + std::filesystem::rename(temporary, target); + temporary.clear(); + random = staged; + } catch (const std::exception& e) { + autosave_error_ = e.what(); + if (!temporary.empty()) { + std::error_code ignored; + std::filesystem::remove(temporary, ignored); + } + } +} + +bool CareerSession::save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error) { + if (advertising_renewal_dispatch_active_) { error="save_blocked_during_advertising_renewal"; return false; } + if(balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_|| + top_scorers_owner_||top_scorers_dispatch_active_ || stadium_.block_expansion||other_games_owner_||other_games_dispatch_active_){error="strengths_active";return false;} + if(balance_draft_||balance_dispatch_active_||league_pairings_draft_||league_pairings_dispatch_active_){error="league_pairings_active";return false;} + if (transfer_offer_editor_) { error = "transfer_offer_editor_active"; return false; } + if (pending_offer_dispatch_active_) { error = "pending_offer_decision_active"; return false; } + if (market_dispatch_active_) { error = "transfer_market_decision_active"; return false; } + if (career_complete()) { error = "career_complete"; return false; } + const int active = int(g_.memory.u8(::bmh::layout::ActiveManager)); + std::string extension = path.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + if (manager_slot != active || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() || + extension != ".fbm" || path.filename().empty()) { + error = "invalid_save_request"; return false; + } + std::error_code ec; + if (!std::filesystem::is_directory(path.parent_path(), ec) || ec) { + error = "save_directory_unavailable"; return false; + } + const auto status = std::filesystem::symlink_status(path, ec); + if (!ec && std::filesystem::is_symlink(status)) { error = "save_target_is_symlink"; return false; } + ec.clear(); + const bool exists = std::filesystem::exists(path, ec); + if (ec || (exists && !overwrite)) { error = exists ? "overwrite_confirmation_required" : "save_target_unavailable"; return false; } + try { + WatcomRandom staged_rand = rand_; + const Savegame save = make_savegame(g_, staged_rand); + write_savegame(path, save); + rand_ = staged_rand; + return true; + } catch (const std::exception&) { + error = "save_write_failed"; return false; + } +} + +bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uint64_t& revision, + std::string& error) { + constexpr uint32_t kLayouts = ::bmh::layout::Desktops; + constexpr size_t kLayoutBytes = 0x360; + constexpr int kDeskItemCount = 54; + if (request.file_kind != ui::SaveLoadFileKind::menu_layout || + request.origin_item_id < 0 || request.origin_item_id >= kDeskItemCount) { + error = "invalid_menu_layout_origin"; return false; + } + if (request.revision != revision || revision == UINT64_MAX || request.path.filename().empty() || + request.manager_slot < 0 || request.manager_slot > 3 || + !g_.memory.has(::bmh::layout::ActiveManager) || int(g_.memory.u8(::bmh::layout::ActiveManager)) != request.manager_slot) { + error = "stale_menu_layout_owner"; return false; + } + if (calendar_advance_active_ || live_intervention_ || career_complete() || + (turn_driver_.stage != TurnDriver::Stage::Empty && + turn_driver_.stage != TurnDriver::Stage::MatchdayDesks && + turn_driver_.stage != TurnDriver::Stage::SeasonEndDesk) || + pending_offer_dispatch_active_ || market_dispatch_active_ || transfer_offer_editor_ || + manager_join_ || contract_quote_ || advertising_renewal_dispatch_active_ || + balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ || + top_scorers_owner_ || top_scorers_dispatch_active_ || opportunities_owner_ || + opportunities_dispatch_active_ || league_pairings_draft_ || league_pairings_dispatch_active_ || + league_family_owner_ || league_family_teaminfo_active_ || other_games_owner_ || + other_games_dispatch_active_ || stadium_.block_expansion || stadium_.investment || + stadium_.tip || stadium_.periphery_quote) { + error = "menu_layout_unavailable_during_active_flow"; return false; + } + std::string extension = request.path.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), + [](unsigned char c) { return char(std::tolower(c)); }); + if (extension != ".men") { error = "invalid_menu_layout_extension"; return false; } + const size_t active_base = size_t(request.manager_slot) * 0xb0c; + if (active_base + 0xb0c > g_.manager_records.size() || + size_t(request.manager_slot) >= g_.manager_teams.size() || + (int(g_.manager_records[active_base + 0x290]) | + int(g_.manager_records[active_base + 0x291]) << 8) != g_.manager_teams[size_t(request.manager_slot)]) { + error = "menu_layout_manager_record_mismatch"; return false; + } + if (!g_.memory.has(kLayouts + uint32_t(request.manager_slot) * uint32_t(kLayoutBytes) + + uint32_t(kLayoutBytes - 1))) { + error = "menu_layout_memory_unavailable"; return false; + } + // CopyN returns the matching record index. In the native MEN file, + // the final bar cell (source value 72) resolves to record 53; DeskDate + // dispatches that index to the menu-layout chooser. + const uint32_t base = kLayouts + uint32_t(request.manager_slot) * uint32_t(kLayoutBytes); + const int source_item = g_.memory.u8(base + 53u * 16u + 12u) == 72 ? 53 : -1; + if (source_item != request.origin_item_id) { error = "menu_layout_source_handle_unavailable"; return false; } + + const auto validate_payload = [&](const Bytes& bytes) -> bool { + if (bytes.size() != kLayoutBytes) { error = "menu_layout_wrong_size"; return false; } + // Bound the forward traversal before asking the desk projector to + // validate geometry, kinds, and remaining source fields. Native layouts + // may contain valid custom back-links; Source load does not normalize them. + std::array seen{}; + const int head = bytes[5]; + // CopyN permits an empty linked drawer (head == 0). + if (head == 0) return true; + if (head < 1 || head >= kDeskItemCount) { error = "menu_layout_invalid_head"; return false; } + int item = head; + for (int steps = 0; steps < kDeskItemCount; ++steps) { + if (item <= 0 || item >= kDeskItemCount || seen[size_t(item)]) { + error = "menu_layout_invalid_chain"; return false; + } + seen[size_t(item)] = true; + const size_t at = size_t(item) * 16; + item = bytes[at + 5]; + if (item == 0) return true; + if (item == 0xff) { error = "menu_layout_invalid_chain_terminator"; return false; } + } + error = "menu_layout_chain_cycle"; return false; + }; + + if (request.action == ui::SaveLoadAction::load) { + Bytes payload; + try { payload = read_file(request.path); } + catch (const std::exception&) { error = "menu_layout_read_failed"; return false; } + if (!validate_payload(payload)) return false; + GameState staged = g_; + for (size_t i = 0; i < kLayoutBytes; ++i) + staged.memory.set8(base + uint32_t(i), payload[i]); + try { + (void)desktop_projection(staged, revision + 1); + } catch (const std::exception&) { error = "menu_layout_projection_invalid"; return false; } + g_ = std::move(staged); + ++revision; + error.clear(); + return true; + } + if (request.action != ui::SaveLoadAction::save) { + error = "invalid_menu_layout_action"; + return false; + } + + std::error_code ec; + if (!std::filesystem::is_directory(request.path.parent_path(), ec) || ec) { + error = "menu_layout_directory_unavailable"; return false; + } + ec.clear(); + const auto status = std::filesystem::symlink_status(request.path, ec); + if (!ec && std::filesystem::is_symlink(status)) { error = "menu_layout_target_is_symlink"; return false; } + ec.clear(); + const bool exists = std::filesystem::exists(request.path, ec); + if (ec || (exists && !request.overwrite)) { + error = exists ? "menu_layout_overwrite_confirmation_required" : "menu_layout_target_unavailable"; + return false; + } + Bytes payload(kLayoutBytes); + for (size_t i = 0; i < kLayoutBytes; ++i) payload[i] = g_.memory.u8(base + uint32_t(i)); + if (!validate_payload(payload)) return false; + try { + std::ofstream file(request.path, std::ios::binary | std::ios::trunc); + if (!file) { error = "menu_layout_write_failed"; return false; } + file.write(reinterpret_cast(payload.data()), std::streamsize(payload.size())); + file.flush(); + if (!file) { error = "menu_layout_write_failed"; return false; } + } catch (const std::exception&) { error = "menu_layout_write_failed"; return false; } + ++revision; + error.clear(); + return true; +} + +bool 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; +} + +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; +} + +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; +} + +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 { + 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"); + StadiumBlockExpansionConstants block_constants; + for (unsigned i = 0; i < 8; ++i) { + block_constants.price_per_1000[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + (i + 8) * 4); + block_constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (i + 22) * 5); + block_constants.max_places[i] = uint32_t(exe_.u8(::bmh::layout::CareerSession_Invalid_RuntimeField + i)) * 1000; + } + const auto quote_block = [&](StadiumBlockSlot slot, uint32_t total, uint8_t features) { + return 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; + } +} + +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 { + +PendingOfferHooks CareerSession::pending_hooks_for_dispatch(PendingOfferHooks hooks) const { + // Presenters own answers and notice delivery, never allocator provenance. + hooks.human_buyer_allocator_gate = turn_driver_.transfer_allocator_context; + return hooks; +} + +void CareerSession::install_default_hooks() { + // InstallDefaultHooks pauses at the Original contracts screen when a term expires. + // Never synthesize a two-year renewal here: callers must install the real + // interactive ContractExpiryPresenter or month_change stops without a decision. + g_.contract_screen = {}; + g_.loan_return_screen = {}; + g_.loan_return_offer_screen = {}; +} + +void CareerSession::set_contract_expiry_presenter(ContractExpiryPresenter presenter) { + // Clear any previously installed presenter before replacing it. The only + // fallback is an explicit unsupported expiry, never a synthesized decision. + auto loan_return_hook = std::move(g_.loan_return_screen); + auto loan_offer_hook = std::move(g_.loan_return_offer_screen); + install_default_hooks(); + g_.loan_return_screen = std::move(loan_return_hook); + g_.loan_return_offer_screen = std::move(loan_offer_hook); + contract_expiry_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.contract_screen = [this, presenter = std::move(presenter)](GameState& g, int manager, int row) { + return presenter(g, rand_, manager, row); + }; +} + +void CareerSession::set_loan_return_presenter(LoanReturnPresenter presenter) { + auto contract_hook = std::move(g_.contract_screen); + auto loan_offer_hook = std::move(g_.loan_return_offer_screen); + install_default_hooks(); + g_.contract_screen = std::move(contract_hook); + g_.loan_return_offer_screen = std::move(loan_offer_hook); + loan_return_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.loan_return_screen = [this, presenter = std::move(presenter)]( + GameState& g, int manager, const std::string& question) { + return presenter(g, rand_, manager, question); + }; +} + +void CareerSession::set_loan_return_offer_presenter(LoanReturnOfferPresenter presenter, + HumanBuyerSaleHooks sale_hooks) { + auto contract_hook = std::move(g_.contract_screen); + auto loan_question_hook = std::move(g_.loan_return_screen); + install_default_hooks(); + g_.contract_screen = std::move(contract_hook); + g_.loan_return_screen = std::move(loan_question_hook); + loan_return_offer_presenter_installed_ = bool(presenter); + if (!presenter) return; + g_.loan_return_offer_screen = [this, presenter = std::move(presenter), + sale_hooks = std::move(sale_hooks)]( + GameState& g, GameRandom& game, WatcomRandom& rand, int manager, + int source_slot, int list_entry, const HumanBuyerSaleHooks&) mutable { + auto staged_runtime = club_modal_runtime_; + auto services = staged_club_modal_services(g, game, rand, staged_runtime); + auto hooks = sale_hooks; + switch (turn_driver_.transfer_allocator_context) { + case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + const int result = presenter(g, game, rand, services, manager, source_slot, list_entry, hooks); + if (result >= 0) club_modal_runtime_ = std::move(staged_runtime); + return result; + }; +} + +} // namespace bmh::app diff --git a/src/app/career_session.hpp b/src/app/career_session.hpp new file mode 100644 index 0000000..110b27d --- /dev/null +++ b/src/app/career_session.hpp @@ -0,0 +1,1085 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md). +// +// The original starts a career at program start (game/career.hpp): the data files are +// loaded, every player gets new values and InitializeCareer runs up to the options dialog. +// The UI then shows the options and one dialog per manager; after each confirmed +// manager ConfirmManager sets him up, which may move clubs to other places - the UI gets +// the new club order (SelectionContext) for the next dialog. After the last manager the +// first season is prepared and the desk shown. +// +// CareerSession owns the engine state of that sequence. It never draws numbers for +// rendering; every random draw belongs to one of the steps above. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/m3d.hpp" +#include "formats/textd.hpp" +#include "game/random.hpp" +#include "game/desk_actions.hpp" +#include "game/stadium_blocks.hpp" +#include "game/state.hpp" +#include "game/turn_driver.hpp" +#include "game/club_info.hpp" +#include "game/club_player_detail.hpp" +#include "game/pending_offer.hpp" +#include "game/poach.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/weekly.hpp" +#include "ui/flow.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" +#include "ui/league_table_range_dialog.hpp" +#include "ui/league_pairings.hpp" +#include "ui/balance_plan.hpp" +#include "ui/top_scorers_state.hpp" +#include "ui/tactics.hpp" +#include "ui/opportunities.hpp" +#include "ui/other_games_state.hpp" + +namespace bmh::app { + +ui::OutgoingTransferEditorState loan_return_offer_editor_projection( + const GameState&, const TransferOfferEditorState&, uint64_t revision, bool gradient); + +// KB6 commits retain their concrete field even though they also refresh the quote. +TransferOfferEditorState edit_transfer_offer_from_ui(GameState&, const TransferOfferEditorState&, + const ui::OutgoingTransferRequest&, GameRandom&, WatcomRandom&); + +// The original interactive post-desk path needs its own answer producer. +// Existing headless callers retain their prior unpresented driver contract. +enum class PendingOfferEntryPolicy { legacy_unpresented, normal_interactive }; + +// Source SubmitTransferBidSourceHumanBuyer direct purchases have a separate owner and cleanup contract +// from both special pending offers and automatic weekly auctions. +enum class HumanBuyerMarketEntryPolicy { legacy_unpresented, normal_interactive }; + +enum class LiveSubstitutionStatus { rejected, applied, source_notice }; +struct LiveSubstitutionResult { + LiveSubstitutionStatus status = LiveSubstitutionStatus::rejected; + uint32_t source_text_address = 0; + int manager_slot = -1; + std::string error; +}; + +// Synchronous capability facade shared by live club modals and a staged KB31 +// TeamInfo transaction. It exposes no calendar/save/outer revision operations. +struct ClubModalServices { + bool transactional = true; + std::function state; + std::function enter_club; + std::function change_category; + std::function redraw_player; + std::function national_action; + std::function pending_offers; + std::function runtime_byte; + std::function set_runtime_byte; +}; +using TransferOfferTeamInfoPresenter = std::function; +using TransferOfferPlayerInfoPresenter = std::function; + +// Semantic desk settings for frontends without MEN drawer/layout controls. +struct DeskSettingIdentity { + int manager_slot = -1, runtime_club = -1; + std::optional stable_club_identity; + uint64_t revision = 0; +}; +struct TicketPriceRequest { + DeskSettingIdentity identity; + int price = 0; // Original admission range8..25. +}; +enum class DeskAutomation { Formation, Substitution, Tactics, Marking, Training }; +struct AutomationRequest { + DeskSettingIdentity identity; + DeskAutomation automation = DeskAutomation::Substitution; + bool enabled = false; + // Formation on selects an explicit available saved slot1..8; off has no slot. + // Other automation settings must omit this field. + std::optional formation; +}; + +class CareerSession { + friend class TransferActions; +public: + struct LineupCheckpoint { + GameState state; + int manager = -1; + int club = -1; + }; + // Loads the data files and runs the program start up to the options dialog. The Watcom + // generator starts at `watcom_seed` (the original: srand() with the clock). + CareerSession(const std::filesystem::path& data, uint32_t watcom_seed); + + // The order of the clubs as the next manager dialog shows them: runtime club id -> + // master database index (ui::SelectionContext::club_order). + ui::SelectionContext selection_context(uint64_t revision) const; + std::vector manager_choices(uint64_t revision) const; + bool begin_manager_join(const ui::DeskRequest&, const ui::SetupOptions&, uint64_t revision, std::string& error); + bool confirm_manager_join(const ui::ManagerChoice&, std::string& error); + ui::SelectionContext manager_join_context() const; + bool manager_join_complete() const; + void cancel_manager_join() { manager_join_.reset(); } + struct ManagerJoinCheckpoint { + GameState state; + WatcomRandom rand; + GameRandom game; + TurnDriver driver; + std::vector managers; + std::vector desk_callargs; + }; + ManagerJoinCheckpoint manager_join_checkpoint() const { + return {g_, rand_, game_, turn_driver_, managers_, source_desk_callargs_}; + } + void restore_manager_join_checkpoint(ManagerJoinCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); rand_ = checkpoint.rand; game_ = checkpoint.game; + turn_driver_ = std::move(checkpoint.driver); managers_ = std::move(checkpoint.managers); + source_desk_callargs_ = std::move(checkpoint.desk_callargs); + manager_join_.reset(); + } + bool commit_manager_join(ui::CareerInitializationResult&, uint64_t& revision, std::string& error); + + // A confirmed manager (in confirmation order). The options are taken over before the + // first one. Returns false with `error` set if the engine cannot do it. + bool confirm_manager(const ui::SetupOptions& options, const ui::ManagerChoice& choice, std::string& error); + int confirmed() const { return int(managers_.size()); } + + // After the last manager: the first season up to the first desk. + bool finish(ui::CareerInitializationResult& result, std::string& error); + std::optional enter_club_information(int team, std::string& error); + std::optional change_club_information_category(int team, int requested, + std::string& error); + std::optional redraw_club_player_detail( + const ClubPlayerDetailSelection&, std::string& error); + std::optional dispatch_club_player_national_action( + const ClubPlayerDetailSelection&, std::string& error); + // Synchronous manual DispatchClubPlayerPendingOffers batch. Hooks present the staged state; + // unsupported/throwing decisions discard the state and both RNGs together. + std::optional dispatch_club_player_pending_offers( + const ClubPlayerDetailSelection&, uint64_t expected_revision, + const PendingOfferHooks&, uint64_t& revision, std::string& error); + + // Ordinary market actions run on a full Native/RNG copy. Only a supported + // result with valid dependent projections becomes the live state. + std::optional dispatch_transfer_market( + const ui::TransferMarketRequest&, const HumanBuyerSaleHooks&, + uint64_t& revision, std::string& error); + + struct TransferMarketPreviewDispatch { + ui::PreparationState preparation; + ui::TransferMarketPreview quote; + }; + // TransferMarketScreen belongs to pointer input, never to rendering. Stage the optional + // W fallback and validate the owned projection before publishing it. + std::optional preview_transfer_market( + const ui::TransferMarketRequest&, uint64_t& revision, std::string& error); + + struct TransferOfferEditorDispatch { + ui::PreparationState preparation; + ui::OutgoingTransferEditorState editor; + TransferActionResult action; + }; + std::optional open_transfer_offer( + const ui::TransferMarketRequest&, uint64_t& revision, std::string& error); + std::optional dispatch_transfer_offer( + const ui::OutgoingTransferRequest&, const HumanBuyerSaleHooks&, + uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}, + const TransferOfferPlayerInfoPresenter& player_info = {}); + // Poaching (Abwerben, transfer screen button 4): the checks and the special list row of + // src/game/poach.hpp, then the ordinary offer editor on that row (decided at once, see + // dispatch_transfer_offer). Without `editor` the attempt ended with the original's + // messages in `start` (some still count as an attempt and are committed). + struct PoachDispatch { + PoachStart start; + std::optional editor; + }; + std::optional open_poach(int manager_slot, int squad_slot, uint64_t& revision, std::string& error); + // FriendlyMatchScreen(param1=1) owns a separate staged selection, not the normal + // LeagueScreenShown Table family. Return the actual squad selection delivered by + // ClubPlayerDetailFromGame's >25-tick long press, or nullopt when Table is cancelled. + using PoachPlayerSelector = std::function( + CareerSession& selection_session, ClubModalServices&, int manager_slot, + uint64_t& selection_revision, const Image& transfer_backdrop)>; + using PoachUiAccept = std::function; + bool close_poach_table_selection(const ui::LeagueFamilyRequest&, std::string& error); + bool dispatch_poach_ui(const ui::TransferMarketRequest&, const Image&, + const PoachPlayerSelector&, const PoachUiAccept&, uint64_t& revision, std::string& error); + ClubModalServices live_club_modal_services(uint64_t& revision); + struct LeaguePairingsDraft { + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime,original_runtime; + LeaguePairingsOwner owner; + ui::LeaguePairingsIdentity identity; + Bytes original_stream; + uint32_t original_rand_seed=0; + int32_t original_game_seed=0; + uint64_t original_rand_calls=0,original_game_calls=0; + std::optional active_packet; + // Only the active presentation context is borrowed from the driver; + // retain its original descriptors/fixtures/profiles to reject a stale + // redraw or nested return instead of changing packet ownership silently. + std::vector>> original_active_groups; + std::vector original_referee_profiles; + }; + struct LeagueFamilyOwner { + enum class TableDispatchPhase : uint8_t { ready, range_start, range_end, forecast_pending_present }; + ui::StrengthsIdentity identity; + uint8_t child = 0; // Source selector: 1 table, 2 pairings, 3 strengths. + bool friendly_opponent = false; // Direct FriendlyMatchScreen(2,0), without outer LeagueScreenShown close. + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::map runtime; + struct TableOwner { + int first_round = 0, end_round = 0; + uint8_t aggregation_flags = 4; + int normal_mode = 0; + TableDispatchPhase phase = TableDispatchPhase::ready; + int pending_start_round = 0; + int previous_start_round = 0, previous_end_round = 0; + uint16_t display_word_override = 0; + uint8_t runtime_font_id = 0; + std::string retained_range_label_source_bytes; + int dialog_x = 140, dialog_y = 80; + ui::LeagueTableState page; + std::optional forecast_page; + std::optional forecast_game_after; + bool forecast_present_pending = false; + bool operator==(const TableOwner& other) const { + const bool same_rng = forecast_game_after.has_value() == other.forecast_game_after.has_value() && + (!forecast_game_after || (forecast_game_after->seed() == other.forecast_game_after->seed() && + forecast_game_after->calls() == other.forecast_game_after->calls())); + return first_round == other.first_round && end_round == other.end_round && + aggregation_flags == other.aggregation_flags && normal_mode == other.normal_mode && + phase == other.phase && pending_start_round == other.pending_start_round && + previous_start_round == other.previous_start_round && previous_end_round == other.previous_end_round && + display_word_override == other.display_word_override && runtime_font_id == other.runtime_font_id && + retained_range_label_source_bytes == other.retained_range_label_source_bytes && + dialog_x == other.dialog_x && dialog_y == other.dialog_y && page == other.page && + forecast_page == other.forecast_page && same_rng && + forecast_present_pending == other.forecast_present_pending; + } + }; + std::optional table; + bool operator==(const LeagueFamilyOwner&) const = default; + }; + using TableDispatchPhase = LeagueFamilyOwner::TableDispatchPhase; + struct LeagueTableDispatch { + ui::LeagueTableState page; + ui::StrengthsIdentity identity; + TableDispatchPhase phase = TableDispatchPhase::ready; + std::optional dialog; + }; + struct LeaguePairingsCheckpoint { + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional draft; + std::optional family; + uint64_t next_family_id = 1; + }; + struct LeaguePairingsDispatch { + bool closed=false; + ui::LeaguePairingsState page; + ui::PreparationState preparation; + }; + std::optional open_league_pairings(const ui::DeskRequest&,uint64_t revision,std::string& error); + std::optional dispatch_league_pairings(const ui::LeaguePairingsRequest&, + uint64_t& revision,std::string& error,const TransferOfferTeamInfoPresenter& team_info={}); + LeaguePairingsCheckpoint league_pairings_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,league_pairings_draft_,league_family_owner_,next_league_family_id_}; + } + void restore_league_pairings_checkpoint(LeaguePairingsCheckpoint checkpoint) { + g_=std::move(checkpoint.state);game_=checkpoint.game;rand_=checkpoint.rand; + club_modal_runtime_=std::move(checkpoint.runtime);league_pairings_draft_=std::move(checkpoint.draft); + league_family_owner_=std::move(checkpoint.family);next_league_family_id_=checkpoint.next_family_id; + } + const std::optional& league_pairings_owner() const {return league_pairings_draft_;} + struct BalanceDraft { + struct NoticeGate { uint8_t compact_dialog_frame=0,notice_gate_disabled=0,presentation_blocked=0; bool enabled() const { return notice_gate_disabled==0&&(compact_dialog_frame!=0||presentation_blocked==0); } }; + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime, original_runtime; + ui::BalanceState page; + Bytes original_stream; + uint32_t original_rand_seed=0; + int32_t original_game_seed=0; + uint64_t original_rand_calls=0, original_game_calls=0; + bool warning=false; + NoticeGate notice_gate; + }; + struct BalanceCheckpoint { + GameState state; GameRandom game; WatcomRandom rand; + std::map runtime; + std::optional draft; + uint64_t next_scope=0; + }; + struct BalanceDispatch { bool closed=false, warning=false; ui::BalanceState page; ui::PreparationState preparation; }; + std::optional open_balance_plan(const ui::DeskRequest&, uint64_t revision, + const Image& underlay, std::string& error); + std::optional dispatch_balance_plan(const ui::BalanceRequest&, uint64_t& revision, + std::string& error); + BalanceCheckpoint balance_checkpoint() const { return {g_,game_,rand_,club_modal_runtime_,balance_draft_,next_balance_scope_}; } + void restore_balance_checkpoint(BalanceCheckpoint c) { g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime);balance_draft_=std::move(c.draft);next_balance_scope_=c.next_scope; } + bool balance_active() const { return bool(balance_draft_)||balance_dispatch_active_; } + std::map club_modal_runtime_checkpoint() const { return club_modal_runtime_; } + void restore_club_modal_runtime(std::map runtime) { club_modal_runtime_=std::move(runtime); } + const std::optional& transfer_offer_owner() const { return transfer_offer_editor_; } + void restore_transfer_offer_owner(std::optional owner, uint64_t revision) { + transfer_offer_editor_ = std::move(owner); transfer_offer_revision_ = revision; + } + + struct StrengthsOwner { + ui::StrengthsState page; + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::map runtime; + }; + struct LeagueFamilyCheckpoint { + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional family; + std::optional strengths; + std::optional pairings; + uint64_t next_strengths_scope=1,next_family_id=1; + }; + struct StrengthsCheckpoint { + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional owner; + uint64_t next_scope = 1; + std::optional family; + uint64_t next_family_id = 1; + }; + struct StrengthsDispatch { + bool closed = false; + ui::StrengthsState page; + ui::PreparationState preparation; + }; + // Semantic entry has no MEN/open-widget requirement. Every submitted identity + // and both expected saved words are validated again against the live session. + std::optional strengths_open_request(uint64_t revision) const; + std::optional begin_league_family(ui::StrengthsIdentity,uint8_t child, + uint64_t revision,std::string& error); + std::optional begin_friendly_opponent_table(uint64_t revision,std::string& error); + // Resolves the clicked physical row through normal working ranks after KI. + std::optional resolve_friendly_table_opponent(const ui::LeagueFamilyRequest&,uint64_t revision, + std::string& error) const; + std::optional acknowledge_friendly_own_club( + const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + std::optional finish_friendly_opponent_table(const ui::LeagueFamilyRequest&, + uint64_t& revision,std::string& error); + bool advance_league_family(const ui::LeagueFamilyRequest&,ui::StrengthsIdentity,uint8_t target, + uint64_t revision,std::string& error); + std::optional league_family_owner() const { return league_family_owner_; } + LeagueFamilyCheckpoint league_family_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,league_family_owner_,strengths_owner_,league_pairings_draft_, + next_strengths_scope_,next_league_family_id_}; + } + void restore_league_family_checkpoint(LeagueFamilyCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime); + league_family_owner_=std::move(c.family);strengths_owner_=std::move(c.strengths); + league_pairings_draft_=std::move(c.pairings);next_strengths_scope_=c.next_strengths_scope; + next_league_family_id_=c.next_family_id; + } + std::optional close_league_family(const ui::LeagueFamilyRequest&, + uint64_t& revision,std::string& error); + bool suspend_strengths_for_family(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + bool suspend_pairings_for_family(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + bool select_league_family_page(const ui::LeagueFamilyRequest&,uint64_t revision,std::string& error); + std::optional current_league_table_dispatch(std::string& error) const; + std::optional dispatch_league_table_control( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional dispatch_league_table_range_reply( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional acknowledge_league_forecast_present( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error); + std::optional dispatch_family_table_team_info( + const ui::LeagueFamilyRequest&,uint64_t& revision,std::string& error, + const TransferOfferTeamInfoPresenter&, + const std::optional* poach_selection = nullptr); + bool refresh_family_after_child(const ui::StrengthsIdentity& prior,uint8_t child, + ui::StrengthsIdentity next,uint64_t revision,std::string& error); + bool prepare_league_family_child(const ui::StrengthsIdentity&,uint8_t child, + uint64_t revision,std::string& error); + std::optional dispatch_strengths(const ui::StrengthsRequest&, + uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info = {}, + bool family_transition = false); + StrengthsCheckpoint strengths_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,strengths_owner_,next_strengths_scope_,league_family_owner_,next_league_family_id_}; + } + void restore_strengths_checkpoint(StrengthsCheckpoint checkpoint) { + g_=std::move(checkpoint.state); game_=checkpoint.game; rand_=checkpoint.rand; + club_modal_runtime_=std::move(checkpoint.runtime); strengths_owner_=std::move(checkpoint.owner); + next_strengths_scope_=checkpoint.next_scope;league_family_owner_=std::move(checkpoint.family); + next_league_family_id_=checkpoint.next_family_id; + } + const std::optional& strengths_owner() const { return strengths_owner_; } + + struct TopScorersOwner { + ui::TopScorersState page; + Bytes native; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + struct TopScorersCheckpoint { + GameState state; + GameRandom game; + WatcomRandom rand; + std::optional owner; + uint64_t next_scope = 1; + }; + struct TopScorersDispatch { + bool closed = false; + ui::TopScorersState page; + ui::PreparationState preparation; + }; + std::optional open_top_scorers(const ui::DeskRequest&, uint64_t revision, + const Image& underlay, std::string& error); + std::optional dispatch_top_scorers(const ui::TopScorersRequest&, + uint64_t& revision, std::string& error); + TopScorersCheckpoint top_scorers_checkpoint() const { + return {g_,game_,rand_,top_scorers_owner_,next_top_scorers_scope_}; + } + void restore_top_scorers_checkpoint(TopScorersCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand; + top_scorers_owner_=std::move(c.owner);next_top_scorers_scope_=c.next_scope; + } + bool top_scorers_active() const { return bool(top_scorers_owner_) || top_scorers_dispatch_active_; } + const std::optional& top_scorers_owner() const { return top_scorers_owner_; } + + struct OpportunitiesOwner { ui::OpportunitiesState page; Bytes native; GameRandom game; WatcomRandom rand; bool national_source_case=false; }; + struct OpportunitiesCheckpoint { GameState state; GameRandom game; WatcomRandom rand; std::optional owner; uint64_t next_scope=1; }; + struct OpportunitiesDispatch { bool closed=false; ui::OpportunitiesState page; ui::PreparationState preparation; }; + std::optional open_opportunities(const ui::DeskRequest&,uint64_t,const Image&,std::string&, + bool national_source_case=false,int stable_identity=-1); + std::optional dispatch_opportunities(const ui::OpportunitiesRequest&,uint64_t&,std::string&); + OpportunitiesCheckpoint opportunities_checkpoint() const { return {g_,game_,rand_,opportunities_owner_,next_opportunities_scope_}; } + void restore_opportunities_checkpoint(OpportunitiesCheckpoint c) { g_=std::move(c.state);game_=c.game;rand_=c.rand;opportunities_owner_=std::move(c.owner);next_opportunities_scope_=c.next_scope; } + bool opportunities_active() const { return bool(opportunities_owner_)||opportunities_dispatch_active_; } + bool apply_statistics_preference(const ui::DeskRequest&, int manager_slot, uint8_t expected_flags, + uint8_t target_flags, uint64_t& revision, std::string& error); + + struct OtherGamesSelection { + // Process-global Source selectors: the ordinary desk entry does not clear + // Season_SeasonTransition_RuntimeField/CareerSession_FormatError_RuntimeField8 when the active manager changes. + int competition = 0, linked_page = 0; + }; + struct OtherGamesOwner { + ui::OtherGamesState page; + ui::DeskRequest desk_owner; + int round = -1, participant_offset = 0; + OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail; + Bytes native; + std::map runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + struct OtherGamesCheckpoint { + GameState state; + GameRandom game; + WatcomRandom rand; + std::map runtime; + std::optional owner; + OtherGamesSelection selection; + uint64_t next_scope = 1; + }; + struct OtherGamesDispatch { + bool closed = false; + ui::OtherGamesState page; + ui::PreparationState preparation; + }; + std::optional open_other_games( + const ui::DeskRequest&, uint64_t& revision, const Image& underlay, std::string& error); + std::optional dispatch_other_games( + const ui::OtherGamesRequest&, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + OtherGamesCheckpoint other_games_checkpoint() const { + return {g_,game_,rand_,club_modal_runtime_,other_games_owner_,other_games_selection_,next_other_games_scope_}; + } + void restore_other_games_checkpoint(OtherGamesCheckpoint c) { + g_=std::move(c.state);game_=c.game;rand_=c.rand;club_modal_runtime_=std::move(c.runtime); + other_games_owner_=std::move(c.owner);other_games_selection_=c.selection; + next_other_games_scope_=c.next_scope; + } + bool other_games_active() const { return bool(other_games_owner_) || other_games_dispatch_active_; } + const std::optional& other_games_owner() const { return other_games_owner_; } + + // Accept the desk's kickoff request and advance the shared engine turn cursor. + TurnAdvanceResult dispatch_kickoff(const ui::DeskRequest& request, uint64_t& revision, + std::string& error); + + // Fresh coherent preparation views for one controller revision, after a desk action. + ui::PreparationState preparation_projection(uint64_t revision) const; + + // Validates camp request context before any action; advances revision only on change. + bool dispatch_training(const ui::TrainingRequest&, uint64_t& revision, std::string& error); + bool dispatch_training_camp(const ui::TrainingCampRequest&, uint64_t& revision, std::string& error); + bool dispatch_bank(const ui::BankRequest&, uint64_t& revision, std::string& error); + struct BankCheckpoint { + GameState state; + WatcomRandom rand; + GameRandom game; + std::optional last_tip; + std::optional property_notice; + std::optional credit_notice; + }; + BankCheckpoint bank_checkpoint() const { return {g_, rand_, game_, last_stock_tip_, last_property_notice_, last_credit_notice_}; } + void restore_bank_checkpoint(BankCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + rand_ = checkpoint.rand; game_ = checkpoint.game; + last_stock_tip_ = checkpoint.last_tip; + last_property_notice_ = std::move(checkpoint.property_notice); + last_credit_notice_ = std::move(checkpoint.credit_notice); + } + bool dispatch_stadium(const ui::StadiumRequest&, uint64_t& revision, std::string& error, + const ConstructionNoticeHook& notice_presenter = {}, + const SeasonTicketCompensationNoticeHook& compensation_presenter = {}); + struct StadiumRuntime { + struct BlockExpansion { + StadiumBlockExpansionQuote quote; + uint32_t total_target_places = 0; + uint8_t desired_features = 0; + int header_text_variant = -1; + std::optional tip; + }; + bool opened = false; + bool data_open = false; + uint8_t data_flags = 0x40; + int manager = -1, club = -1, stable_club = -1, mode = -1; + uint64_t scope = 0, sequence = 0, revision = 0; + int price_percent = 100; + std::optional> periphery_quote; + std::optional investment; + std::optional selection_status; + int option_index = -1, text_variant = -1; + std::optional option; + std::optional tip; + std::optional block_expansion; + std::string feedback; + }; + struct StadiumCheckpoint { + GameState state; + WatcomRandom rand; + GameRandom game; + StadiumRuntime stadium; + uint64_t next_scope; + }; + StadiumCheckpoint stadium_checkpoint() const { return {g_, rand_, game_, stadium_, next_stadium_scope_}; } + void restore_stadium_checkpoint(StadiumCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); rand_ = checkpoint.rand; game_ = checkpoint.game; + stadium_ = std::move(checkpoint.stadium); next_stadium_scope_ = checkpoint.next_scope; + } + bool stadium_tip_deadline_expired() const; + bool dispatch_toto(const ui::TotoRequest&, uint64_t& revision, std::string& error); + bool dispatch_tactics(const ui::TacticsRequest&, uint64_t& revision, std::string& error); + bool dispatch_lineup(const ui::LineupRequest&, uint64_t& revision, std::string& error); + // Source PitchScreen live-match path: apply one user-picked field/bench + // exchange and re-rate the side while TurnDriver is paused after a minute. + bool dispatch_live_substitution(const ui::LineupRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + LiveSubstitutionResult dispatch_live_substitution_result(const ui::LineupRequest&, int minute, + int source_mode, MatchEngine&, uint64_t& revision); + bool dispatch_live_tactic(const ui::TacticsRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + bool dispatch_live_pitch(const ui::PitchRequest&, int minute, int source_mode, + MatchEngine&, uint64_t& revision, std::string& error); + LiveSubstitutionResult dispatch_live_pitch_result(const ui::PitchRequest&, int minute, + int source_mode, MatchEngine&, uint64_t& revision); + // Source EndPhase's configured keyboard slots 0/1 (G/T) suspend the current + // match-minute loop and open LeagueScreenShown or CupGroupOverviewEffects. The caller must only create + // this request from that synchronous observer; group_index is fixed to 0, + // the first Native descriptor selected by CareerSessionRuntimeField5 (not the current DeskPosition tick). + enum class LiveOverviewKind : uint8_t { league_table, league_pairings, league_strengths, cup_other_games }; + struct LiveOverviewRequest { + int key_slot = -1; // Source Main_FileScreen_RuntimeField slot: 0=G/table, 1=T/pairings. + int minute = -1; + int group_index = -1; + int manager_slot = -1; + int runtime_team = -1; + uint64_t revision = 0; + uint64_t sequence = 0; + bool operator==(const LiveOverviewRequest&) const = default; + }; + struct LiveOverviewProjection { + LiveOverviewKind kind = LiveOverviewKind::league_table; + LiveOverviewRequest owner; + ui::StrengthsIdentity family_identity; // G uses the existing full Table-family controls. + std::optional table; + std::optional pairings; + std::optional strengths; + std::optional cup; + }; + using LiveOverviewAction = std::variant; + struct LiveOverviewDispatch { + LiveOverviewKind kind = LiveOverviewKind::league_table; + bool closed = false; + ui::StrengthsIdentity family_identity; + TableDispatchPhase table_phase = TableDispatchPhase::ready; + std::optional table_dialog; + std::optional table; + std::optional pairings; + std::optional strengths; + std::optional cup; + std::optional preparation; + }; + std::optional open_live_overview(const LiveOverviewRequest&, + MatchEngine&, uint64_t& revision, const Image& underlay, std::string& error); + std::optional dispatch_live_overview(const LiveOverviewAction&, + MatchEngine&, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + bool live_overview_active() const { return bool(live_overview_owner_); } + // Only available inside the installed phase presenter. Uses the same Source + // viewer/action owners as keyboard overviews, before the engine's single ACK. + std::optional open_phase_results(uint64_t& revision, + const Image& underlay, std::string& error); + std::optional dispatch_phase_results(const LiveOverviewAction&, + uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& team_info = {}); + // Source EndPhase key slot 2 suspends the live-minute observer in SettingsSourceRefusal. + // The request is accepted only during that synchronous observer; Session allocates + // the returned sequence, so callers must retain the returned owner verbatim. + struct LiveSettingsRequest { + int minute = -1; + int manager_slot = -1; + int runtime_team = -1; + uint64_t revision = 0; + uint64_t sequence = 0; + bool operator==(const LiveSettingsRequest&) const = default; + }; + struct LiveSettingsWrite { + uint64_t owner_sequence = 0; + ui::SettingsWriteRequest write; + }; + struct LiveSettingsFile { uint64_t owner_sequence = 0; ui::SaveLoadRequest request; }; + struct LiveSettingsCloseRequest { LiveSettingsRequest owner; }; + using LiveSettingsAction = std::variant; + struct LiveSettingsProjection { LiveSettingsRequest owner; ui::SettingsState state; }; + struct LiveSettingsDispatch { LiveSettingsRequest owner; bool closed = false; ui::SettingsState state; }; + std::optional open_live_settings(const LiveSettingsRequest&, + MatchEngine&, uint64_t& revision, std::string& error); + std::optional dispatch_live_settings(const LiveSettingsAction&, + MatchEngine&, uint64_t& revision, std::string& error); + bool live_settings_active() const { return bool(live_settings_owner_); } + struct DeskSettingsOwner { + uint64_t sequence = 0, revision = 0; + int manager_slot = -1, source_item_id = -1; + bool operator==(const DeskSettingsOwner&) const = default; + }; + struct DeskSettingsWrite { uint64_t owner_sequence = 0; ui::SettingsWriteRequest write; }; + struct DeskSettingsFile { uint64_t owner_sequence = 0; ui::SaveLoadRequest request; }; + struct DeskSettingsClose { DeskSettingsOwner owner; }; + using DeskSettingsAction = std::variant; + struct DeskSettingsProjection { DeskSettingsOwner owner; ui::SettingsState state; }; + struct DeskSettingsDispatch { DeskSettingsOwner owner; bool closed = false; ui::SettingsState state; }; + struct DeskSettingsCheckpoint { + GameState state; + std::map runtime; + std::optional owner; + uint8_t initial_h8 = 0; + uint64_t next_scope = 1, revision = 0; + }; + std::optional open_desk_settings(const ui::DeskRequest&, + uint64_t& revision, std::string& error); + std::optional dispatch_desk_settings(const DeskSettingsAction&, + uint64_t& revision, std::string& error); + DeskSettingsCheckpoint desk_settings_checkpoint(uint64_t revision) const; + void restore_desk_settings_checkpoint(DeskSettingsCheckpoint, uint64_t& revision); + bool desk_settings_active() const { return bool(desk_settings_owner_); } + bool begin_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision, std::string& error); + bool begin_live_event_intervention(const LiveMatchEvent&, MatchEngine&, + uint64_t& revision, std::string& error); + bool finish_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision, std::string& error); + bool finish_live_event_intervention(const LiveMatchEvent&, MatchEngine&, + uint64_t& revision, std::string& error); + void abort_live_intervention(int minute, int source_mode, int manager, int team, + MatchEngine&, uint64_t& revision); + // Semantic Pitch actions bind the live manager/club, prepared entry and revision. + // The four Source helpers are deterministic; rejected actions do not commit. + bool dispatch_pitch(const ui::PitchRequest&, uint64_t& revision, std::string& error); + bool dispatch_pitch_swap(const ui::PitchRequest&, uint64_t& revision, std::string& error); + // The Source desk callargs are the only authority for an ordinary upcoming + // opponent. The revision binds the returned display projection; write requests + // are independently checked against the controller's current revision. + std::optional prepared_lineup_opponent(int manager_slot, int runtime_club, + uint64_t revision) const; + LineupCheckpoint lineup_checkpoint() const { return {g_, lineup_entry_manager_, lineup_entry_club_}; } + void restore_lineup_checkpoint(LineupCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + lineup_entry_manager_ = checkpoint.manager; + lineup_entry_club_ = checkpoint.club; + } + bool dispatch_mailbox(const ui::MailboxActionRequest&, uint64_t& revision, std::string& error); + std::optional pending_mailbox_notification(uint64_t revision) const; + bool acknowledge_mailbox_close(const ui::MailboxCloseRequest&, uint64_t revision, + std::string& error); + uint32_t mailbox_notification_checkpoint() const { + return g_.memory.has(::bmh::layout::MailboxRecipientMask) ? g_.memory.u32(::bmh::layout::MailboxRecipientMask) : 0; + } + void restore_mailbox_notification_checkpoint(uint32_t mask) { + if (g_.memory.has(::bmh::layout::MailboxRecipientMask)) g_.memory.set32(::bmh::layout::MailboxRecipientMask, mask); + } + bool dispatch_settings(const ui::SettingsWriteRequest&, uint64_t& revision, std::string& error); + bool dispatch_contract(const ui::ContractRequest&, uint64_t& revision, + ui::ContractActionResult&, std::string& error); + bool dispatch_advertising(const ui::AdvertisingRequest&, uint64_t& revision, std::string& error, + AdvertisingSpendingResult* spending_result = nullptr); + // CheckAdvertisingRenewal: renewing a contract whose months ran out (game/desk_actions.hpp). The + // check draws the sponsor's random number and returns the question or settles the + // refusal; the answer applies the manager's choice. Both bind the active manager and + // the revision (and advance it). + std::optional check_advertising_renewal(int manager_slot, int display_slot, uint64_t& revision, + std::string& error); + bool answer_advertising_renewal(int manager_slot, int contract_slot, bool renew, uint64_t& revision, std::string& error); + enum class AdvertisingRenewalPresentation { abort, renew, decline, acknowledged }; + using AdvertisingRenewalPresenter = std::function; + std::optional dispatch_advertising_renewal( + const ui::AdvertisingRequest&, uint64_t& revision, std::string& error, + const AdvertisingRenewalPresenter& presenter); + struct AdvertisingActionResult { + AdvertisingSpendingResult spending; + std::optional renewal; + }; + using AdvertisingAcknowledge = std::function; + // Frontends supply an observed intent, never a live-state refresh of an old + // offer. Acknowledgement is inside the transaction (SDL projection can fail). + bool apply_advertising(const ui::AdvertisingRequest&, uint64_t& revision, + std::string& error, const AdvertisingAcknowledge& acknowledge = {}, + const AdvertisingRenewalPresenter& presenter = {}); + bool accept_advertising_selection(const ui::AdvertisingState& observed, int display_slot, + int raw_offer, uint64_t request_id, uint64_t& revision, std::string& error); + bool set_advertising_budget(const ui::AdvertisingState& observed, int target_slot, + uint32_t amount, uint64_t request_id, uint64_t& revision, std::string& error, + AdvertisingSpendingResult& result); + struct AdvertisingCheckpoint { + GameState state; + uint64_t last_request_id = 0; + WatcomRandom rand; + GameRandom game; + }; + AdvertisingCheckpoint advertising_checkpoint() const { return {g_, last_advertising_request_id_, rand_, game_}; } + void restore_advertising_checkpoint(AdvertisingCheckpoint checkpoint) { + g_ = std::move(checkpoint.state); + last_advertising_request_id_ = checkpoint.last_request_id; + rand_ = checkpoint.rand; + game_ = checkpoint.game; + } + void clear_contract_quote() { contract_quote_.reset(); } + bool dispatch_desk_widget(const ui::DeskRequest&, uint64_t& revision, std::string& error); + bool dispatch_desktop_layout(const ui::DeskRequest&, uint64_t& revision, std::string& error); + bool dispatch_ticket_price(const TicketPriceRequest&, uint64_t& revision, std::string& error); + bool dispatch_automation(const AutomationRequest&, uint64_t& revision, std::string& error); + ui::DeskState desktop_projection(uint64_t revision) const; + bool save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error); + void configure_autosave_directory(const std::filesystem::path& directory); + std::string take_autosave_error(); + // Source DispatchMenuLayout: read/write the active manager's raw 0x360-byte .MEN layout. + // This operation never serializes a CareerSession or consumes either RNG. + bool dispatch_menu_layout(const ui::SaveLoadRequest&, uint64_t& revision, std::string& error); + + // Load an existing V2.24 save without applying new-career options or startup RNG. + CareerSession(const std::filesystem::path& data, uint32_t watcom_seed, const std::filesystem::path& save_path); + + const GameState& state() const { return g_; } + GameState& state() { return g_; } + const TurnResultSnapshot& last_turn_results() const { return turn_driver_.last_results; } + // Owned presentation for the event completed by the last accepted kickoff. + // Empty on a manager handoff or a calendar event without fixtures. + const std::optional& completed_matchday_results() const { return completed_results_; } + // The manager's intervention during a matchday (see TurnDriver::live_minute). + void set_live_minute(decltype(TurnDriver::live_minute) hook) { turn_driver_.live_minute = std::move(hook); } + void set_original_sound(decltype(TurnDriver::original_sound) hook) { turn_driver_.original_sound = std::move(hook); } + void set_live_event(decltype(TurnDriver::live_event) hook) { turn_driver_.live_event = std::move(hook); } + void set_live_reality(decltype(TurnDriver::live_reality) hook) { turn_driver_.live_reality = std::move(hook); } + void set_phase_results(decltype(TurnDriver::phase_results) hook); + void set_live_ball(decltype(TurnDriver::live_ball) hook) { turn_driver_.live_ball = std::move(hook); } + void set_live_chance(decltype(TurnDriver::live_chance) hook) { turn_driver_.live_chance = std::move(hook); } + void set_live_shot(decltype(TurnDriver::live_shot) hook) { turn_driver_.live_shot = std::move(hook); } + void set_live_set_piece(decltype(TurnDriver::live_set_piece) hook) { turn_driver_.live_set_piece = std::move(hook); } + void set_live_booking(decltype(TurnDriver::live_booking) hook) { turn_driver_.live_booking = std::move(hook); } + void set_live_shootout(decltype(TurnDriver::live_shootout) hook) { turn_driver_.live_shootout = std::move(hook); } + // Temporary synchronous presenter for InstallDefaultHooks, invoked by the monthly + // board walk. The supplied random stream is the session's live Watcom stream. + // Frontends install this only while an interactive kickoff is running. + using ContractExpiryPresenter = std::function; + void set_contract_expiry_presenter(ContractExpiryPresenter presenter); + using LoanReturnPresenter = std::function; + void set_loan_return_presenter(LoanReturnPresenter presenter); + using LoanReturnOfferPresenter = std::function; + void set_loan_return_offer_presenter(LoanReturnOfferPresenter presenter, + HumanBuyerSaleHooks sale_hooks = {}); + SportschauSourceOptions sportschau_source_options() const; + void set_sportschau_presentation_hooks(SportschauPresentationHooks hooks) { + turn_driver_.sportschau = std::move(hooks); + } + const SportschauPresentationHooks& sportschau_presentation_hooks() const { + return turn_driver_.sportschau; + } + void set_season_pause(decltype(TurnDriver::season_pause) hook) { turn_driver_.season_pause = std::move(hook); } + void set_season_promotion(SeasonPromotionHook hook) { turn_driver_.season_promotion = std::move(hook); } + void set_season_cup_draw(SeasonCupDrawHook hook) { turn_driver_.season_cup_draw = std::move(hook); } + void set_season_tax(SeasonTaxHooks hooks) { turn_driver_.season_tax = std::move(hooks); } + void set_season_highscore(decltype(TurnDriver::season_highscore) hook) { turn_driver_.season_highscore = std::move(hook); } + // Borrowed only during the synchronous post-desk transaction. Its modal + // presenters receive the staged state rather than the session's live state. + void set_pending_offer_hooks(PendingOfferHooks hooks) { pending_offer_hooks_ = std::move(hooks); } + const PendingOfferHooks& pending_offer_hooks() const { return pending_offer_hooks_; } + void set_pending_offer_entry_policy(PendingOfferEntryPolicy policy) { pending_offer_entry_policy_ = policy; } + PendingOfferEntryPolicy pending_offer_entry_policy() const { return pending_offer_entry_policy_; } + // Synchronous original offer chooser. Installed only while the app advances; + // the modal presenter cannot dispatch another desk action or save a partial turn. + void set_transfer_offer_selector(std::function hook) { + g_.transfer_offer_selector = std::move(hook); + } + void set_transfer_decision_observer(std::function hook) { + g_.transfer_decision_observer = std::move(hook); + } + GameRandom& game() { return game_; } + WatcomRandom& rand() { return rand_; } + uint64_t session_id() const { return session_id_; } + bool career_complete() const { return turn_driver_.stage == TurnDriver::Stage::CareerComplete; } + + // Portable host driver capabilities replace SOUND.CFG runtime latches; they + // are never inferred from a saved switch or written into an FBM on entry. + void configure_sound_capabilities(bool music, bool effects) { + sound_capabilities_ = ui::SettingsSoundCapabilities{music, effects}; + } + ui::SettingsState settings_projection(int manager, uint64_t revision) const { + return ui::settings_from_game(state(), manager, revision, exe_, sound_capabilities_); + } +private: + std::optional sound_capabilities_; + std::optional autosave_directory_; + std::string autosave_error_; + void write_desk_autosave(const GameState&, WatcomRandom&); + bool live_source_identity(const ui::StrengthsIdentity&) const; + bool validate_desk_setting_owner(const DeskSettingIdentity&, uint64_t revision, std::string& error, + bool require_desk_phase = true) const; + bool apply_desk_setting(int manager, bool price, int index, int value, std::string& error); + ui::PreparationState preparation_projection(const GameState&, uint64_t revision) const; + ui::DeskState desktop_projection(const GameState&, uint64_t revision) const; + bool pending_offer_dispatch_active_ = false; + bool market_dispatch_active_ = false; + bool league_pairings_dispatch_active_=false; + bool league_family_teaminfo_active_=false; + bool poach_table_selection_=false; // Only the isolated50775(param1=1) selection Session. + bool strengths_dispatch_active_=false; + bool top_scorers_dispatch_active_=false; + bool opportunities_dispatch_active_=false; + bool other_games_dispatch_active_=false; + uint64_t next_other_games_scope_=1; + std::optional other_games_owner_; + OtherGamesSelection other_games_selection_; + bool balance_dispatch_active_=false; + uint64_t next_balance_scope_=1; + std::optional balance_draft_; + uint64_t next_strengths_scope_=1; + std::optional strengths_owner_; + std::optional league_family_owner_; + uint64_t next_league_family_id_=1; + uint64_t next_top_scorers_scope_=1; + std::optional top_scorers_owner_; + uint64_t next_opportunities_scope_=1; + std::optional opportunities_owner_; + uint64_t league_pairings_scope_=0; + std::optional league_pairings_draft_; + std::optional validate_normal_pairings_group( + const GameState&,LeaguePairingsOwner&,const std::map&) const; + std::optional transfer_offer_editor_; + std::optional poach_; // the open poaching attempt (its editor is transfer_offer_editor_) + uint64_t transfer_offer_revision_ = 0; + bool calendar_advance_active_ = false; + PendingOfferHooks pending_offer_hooks_; + PendingOfferEntryPolicy pending_offer_entry_policy_ = PendingOfferEntryPolicy::legacy_unpresented; + std::map club_modal_runtime_; + void initialize_club_modal_runtime(); + ClubModalServices staged_club_modal_services(GameState&,GameRandom&,WatcomRandom&, + std::map&); + PendingOfferHooks pending_hooks_for_dispatch(PendingOfferHooks) const; + void capture_source_desk_callargs(); + uint64_t last_advertising_request_id_ = 0; + bool advertising_renewal_dispatch_active_ = false; + // Engine hooks for screens the app does not have yet. The contracts screen + // (InstallDefaultHooks, desk menu 27): until it exists, the assistant renews an ended + // contract for two years at the market salary (see the definition). + void install_default_hooks(); + void apply_options(const ui::SetupOptions& options); + int runtime_club(int master) const; + int runtime_club(const GameState&, int master) const; + ui::SelectionContext selection_context_for(const GameState&, uint64_t revision) const; + struct ManagerJoinDraft { + GameState state; + WatcomRandom rand; + GameRandom game; + ui::SetupOptions options; + ui::DeskRequest origin; + std::vector choices; + Bytes original_stream; + uint32_t original_rand_seed = 0; + int32_t original_game_seed = 0; + uint64_t original_rand_calls = 0, original_game_calls = 0, context_revision = 0; + }; + std::optional manager_join_; + + std::filesystem::path data_directory_; + LeImage exe_; + // Source MatchEventsDisabled belongs to the loaded program image, not the Native FBM. + // Both session constructors explicitly initialize this owned runtime input. + Database db_; + TextDb texts_; + GameState g_; + GameRandom game_{0}; + WatcomRandom rand_; + TurnDriver turn_driver_; + // DayCompetitions2 callargs are event-local. A join retains the old slots and + // gets Source's default arrays for its new slot until the next event. + std::vector source_desk_callargs_; + std::string saved_turn_error_; + std::optional completed_results_; + int lineup_entry_manager_ = -1, lineup_entry_club_ = -1; + struct LiveInterventionCheckpoint { + GameState state; + std::vector groups; + GameRandom game{0}; + WatcomRandom rand; + int minute = 0, source_mode = 0, manager = -1, team = -1; + bool source_event = false; + LiveMatchEvent event; + uint64_t initial_revision = 0, current_revision = 0; + }; + std::optional live_intervention_; + struct LiveOverviewOwner { + bool phase_result = false; + LiveOverviewRequest request; + LiveOverviewKind kind = LiveOverviewKind::league_table; + ui::StrengthsIdentity family_identity; + int source_competition = -1; + Bytes original_native; + uint32_t original_rand_seed = 0; + int32_t original_game_seed = 0; + uint64_t original_rand_calls = 0, original_game_calls = 0; + std::vector>> active_groups; + std::vector referees; + }; + std::optional live_overview_owner_; + const PhaseResultRequest* phase_result_request_ = nullptr; // borrowed synchronous boundary only + std::optional open_running_overview(const LiveOverviewRequest&, + MatchEngine&, uint64_t& revision, const Image& underlay, std::string& error, + bool phase_result); + uint64_t next_live_overview_scope_ = 1; + struct LiveSettingsOwner { + LiveSettingsRequest request; + Bytes native; + std::vector expected_buttons; + bool expected_live_desk_disabled = false, expected_live_scene_visible = false; + std::map expected_runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + std::vector>> active_groups; + std::vector referees; + }; + std::optional live_settings_owner_; + uint64_t next_live_settings_scope_ = 1; + bool live_settings_dispatch_active_ = false; + struct DeskSettingsOwnerState { + DeskSettingsOwner owner; + uint8_t initial_h8 = 0; // ApplySettingsFile captures CareerSession_DispatchStrengths_ExecutableField before SettingsSourceRefusal. + Bytes native; + std::map expected_runtime; + uint32_t rand_seed = 0; + int32_t game_seed = 0; + uint64_t rand_calls = 0, game_calls = 0; + }; + std::optional desk_settings_owner_; + uint64_t next_desk_settings_scope_ = 1; + bool desk_settings_dispatch_active_ = false; + bool apply_settings_file(const ui::SaveLoadRequest&, int manager_slot, int origin_item_id, + GameState& staged, bool& loaded, std::string& error) const; + uint64_t session_id_ = 0; + std::vector managers_; + std::optional last_stock_tip_; + std::optional last_property_notice_; + std::optional last_credit_notice_; + StadiumRuntime stadium_; + uint64_t next_stadium_scope_ = 1; + struct ContractQuoteRecord { + uint64_t quote_id = 0, request_id = 0, revision = 0; + int manager_slot = -1, runtime_club = -1, row = -1, player_id = -1; + std::array demands{}; + }; + // Snapshot every mutable Session owner around the synchronous modal. The callback + // may hold a reference to this session; a changed fingerprint rejects the answer, + // and the full copy is restored before the staged Core result can be committed. + struct AdvertisingSessionCheckpoint { + GameState state; GameRandom game; WatcomRandom rand; + TurnDriver driver; std::vector desk_callargs; + std::string saved_turn_error; std::optional completed_results; + int lineup_manager=-1, lineup_club=-1; std::vector managers; + std::optional stock_tip; + std::optional property_notice; + std::optional credit_notice; + StadiumRuntime stadium; uint64_t next_stadium_scope=1; + std::optional contract_quote; uint64_t next_contract_quote_id=1; + uint64_t last_contract_request_id=0; bool options_applied=false; + bool pending_offer_active=false, market_active=false, pairings_active=false, + family_teaminfo_active=false, strengths_active=false, top_scorers_active=false, + other_games_active=false, balance_active=false, calendar_active=false; + uint64_t next_other_games_scope=1; std::optional other_games_owner; + OtherGamesSelection other_games_selection; + uint64_t next_balance_scope=1; std::optional balance; + uint64_t next_strengths_scope=1; std::optional strengths; + std::optional family; uint64_t next_family_id=1; + uint64_t next_top_scorers_scope=1; std::optional top_scorers; + uint64_t pairings_scope=0; std::optional pairings; + std::optional transfer_editor; std::optional poach; + uint64_t transfer_offer_revision=0; PendingOfferHooks pending_hooks; + PendingOfferEntryPolicy pending_policy=PendingOfferEntryPolicy::legacy_unpresented; + std::map runtime; uint64_t last_request_id=0; + std::optional manager_join; + uint64_t revision=0, session_id=0; + }; + AdvertisingSessionCheckpoint advertising_session_checkpoint(uint64_t revision) const; + void restore_advertising_session_checkpoint(AdvertisingSessionCheckpoint); + bool advertising_session_unchanged(const AdvertisingSessionCheckpoint&, uint64_t revision) const; + std::optional contract_quote_; + uint64_t next_contract_quote_id_ = 1; + uint64_t last_contract_request_id_ = 0; + bool contract_expiry_presenter_installed_ = false; + bool loan_return_presenter_installed_ = false; + bool loan_return_offer_presenter_installed_ = false; + bool options_applied_ = false; +}; + +} // namespace bmh::app diff --git a/src/app/controller.cpp b/src/app/controller.cpp new file mode 100644 index 0000000..caef2c6 --- /dev/null +++ b/src/app/controller.cpp @@ -0,0 +1,2351 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "app/controller.hpp" +#include "app/window_actions.hpp" +#include "app/desktop_actions.hpp" +#include "app/audio.hpp" + +#include +#include +#include +#include +#include + +#include "game/save.hpp" +#include "game/reschedule.hpp" +#include "game/messages.hpp" +#include "game/highscore.hpp" +#include "game/schedule.hpp" +#include "ui/league_table.hpp" +#include "ui/desk_records.hpp" +#include "formats/textd.hpp" + + +namespace bmh::app { +namespace fs = std::filesystem; +namespace { +bool same_pending_friendly_request(const ui::StartupFlow& flow, + const ui::FriendlyMatchRequest& request) { + const auto* pending = flow.pending_friendly_action(); + return pending && *pending == request; +} + +std::string friendly_status_message(FriendlyBookingStatus status) { + switch (status) { + case FriendlyBookingStatus::declined: return "Die Kosten wurden abgelehnt."; + case FriendlyBookingStatus::opponent_declined: return "Der Gegner hat nicht zugestimmt."; + case FriendlyBookingStatus::insufficient_funds: return "Das Geld reicht für dieses Spiel nicht aus."; + case FriendlyBookingStatus::invalid_manager: return "Der zuständige Manager ist nicht mehr aktiv."; + case FriendlyBookingStatus::invalid_opponent: return "Der gewählte Gegner ist nicht mehr verfügbar."; + case FriendlyBookingStatus::invalid_date: return "Dieser Termin liegt außerhalb der Saison."; + case FriendlyBookingStatus::date_unavailable: return "Dieser Termin ist inzwischen belegt."; + case FriendlyBookingStatus::plan_full: return "Der Spielplan ist voll."; + case FriendlyBookingStatus::stale_quote: return "Das Angebot ist veraltet. Bitte wähle den Gegner erneut."; + case FriendlyBookingStatus::invalid_request: return "Die Angaben zum Spieltermin sind ungültig."; + case FriendlyBookingStatus::booked: break; + } + return "Der Termin konnte nicht gebucht werden."; +} + +ui::NationalFriendlyIdentity national_friendly_identity(const GameState& game,int manager,int team) { + if(manager<0||manager>=5||size_t(manager+1)*0xb0c>game.manager_records.size()) + throw FormatError("national friendly: missing Source manager identity"); + const size_t record=size_t(manager)*0xb0c; + ui::NationalFriendlyIdentity out; + for(size_t i=0;i<30&&game.manager_records[record+0xa8+i];++i) + out.manager_name.push_back(char(game.manager_records[record+0xa8+i])); + out.portrait=game.manager_records[record+0x221]; + out.manager_slot=manager; + out.badge_fallback=team==0x0fff||(team>89&&team<138)||(team>167&&team<357); + if(!out.badge_fallback&&team>=0&&size_t(team)*2+1= 4) throw FormatError("statistics: invalid manager slot"); + const size_t at=size_t(manager_slot)*0xb0c+0x21d; + if(at>=game.manager_records.size())throw FormatError("statistics: missing manager transfer-history counter"); + const int count=game.manager_records[at]; + if(count>25)throw FormatError("statistics: Original transfer-history count exceeds 25"); + return count; +} +int source_transfer_history_origin(int count) { + if(count<0||count>25)throw FormatError("statistics: invalid transfer-history count"); + const int source_count=count==0?1:count; + return 0x0d+(0x1c-source_count)*3; +} + +void serve_friendly_action(ui::StartupFlow& flow, CareerSession& session, + const ui::FriendlyMatchRequest& request, uint64_t& revision, + const std::filesystem::path& data) { + if (!flow.desktop() || !same_pending_friendly_request(flow, request)) return; + auto& game = session.state(); + const auto& state = flow.desktop()->state(); + const int manager = request.manager_slot; + const bool identity_ok = request.revision == revision && request.revision == state.revision && + manager == state.manager_slot && manager >= 0 && manager < 4 && + size_t(manager) < game.manager_teams.size() && game.memory.has(::bmh::layout::ActiveManager) && + game.memory.has(::bmh::layout::ManagerCount) && game.memory.has(::bmh::layout::FriendlyPlanCount) && + game.memory.u8(::bmh::layout::ActiveManager) == manager && game.memory.u8(::bmh::layout::ManagerCount) == game.manager_teams.size() && + request.runtime_team == game.manager_teams[size_t(manager)] && + request.runtime_team == state.runtime_club && + request.planner_count == game.memory.u8(::bmh::layout::FriendlyPlanCount); + if (!identity_ok || revision == std::numeric_limits::max()) { + flow.reject_friendly_action("Der Spielstand hat sich geändert. Bitte öffne das Menü erneut."); + return; + } + + if(request.national_booking) { + const auto& national=*request.national_booking; + const auto expected=FriendlyActions::national_owner(request); + if(request.kind!=ui::FriendlyRequestKind::book||!request.quote_id|| + request.runtime_team!=0x165||request.opponent<0x166||request.opponent>0x1a2|| + request.season_day<0||request.season_day>365||request.planner_count<0|| + request.planner_count>253||request.revision!=revision|| + national.owner!=expected||national.quote.owner!=expected|| + national.season_day!=request.season_day||national.quote.terms.manager!=manager|| + national.quote.terms.manager_team!=0x165||national.quote.terms.opponent!=request.opponent|| + national.quote.terms.planner_count!=request.planner_count|| + national.quote.terms.home_team!=request.home_team||national.quote.terms.away_team!=request.away_team|| + national.quote.terms.payer_manager!=request.payer_manager|| + national.quote.terms.opponent_manager!=request.opponent_manager|| + national.quote.terms.cost!=request.cost||national.quote.terms.manager_home!=request.manager_home|| + request.accept_cost!=national.accept_cost||request.accept_opponent!=national.accept_opponent) { + flow.reject_friendly_action("Die Angaben zum nationalen Freundschaftsspiel sind veraltet."); + return; + } + const auto date_status=FriendlyActions(session).national_date_status(national.quote,national.owner,uint16_t(request.season_day)); + if(date_status!=FriendlyDateStatus::available&& + date_status!=FriendlyDateStatus::available_with_calendar_event) { + flow.reject_friendly_action(date_status==FriendlyDateStatus::plan_full + ?"Der Spielplan ist voll.":date_status==FriendlyDateStatus::current_or_past + ?"Dieser Termin ist nicht mehr verfügbar.":"Dieser Termin ist inzwischen belegt."); + return; + } + try { + const auto applied=FriendlyActions(session).book_national(request,revision,[&](const ui::FriendlyBookingAck& ack) { + auto desk=session.desktop_projection(ack.revision); + auto preparation=session.preparation_projection(ack.revision); + if(!flow.acknowledge_friendly_booking(ack,std::move(desk),std::move(preparation))) + throw FormatError("national friendly booking ACK did not match the active screen"); + }); + if(!applied.applied) + flow.reject_friendly_action(applied.planner_mismatch ? "Der Spielplan konnte nicht übernommen werden." : + national_friendly_status_message(applied.result.status)); + } catch(...) { + flow.reject_friendly_action("Der Termin konnte nicht übernommen werden."); + } + return; + } + + if (request.kind == ui::FriendlyRequestKind::quote) { + const auto quote = FriendlyActions(session).quote(manager, request.opponent, request.manager_home); + if (quote.status != FriendlyQuoteStatus::quoted || quote.manager_team != request.runtime_team) { + flow.reject_friendly_action("Für diese Mannschaft kann kein Freundschaftsspiel angeboten werden."); + return; + } + ui::FriendlyQuoteProjection projection; + projection.request_id = request.request_id; + projection.revision = request.revision; + projection.manager_slot = manager; + projection.runtime_team = quote.manager_team; + projection.opponent = quote.opponent; + projection.opponent_manager = quote.opponent_manager; + projection.payer_manager = quote.payer_manager; + projection.home_team = quote.home_team; + projection.away_team = quote.away_team; + projection.cost = quote.cost; + projection.planner_count = quote.planner_count; + projection.manager_home = quote.manager_home; + projection.cost_question=friendly_question(game,manager,0x404, + message_text(game,::bmh::layout::Controller_FormatError_TextPointer2)+format_number(game,quote.cost,0x101)); + const int other=quote.opponent_manager>=0?quote.opponent_manager:quote.payer_manager; + if(other>=0&&other!=manager) { + auto body=message_text(game,::bmh::layout::Controller_FormatError_TextPointer3); + if(!quote.manager_home) { + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + body+=exe.cstring(::bmh::layout::NationalFriendlyPayerPrefixText)+format_number(game,quote.cost,0x101)+exe.cstring(::bmh::layout::Controller_FormatError_ExecutableField); + } + projection.owner_question=friendly_question(game,other,0x303,std::move(body)); + } + projection.dates.reserve(366); + for (int day = 0; day <= 365; ++day) { + const auto status = FriendlyActions(session).date_status(quote, uint16_t(day)); + ui::FriendlyDateMark mark = ui::FriendlyDateMark::unavailable; + if (status == FriendlyDateStatus::available) mark = ui::FriendlyDateMark::available; + else if (status == FriendlyDateStatus::available_with_calendar_event) + mark = ui::FriendlyDateMark::available_flagged; + else if (status == FriendlyDateStatus::current_or_past && day == game.season_day()) + mark = ui::FriendlyDateMark::current_day; + projection.dates.push_back({day, mark}); + } + if (!flow.acknowledge_friendly_quote(std::move(projection))) + flow.reject_friendly_action("Das Angebot ist nicht mehr aktuell. Bitte versuche es erneut."); + return; + } + + if (request.kind != ui::FriendlyRequestKind::book || request.quote_id == 0 || + request.season_day < 0 || request.season_day > 365 || request.opponent < 0 || + request.opponent >= 168 || request.cost < 0 || request.planner_count > 253) { + flow.reject_friendly_action("Die Angaben zum Spieltermin sind ungültig."); + return; + } + try { + const auto applied=FriendlyActions(session).book_club(request,revision,[&](const ui::FriendlyBookingAck& ack) { + auto desk=session.desktop_projection(ack.revision); + auto preparation=session.preparation_projection(ack.revision); + if(!flow.acknowledge_friendly_booking(ack,std::move(desk),std::move(preparation))) + throw FormatError("friendly booking ACK did not match the active screen"); + }); + if(!applied.applied) + flow.reject_friendly_action(applied.planner_mismatch ? "Der Spielplan konnte nicht übernommen werden." : + friendly_status_message(applied.result.status)); + } catch(const std::exception&) { + flow.reject_friendly_action("Der Termin konnte nicht übernommen werden."); + } +} + +bool valid_national_friendly_family(const ui::StartupFlow& flow,const GameState& game,uint64_t revision) { + if(!flow.national_friendly_family_active())return true; + const auto* owner=flow.national_friendly_owner(); + const auto* origin=flow.national_friendly_desk_owner(); + const auto* menu=flow.statistics_menu(); + const auto* desk=flow.desktop(); + if(!owner||!origin||!menu||!desk||owner->desk_menu!=6||owner->runtime_team!=0x165|| + owner->manager<0||owner->revision!=revision||origin->kind!=ui::DeskRequestKind::open_menu|| + origin->menu_kind!=6||origin->manager_slot!=owner->manager||origin->revision!=revision|| + desk->state().revision!=revision||desk->state().manager_slot!=owner->manager|| + menu->state().owner.kind!=ui::DeskRequestKind::open_menu||menu->state().owner.menu_kind!=23|| + menu->state().owner.manager_slot!=owner->manager||menu->state().owner.revision!=revision|| + size_t(owner->manager)>=game.manager_teams.size()||game.manager_teams[size_t(owner->manager)]!=0x165|| + !game.memory.has(::bmh::layout::ActiveManager)||int(game.memory.u8(::bmh::layout::ActiveManager))!=owner->manager)return false; + return true; +} + +void serve_national_friendly_selection(ui::StartupFlow& flow,CareerSession& session, + int selected_team,uint64_t& revision,const std::filesystem::path& data, + const NationalFriendlyQuestionPresenter& presenter) { + const auto* owner=flow.national_friendly_owner(); + const auto* desk_request=flow.national_friendly_desk_owner(); + if(!owner||!desk_request||!flow.desktop()||!session.state().memory.has(::bmh::layout::ActiveManager)|| + !valid_national_friendly_family(flow,session.state(),revision))return; + const auto& game=session.state(); + const auto& desk=flow.desktop()->state(); + const int manager=owner->manager; + if(owner->desk_menu!=6||owner->runtime_team!=0x165||owner->revision!=revision|| + desk_request->kind!=ui::DeskRequestKind::open_menu||desk_request->menu_kind!=6|| + desk_request->revision!=revision||desk_request->manager_slot!=manager|| + desk.revision!=revision||desk.manager_slot!=manager||manager<0|| + size_t(manager)>=game.manager_teams.size()||game.manager_teams[size_t(manager)]!=0x165|| + int(game.memory.u8(::bmh::layout::ActiveManager))!=manager||selected_team<0x166||selected_team>0x1a2) { + flow.close_national_friendly_picker(); + return; + } + if(!presenter) { flow.close_national_friendly_picker(); return; } + ui::NationalFriendlyUi dialog_flow(*owner,national_friendly_identity(game,manager,0x165)); + auto venue=dialog_flow.select_opponent(game,selected_team); + if(venue.kind!=ui::NationalFriendlyUiActionKind::show_question||!venue.question) { + flow.close_national_friendly_picker();return; + } + const auto backdrop=flow.render(); + auto answer=presenter(game,*venue.question,backdrop); + if(!answer) { flow.close_national_friendly_picker();return; } + const auto quote_request=dialog_flow.answer_venue(*answer); + if(quote_request.kind!=ui::NationalFriendlyUiActionKind::quote||!quote_request.engine_owner) { + flow.close_national_friendly_picker();return; + } + const auto quote=FriendlyActions(session).national_quote(*quote_request.engine_owner,selected_team,quote_request.manager_home); + if(quote.terms.status!=FriendlyQuoteStatus::quoted) { flow.close_national_friendly_picker();return; } + if(quote.terms.opponent_manager>=0) + dialog_flow.set_opponent_manager_identity( + national_friendly_identity(game,quote.terms.opponent_manager,selected_team)); + auto action=dialog_flow.accept_quote(game,quote); + while(action.kind==ui::NationalFriendlyUiActionKind::show_question&&action.question) { + answer=presenter(game,*action.question,backdrop); + if(!answer) { flow.close_national_friendly_picker();return; } + if(dialog_flow.stage()==ui::NationalFriendlyUiStage::cost_question) + action=dialog_flow.answer_cost(game,*answer); + else if(dialog_flow.stage()==ui::NationalFriendlyUiStage::payer_question) + action=dialog_flow.answer_payer(*answer); + else { flow.close_national_friendly_picker();return; } + } + const auto booking=dialog_flow.booking_template(); + if(action.kind!=ui::NationalFriendlyUiActionKind::open_calendar||!booking) { + flow.close_national_friendly_picker();return; + } + ui::FriendlyQuoteProjection projection; + projection.request_id=quote_request.engine_owner->request_id; + projection.revision=revision;projection.manager_slot=manager;projection.runtime_team=0x165; + projection.opponent=selected_team;projection.opponent_manager=quote.terms.opponent_manager; + projection.payer_manager=quote.terms.payer_manager;projection.home_team=quote.terms.home_team; + projection.away_team=quote.terms.away_team;projection.cost=quote.terms.cost; + projection.planner_count=quote.terms.planner_count;projection.manager_home=quote.terms.manager_home; + projection.dates.reserve(366); + for(int day=0;day<=365;++day) { + const auto status=FriendlyActions(session).national_date_status(quote,*quote_request.engine_owner,uint16_t(day)); + ui::FriendlyDateMark mark=ui::FriendlyDateMark::unavailable; + if(status==FriendlyDateStatus::available)mark=ui::FriendlyDateMark::available; + else if(status==FriendlyDateStatus::available_with_calendar_event)mark=ui::FriendlyDateMark::available_flagged; + else if(status==FriendlyDateStatus::current_or_past&&day==game.season_day())mark=ui::FriendlyDateMark::current_day; + projection.dates.push_back({day,mark}); + } + ui::FriendlyMatchState calendar; + calendar.revision=revision;calendar.manager_slot=manager;calendar.runtime_team=0x165; + calendar.current_day=game.season_day();calendar.planner_count=quote.terms.planner_count; + calendar.season_start_counter=game.season_start;calendar.mode_three=desk.options.mode==3; + calendar.national_team=true;calendar.manager_name=ui::original_to_utf8(desk.manager_name); + calendar.leagues=ui::league_tables_from_game(game,manager); + calendar.calendar=ui::calendar_from_game(game,load_le(ui::asset_path(data,"BMH.exe"))); + try { flow.show_national_friendly_calendar(std::move(calendar),std::move(projection),*booking); } + catch(...) { flow.close_national_friendly_picker(); } + (void)data; +} + +void start_original_desk_audio(openbmh::audio::Playback& playback, const GameState& state, bool enabled) { + playback.set_original_options(original_audio_options(state, enabled)); + original_audio_command(playback, 1); // SavePathInDirectory / CareerFirstSteps2, resume the same song. +} + +bool save_path_in_directory(const fs::path& path, const fs::path& directory, + std::string_view expected_extension = ".fbm") { + if (path.filename().empty()) return false; + std::string ext = path.extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + if (ext != expected_extension) return false; + std::error_code ec; + const auto expected = fs::weakly_canonical(directory, ec); + if (ec) return false; + const auto actual = fs::weakly_canonical(path.parent_path(), ec); + return !ec && expected == actual; +} + +std::string transfer_status_message(TransferActionStatus status, ui::TransferMarketRequestKind kind) { + switch (status) { + case TransferActionStatus::accepted: + return kind == ui::TransferMarketRequestKind::list_player + ? "Der Spieler steht jetzt auf der Transferliste." : "Der Spieler hat das Angebot angenommen."; + case TransferActionStatus::pending: return "Der Spieler entscheidet sich nächste Woche."; + case TransferActionStatus::offer_too_low: return "Das Angebot ist zu niedrig."; + case TransferActionStatus::blocked_by_board: return "Der Vorstand genehmigt diesen Transfer nicht."; + case TransferActionStatus::insufficient_funds: return "Das Geld reicht für diesen Transfer nicht aus."; + case TransferActionStatus::no_squad_room: return "Im Kader ist kein Platz für diesen Spieler."; + case TransferActionStatus::rejected: return "Der Spieler hat das Angebot abgelehnt."; + default: return "Diese Transferaktion ist nicht mehr verfügbar."; + } +} + +void serve_transfer_action(ui::StartupFlow& flow, CareerSession& session, + const ui::TransferMarketRequest& request, uint64_t& revision, + const HumanBuyerSaleHooks& presenters, + HumanBuyerMarketEntryPolicy entry_policy, + const CareerSession::PoachPlayerSelector& poach_selector, const PoachNoticePresenter& poach_notice) { + const auto* pending = flow.pending_transfer_market(); + // JSON covers every offer field except its redundant nested manager identity. + // Check that identity too, before an engine helper can consume a random draw. + if (!pending || request.bid.manager != pending->bid.manager || + ui::transfer_market_request_json(request) != ui::transfer_market_request_json(*pending)) return; + const auto rejection = TransferActions(session).rejection(request, revision, entry_policy); + if (!rejection.empty()) { + flow.reject_preparation_action(rejection); + return; + } + if(request.kind==ui::TransferMarketRequestKind::open_poach) { + if(entry_policy!=HumanBuyerMarketEntryPolicy::normal_interactive) { + flow.reject_preparation_action("Die Original-Spielerauswahl ist in diesem Einstieg nicht verfügbar."); + return; + } + std::string error; + const auto backdrop=flow.render(); + const bool accepted=session.dispatch_poach_ui(request,backdrop,poach_selector, + [&](const CareerSession::PoachDispatch& result,ui::PreparationState preparation) { + if(result.editor) { + flow.show_transfer_offer(result.editor->preparation,result.editor->editor); + } else { + if(poach_notice&&!result.start.messages.empty())poach_notice(session.state(),result.start,backdrop); + std::string notice; + for(const auto& message:result.start.messages) { + if(poach_notice)break; + if(!notice.empty())notice+='\n'; + notice+=ui::original_to_utf8(message); + } + if(preparation.desktop.revision==request.revision) + flow.reject_preparation_action(std::move(notice)); + else flow.acknowledge_preparation(std::move(preparation),std::move(notice)); + } + },revision,error); + if(!accepted) { + std::fprintf(stderr,"poach: %s\n",error.c_str()); + flow.reject_preparation_action("Das Abwerben konnte nicht abgeschlossen werden."); + } + return; + } + if (request.kind == ui::TransferMarketRequestKind::open_offer) { + if (entry_policy != HumanBuyerMarketEntryPolicy::normal_interactive) { + flow.reject_preparation_action("Der Original-Angebotsdialog ist in diesem Einstieg nicht verfügbar."); + return; + } + try { + std::string error; + auto result = TransferActions(session).open_offer(request, revision, error, + [&](CareerSession::TransferOfferEditorDispatch& opened) { + flow.show_transfer_offer(std::move(opened.preparation), std::move(opened.editor)); + }); + if (!result) throw FormatError(error); + } catch (const std::exception&) { + flow.reject_preparation_action("Dieser Angebotsdialog konnte nicht geöffnet werden."); + } + return; + } + if (request.kind == ui::TransferMarketRequestKind::preview_quote) { + if (entry_policy != HumanBuyerMarketEntryPolicy::normal_interactive) { + flow.reject_preparation_action("Die Original-Transfervorschau ist in diesem Einstieg nicht verfügbar."); + return; + } + try { + std::string error; + auto result = TransferActions(session).preview(request, revision, error, + [&](CareerSession::TransferMarketPreviewDispatch& preview) { + flow.acknowledge_transfer_market_preview(std::move(preview.preparation), preview.quote); + }); + if (!result) throw FormatError(error); + } catch (const std::exception&) { + flow.reject_preparation_action("Die Transfervorschau konnte nicht übernommen werden."); + } + return; + } + try { + auto hooks = presenters; + bool source_notice_presented = false; + if (hooks.notice) { + const auto present = hooks.notice; + hooks.notice = [present, &source_notice_presented](const GameState& staged, const HumanBuyerSaleNotice& notice) { + present(staged, notice); + source_notice_presented = true; + }; + } + std::string error; + const auto outcome = TransferActions(session).market(request, hooks, revision, error, entry_policy, + [&](const TransferActions::MarketDispatch& applied) { + // Preserve the Source caller's existing notice/ACK sequence. + const bool source_finished = entry_policy == HumanBuyerMarketEntryPolicy::normal_interactive && + (source_notice_presented || applied.action.status == TransferActionStatus::pending); + auto notice = source_finished ? std::string{} : transfer_status_message(applied.action.status, request.kind); + if (!applied.changed && source_finished) flow.acknowledge_unchanged_transfer_market(); + else if (!applied.changed) flow.reject_preparation_action(std::move(notice)); + else flow.acknowledge_preparation(session.preparation_projection(revision), std::move(notice)); + }); + if (!outcome) throw FormatError(error); + } catch (const std::exception&) { + flow.reject_preparation_action("Diese Transferaktion konnte nicht übernommen werden."); + } +} + +void serve_transfer_offer(ui::StartupFlow& flow, CareerSession& session, + const ui::OutgoingTransferRequest& request, uint64_t& revision, + const HumanBuyerSaleHooks& presenters, HumanBuyerMarketEntryPolicy policy, + const TransferOfferTeamInfoPresenter& team_info_presenter, + const TransferOfferPlayerInfoPresenter& player_info_presenter) { + const auto* pending = flow.pending_transfer_offer(); + if (!pending || ui::outgoing_transfer_request_json(*pending) != ui::outgoing_transfer_request_json(request)) return; + if (policy != HumanBuyerMarketEntryPolicy::normal_interactive) { + flow.reject_transfer_offer("Der Original-Angebotsdialog ist in diesem Einstieg nicht verfügbar."); + return; + } + try { + std::string error; + auto result = TransferActions(session).offer(request, presenters, revision, error, + team_info_presenter, player_info_presenter, [&](CareerSession::TransferOfferEditorDispatch& applied) { + flow.acknowledge_transfer_offer(std::move(applied.preparation), std::move(applied.editor)); + }); + if (!result) throw FormatError(error); + } catch (const std::exception&) { + flow.reject_transfer_offer("Diese Angebotsaktion konnte nicht übernommen werden."); + } +} + +} // namespace + +// Hands the flow's engine requests to the career session. Returns a message for the +// console when something went wrong. +std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& result, std::unique_ptr& session, + const fs::path& data, const fs::path& save_directory, uint32_t seed, uint64_t& revision, + openbmh::audio::Playback& playback, std::optional& audio_session, bool music_enabled, + std::function&, const GameState&)> live_presenter, + TransferOfferPresenter transfer_presenter, + TransferDecisionPresenter transfer_decision_presenter, SeasonPresenter season_presenter, + SeasonTaxHooks tax_presenter, SeasonHighscoreHook highscore_presenter, + SeasonPromotionHook promotion_presenter, SeasonCupDrawHook cup_draw_presenter, + PendingOfferHooks pending_offer_presenter, PendingOfferEntryPolicy pending_entry_policy, + HumanBuyerSaleHooks market_sale_presenter, HumanBuyerMarketEntryPolicy market_entry_policy, + TransferOfferTeamInfoPresenter team_info_presenter, + TransferOfferPlayerInfoPresenter player_info_presenter, + ConstructionNoticeHook construction_notice_presenter, + SeasonTicketCompensationNoticeHook compensation_notice_presenter, + SportschauPresentationHooks sportschau_presenter, + AdvertisingRenewalPresenter advertising_renewal_presenter, + CareerSession::PoachPlayerSelector poach_player_selector, + PoachNoticePresenter poach_notice_presenter, + ContractExpiryPresenter contract_expiry_presenter, + NationalFriendlyQuestionPresenter national_friendly_question_presenter, + LoanReturnPresenter loan_return_presenter, + LoanReturnOfferPresenter loan_return_offer_presenter, + LiveInterventionPresenter live_intervention_presenter, + EnvironmentNoticePresenter environment_notice_presenter, + LiveMatchEventPresenter live_match_event_presenter, + LiveBallPresenter live_ball_presenter, + LiveChancePresenter live_chance_presenter, + LiveShotPresenter live_shot_presenter, + LiveSetPiecePresenter live_set_piece_presenter, + LiveBookingPresenter live_booking_presenter, + LiveShootoutPresenter live_shootout_presenter, + LiveRealityPresenter live_reality_presenter, + PhaseResultPresenter phase_result_presenter, bool enable_autosave) { + std::string error; + if (enable_autosave && session) session->configure_autosave_directory(save_directory); + if(session&&session->opportunities_active()&&result.request!=ui::FlowRequest::none&& + result.request!=ui::FlowRequest::opportunities_action&& + result.request!=ui::FlowRequest::statistics_menu_action&& + result.request!=ui::FlowRequest::statistics_page_action) + return "opportunities: another session action is blocked while the Source owner is open"; + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==5) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + const auto underlay=flow.desktop()->render(); + auto page=OtherGamesActions(*session).open(result.desk_action,revision,underlay,error, + [&](ui::OtherGamesState& opened) { + const auto& desk=flow.desktop()->state(); + if(opened.identity.manager_slot!=desk.manager_slot|| + opened.identity.runtime_team!=desk.runtime_club|| + opened.identity.day_counter!=desk.day_counter||desk.manager_slot<0|| + size_t(desk.manager_slot)>=desk.managers.size()|| + opened.identity.club_identity!=desk.managers[size_t(desk.manager_slot)].club_identity_key) + throw FormatError("other games: stale desktop identity"); + flow.show_other_games(std::move(opened),session->preparation_projection(revision),result.desk_action); + }); + if(!page)flow.reject_desk_action(error); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::other_games_action&&session) { + const auto* pending=flow.pending_other_games_action(); + if(!pending||*pending!=result.other_games_action)return {}; + try { + auto applied=OtherGamesActions(*session).dispatch(result.other_games_action,revision,error,team_info_presenter, + [&](CareerSession::OtherGamesDispatch& action) { + if(action.closed)flow.close_other_games(std::move(action.page),std::move(action.preparation)); + else flow.acknowledge_other_games(std::move(action.page),std::move(action.preparation)); + }); + if(!applied) { + flow.reject_other_games(error); + } + } catch(const std::exception& e) { + if(flow.pending_other_games_action())flow.reject_other_games(e.what()); + return e.what(); + } + return error; + } + if(session&&session->other_games_active()&&result.request!=ui::FlowRequest::none) + return "other games: another session action is blocked while the Source owner is open"; + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==23) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + flow.show_statistics_menu(result.desk_action, + source_transfer_history_count(session->state(),result.desk_action.manager_slot)); + // StatisticsMenuScreen enters the normal statistics page at index 7, whose + // StatisticsRankingsFromGame child starts at local category 0. + try { + const auto underlay=flow.statistics_menu()->render_page(7); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto projection=ui::statistics_rankings_from_game(session->state(),exe, + result.desk_action.manager_slot,0,0,underlay); + flow.show_statistics_rankings(std::move(projection)); + } catch(const std::exception& e) { + flow.close_statistics_menu(); + return e.what(); + } + return {}; + } + if(result.request==ui::FlowRequest::statistics_menu_action&&session) { + const auto* pending=flow.pending_statistics_menu(); + if(!pending||*pending!=result.statistics_menu_action)return {}; + if(flow.national_friendly_family_active()&& + !valid_national_friendly_family(flow,session->state(),revision)) { + flow.close_statistics_menu();return {}; + } + if(pending->close) { flow.close_statistics_menu();return {}; } + // Parent selector actions remain live above either implemented child. + // Closing A-D uses the same typed Source close transaction as its right-click path. + const auto menu_request=*pending; + if((menu_request.selected_index==1||menu_request.selected_index==2||(menu_request.selected_index>=3&&menu_request.selected_index<=8))&&session->opportunities_active()) { + if(!flow.opportunities()||flow.opportunities()->pending()||!flow.statistics_menu()|| + menu_request.owner!=flow.statistics_menu()->state().owner|| + !flow.desktop()||menu_request.owner.revision!=flow.desktop()->state().revision) { + flow.reject_statistics_menu("Der Statistikwechsel ist veraltet.");return {}; + } + try { + OpportunitiesActions(*session).apply(revision, [&] { + std::optional history; + std::optional minutes; + std::optional transfers; + std::optional analytics; + std::optional alltime; + std::optional worldcup; + std::optional finance; + std::optional series; + if(menu_request.selected_index==2) { + const auto underlay=flow.statistics_menu()->render_page(2); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + analytics=ui::analytics_from_game(session->state(),exe,menu_request.owner.manager_slot,underlay); + analytics->owner=menu_request.owner; + ui::AnalyticsScreen staged(data,*analytics); + } else if(menu_request.selected_index==7) { + const auto underlay=flow.statistics_menu()->render_page(7); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + history=ui::statistics_rankings_from_game(session->state(),exe, + menu_request.owner.manager_slot,0,0,underlay); + ui::StatisticsRankingsScreen staged(data,*history); + } else if(menu_request.selected_index==8) { + minutes=ui::minute_statistics_from_game(session->state(),menu_request.owner.manager_slot); + ui::MinuteStatisticsScreen staged(data,*minutes); + } else if(menu_request.selected_index==3) { + alltime=ui::alltime_table_from_game(session->state(),load_le(ui::asset_path(data,"BMH.exe")), + menu_request.owner,flow.statistics_menu()->render_page(3)); + ui::AllTimeTableScreen staged(data,*alltime); + } else if(menu_request.selected_index==4) { + worldcup=ui::world_cup_statistics_from_game(session->state(),load_le(ui::asset_path(data,"BMH.exe")), + flow.national_friendly_family_active() ? ui::WorldCupStatisticsOwner::friendly_match_nation_picker : + ui::WorldCupStatisticsOwner::desk_read_only); + ui::WorldCupStatisticsScreen staged(data,*worldcup,flow.statistics_menu()->render_page(4)); + } else if(menu_request.selected_index==5) { + finance=ui::finance_totals_from_game(session->state(),menu_request.owner.manager_slot); + ui::FinanceTotalsScreen staged(data,*finance,flow.statistics_menu()->render_page(5)); + } else if(menu_request.selected_index==6) { + series=ui::series_records_from_game(session->state(),load_le(ui::asset_path(data,"BMH.exe")),menu_request.owner.manager_slot); + ui::SeriesRecordsScreen staged(data,*series,flow.statistics_menu()->render_page(6)); + } else { + const int count=source_transfer_history_count(session->state(),menu_request.owner.manager_slot); + const int origin=source_transfer_history_origin(count); + const auto underlay=flow.statistics_menu()->render_page(1); + transfers=ui::transfer_history_from_game(session->state(),menu_request.owner.manager_slot); + ui::TransferHistoryScreen staged(data,session->state(),*transfers); + (void)staged.render(underlay,origin); + } + const auto child=flow.opportunities()->state(); + const auto close=OpportunitiesActions::close_request(child); + auto applied=OpportunitiesActions(*session).dispatch(close,revision,error); + if(!applied||!applied->closed)throw FormatError(error.empty()?"A-D konnte nicht geschlossen werden.":error); + flow.close_opportunities_for_statistics_parent(std::move(applied->page),std::move(applied->preparation)); + if(analytics) { + analytics->owner=flow.statistics_menu()->state().owner; + flow.show_analytics(std::move(*analytics)); + } + else if(alltime) { + alltime->owner=flow.statistics_menu()->state().owner; + alltime->underlay=flow.statistics_menu()->render_page(3); + flow.show_alltime_table(std::move(*alltime)); + } + else if(worldcup)flow.show_world_cup_statistics(std::move(*worldcup)); + else if(finance)flow.show_finance_totals(std::move(*finance)); + else if(series)flow.show_series_records(std::move(*series)); + else if(history)flow.show_statistics_rankings(std::move(*history)); + else if(minutes)flow.show_minute_statistics(std::move(*minutes)); + else flow.show_transfer_history(std::move(*transfers),session->state(), + source_transfer_history_origin(source_transfer_history_count(session->state(),menu_request.owner.manager_slot))); + return true; + }); + } catch(const std::exception& e) { + if(flow.pending_statistics_menu())flow.reject_statistics_menu(e.what()); + return e.what(); + } + return error; + } + const bool opening_owner=flow.desktop()&&pending->owner.revision==revision&& + ((flow.desktop()->pending()&&*flow.desktop()->pending()==pending->owner)|| + (!flow.desktop()->pending()&&flow.desktop()->state().revision==revision)); + if((pending->selected_index<0||pending->selected_index>8)||!opening_owner) { + flow.reject_statistics_menu("Diese Statistikaktion konnte nicht zugeordnet werden."); + return {}; + } + if(!flow.desktop()||pending->owner.revision!=revision)return {}; + if(menu_request.selected_index==2) { + if(flow.desktop()->state().manager_slot!=pending->owner.manager_slot) { + flow.reject_statistics_menu("Die Analytics-Ansicht ist veraltet.");return {}; + } + try { + const auto underlay=flow.statistics_menu()->render_page(2); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto projection=ui::analytics_from_game(session->state(),exe,pending->owner.manager_slot,underlay); + projection.owner=pending->owner; + flow.show_analytics(std::move(projection)); + } catch(const std::exception& e) { + if(flow.pending_statistics_menu())flow.reject_statistics_menu(e.what()); + return e.what(); + } + return {}; + } + if(menu_request.selected_index==1) { + try { + const int count=source_transfer_history_count(session->state(),menu_request.owner.manager_slot); + auto projection=ui::transfer_history_from_game(session->state(),menu_request.owner.manager_slot); + const auto underlay=flow.statistics_menu()->render_page(1); + ui::TransferHistoryScreen staged(data,session->state(),projection); + (void)staged.render(underlay,source_transfer_history_origin(count)); + flow.show_transfer_history(std::move(projection),session->state(),source_transfer_history_origin(count)); + } catch(const std::exception& e) { + flow.reject_statistics_menu(e.what());return e.what(); + } + return {}; + } + if(menu_request.selected_index==8) { + if(flow.in_statistics_rankings())flow.close_statistics_rankings(); + try { + auto projection=ui::minute_statistics_from_game(session->state(),menu_request.owner.manager_slot); + flow.show_minute_statistics(std::move(projection)); + } catch(const std::exception& e) { + flow.reject_statistics_menu(e.what());return e.what(); + } + return {}; + } + if(menu_request.selected_index>=3&&menu_request.selected_index<=6) { + try { + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + if(menu_request.selected_index==3) { + auto state=ui::alltime_table_from_game(session->state(),exe,menu_request.owner, + flow.statistics_menu()->render_page(3)); + ui::AllTimeTableScreen staged(data,state); + flow.show_alltime_table(std::move(state)); + } else if(menu_request.selected_index==4) { + auto state=ui::world_cup_statistics_from_game(session->state(),exe, + flow.national_friendly_family_active() ? ui::WorldCupStatisticsOwner::friendly_match_nation_picker : + ui::WorldCupStatisticsOwner::desk_read_only); + ui::WorldCupStatisticsScreen staged(data,state,flow.statistics_menu()->render_page(4)); + flow.show_world_cup_statistics(std::move(state)); + } else if(menu_request.selected_index==5) { + auto state=ui::finance_totals_from_game(session->state(),menu_request.owner.manager_slot); + ui::FinanceTotalsScreen staged(data,state,flow.statistics_menu()->render_page(5)); + flow.show_finance_totals(std::move(state)); + } else { + auto state=ui::series_records_from_game(session->state(),exe,menu_request.owner.manager_slot); + ui::SeriesRecordsScreen staged(data,state,flow.statistics_menu()->render_page(6)); + flow.show_series_records(std::move(state)); + } + } catch(const std::exception& e) { + if(flow.pending_statistics_menu())flow.reject_statistics_menu(e.what()); + return e.what(); + } + return {}; + } + if(menu_request.selected_index==7) { + if(flow.in_opportunities())return {}; + if(flow.in_statistics_rankings())flow.close_statistics_rankings(); + try { + const auto underlay=flow.statistics_menu()->render_page(7); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto projection=ui::statistics_rankings_from_game(session->state(),exe, + pending->owner.manager_slot,0,0,underlay); + flow.show_statistics_rankings(std::move(projection)); + } catch(const std::exception& e) { + flow.reject_statistics_menu(e.what()); + return e.what(); + } + return {}; + } + if(flow.in_statistics_rankings())flow.close_statistics_rankings(); + try { + const auto owner=pending->owner; + const auto underlay=flow.statistics_menu()->render_page(0); + const bool national_source_case=flow.national_friendly_family_active(); + const int stable_identity=national_source_case&&flow.desktop()&& + owner.manager_slot>=0&&size_t(owner.manager_slot)state().managers.size()? + flow.desktop()->state().managers[size_t(owner.manager_slot)].club_identity_key:-1; + auto page=OpportunitiesActions(*session).open(owner,revision,underlay,error, + national_source_case,stable_identity,[&](ui::OpportunitiesState& opened) { + const auto& desk=flow.desktop()->state(); + if(opened.identity.manager_slot!=desk.manager_slot||opened.identity.runtime_team!=desk.runtime_club|| + opened.identity.day_counter!=desk.day_counter||desk.manager_slot<0|| + size_t(desk.manager_slot)>=desk.managers.size()|| + opened.identity.stable_club_identity!=int(desk.managers[size_t(desk.manager_slot)].club_identity_key)) + throw FormatError("opportunities: stale desktop identity"); + flow.show_opportunities(std::move(opened),session->preparation_projection(revision),owner); + }); + if(!page)flow.reject_statistics_menu(error); + } catch(const std::exception& e) { + if(flow.pending_statistics_menu())flow.reject_statistics_menu(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::statistics_page_action&&session) { + const auto* pending=flow.pending_statistics_page_action(); + if(!pending||*pending!=result.statistics_page_action||!flow.in_statistics_page()|| + !flow.statistics_menu()||pending->owner!=flow.statistics_menu()->state().owner|| + !flow.desktop()||pending->owner.revision!=flow.desktop()->state().revision|| + pending->owner.manager_slot!=flow.desktop()->state().manager_slot)return {}; + if(flow.national_friendly_family_active()&& + !valid_national_friendly_family(flow,session->state(),revision)) { + flow.close_statistics_menu();return {}; + } + if(pending->kind==ui::StatisticsPageActionKind::close) { + flow.close_statistics_page(); + return {}; + } + if(pending->kind!=ui::StatisticsPageActionKind::alltime||pending->page!=3||!flow.in_statistics_page())return {}; + try { + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto state=ui::alltime_table_from_game(session->state(),exe,pending->owner, + flow.statistics_menu()->render_page(3),pending->nation,pending->relative); + flow.show_alltime_table(std::move(state)); + } catch(const std::exception&) { + flow.close_statistics_page(); + } + return {}; + } + if(result.request==ui::FlowRequest::statistics_rankings_action&&session) { + const auto* pending=flow.pending_statistics_rankings(); + if(!pending||*pending!=result.statistics_rankings_action|| + pending->kind!=ui::StatisticsRankingsRequestKind::select_category||!flow.statistics_rankings())return {}; + try { + const auto& prior=flow.statistics_rankings()->state(); + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto next=ui::statistics_rankings_from_game(session->state(),exe,prior.manager_slot, + pending->category,0,prior.underlay); + flow.acknowledge_statistics_rankings(std::move(next)); + } catch(const std::exception&) { flow.reject_statistics_rankings(); } + return {}; + } + if(result.request==ui::FlowRequest::analytics_action&&session) { + const auto* pending=flow.pending_analytics(); + if(!pending||*pending!=result.analytics_action||!flow.analytics()||!flow.statistics_menu()|| + pending->owner!=flow.analytics()->state().owner||pending->manager_slot!=pending->owner.manager_slot|| + pending->owner!=flow.statistics_menu()->state().owner)return {}; + if(pending->kind==ui::AnalyticsRequestKind::close) { flow.close_analytics();return {}; } + try { + if(!OpportunitiesActions(*session).preference(*pending,revision,error,[&] { + const auto underlay=flow.analytics()->state().underlay; + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto accepted=ui::analytics_from_game(session->state(),exe,pending->manager_slot,underlay); + accepted.owner=pending->owner;accepted.owner.revision=revision; + flow.acknowledge_analytics(std::move(accepted),session->preparation_projection(revision)); + })) { + flow.reject_analytics(); + return error; + } + } catch(const std::exception& e) { + if(flow.pending_analytics())flow.reject_analytics(); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::opportunities_action&&session) { + const auto* pending=flow.pending_opportunities(); + if(!pending||*pending!=result.opportunities_action)return {}; + try { + auto applied=OpportunitiesActions(*session).dispatch(result.opportunities_action,revision,error, + [&](CareerSession::OpportunitiesDispatch& action) { + if(action.closed) { + const bool source_parent=flow.in_statistics_menu(); + const bool national_family=flow.national_friendly_family_active(); + flow.close_opportunities(std::move(action.page),std::move(action.preparation)); + if(national_family) { + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto projection=ui::world_cup_statistics_from_game(session->state(),exe, + ui::WorldCupStatisticsOwner::friendly_match_nation_picker); + flow.show_world_cup_statistics(std::move(projection)); + } else if(source_parent)flow.close_statistics_menu(); + } else flow.acknowledge_opportunities(std::move(action.page),std::move(action.preparation)); + }); + if(!applied)flow.reject_opportunities(error); + } catch(const std::exception& e) { + if(flow.pending_opportunities())flow.reject_opportunities(e.what());return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==20) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + const auto underlay=flow.desktop()->render(); + auto page=TopScorersActions(*session).open(result.desk_action,revision,underlay,error, + [&](ui::TopScorersState& opened) { + const auto& desk=flow.desktop()->state(); + if(opened.identity.manager_slot!=desk.manager_slot|| + opened.identity.runtime_team!=desk.runtime_club|| + opened.identity.day_counter!=desk.day_counter|| + desk.manager_slot<0|| + size_t(desk.manager_slot)>=desk.managers.size()|| + opened.identity.club_identity!=desk.managers[size_t(desk.manager_slot)].club_identity_key) + throw FormatError("top scorers: stale desktop identity"); + flow.show_top_scorers(std::move(opened),session->preparation_projection(revision),result.desk_action); + }); + if(!page)flow.reject_desk_action(error); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&& + (result.desk_action.menu_kind==25||result.desk_action.menu_kind==26)) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + const auto underlay=flow.desktop()->render(); + ui::DeskRecordsState page; + std::optional ranked_file; + HighscoreTable ranked_rows{}; + if(result.desk_action.menu_kind==25) { + const int manager=result.desk_action.manager_slot; + const auto& game=session->state(); + if(manager<0||size_t(manager)>=game.manager_teams.size()|| + !game.memory.has(::bmh::layout::ActiveManager)||game.memory.u8(::bmh::layout::ActiveManager)!=manager|| + size_t(manager+1)*0xb0c>game.manager_records.size()) + throw FormatError("fair play: invalid active manager"); + const int team=game.manager_teams[size_t(manager)]; + if(team!=kNoTeam&&(team<0||size_t(team)>=game.team_flags.size())) + throw FormatError("fair play: active manager has no Source roster"); + const int league=team>0x164?0:team_league(team); + page=ui::fair_play_state_from_game(game,league,underlay,manager); + } else { + page.kind=ui::DeskRecordKind::highscore; + const auto& game=session->state(); + const int manager=result.desk_action.manager_slot; + if(manager<0||size_t(manager)>=game.manager_teams.size()|| + !game.memory.has(::bmh::layout::ActiveManager)||game.memory.u8(::bmh::layout::ActiveManager)!=manager|| + size_t(manager+1)*0xb0c>game.manager_records.size()) + throw FormatError("highscore: invalid active manager/roster owner"); + const int team=game.manager_teams[size_t(manager)]; + if(team!=kNoTeam&&(team<0||size_t(team)>=game.team_flags.size())) + throw FormatError("highscore: active manager has no Source roster"); + const size_t name_at=size_t(manager)*0xb0c+0xa8; + size_t name_length=0; + while(name_length<30&&game.manager_records[name_at+name_length])++name_length; + if(name_length==30)throw FormatError("highscore: unterminated active manager name"); + page.manager_name.assign(reinterpret_cast(game.manager_records.data()+name_at),name_length); + page.highscore.signature=game.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7); + page.highscore.ranked=page.highscore.signature!=0; + page.highscore.rows={}; + if(page.highscore.ranked) { + auto texts=load_textd(ui::asset_path(data,"TEXTD.BLK")); + const auto file=highscore_file(save_directory,page.highscore.signature,texts.strings.at(889)); + HighscoreTable rows{}; + if(fs::exists(file))rows=load_highscore_table(file); + page.highscore=make_highscore_projection(game,std::move(rows),HighscoreContext::ActiveManager); + ranked_file=file; + ranked_rows=page.highscore.rows; + } else { + page.highscore=make_highscore_projection(game); + + } + page.underlay=underlay; + } + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + const auto& game=session->state(); + const auto source_byte=[&](uint32_t at){return game.memory.has(at)?game.memory.u8(at):exe.u8(at);}; + page.decorated_background=source_byte(::bmh::layout::PlainBackground)==0; + page.gradient_text=source_byte(::bmh::layout::TextGradientDisabled)==0&&source_byte(::bmh::layout::TextGradientMode)==2; + flow.show_desk_records(std::move(page),result.desk_action); + if(ranked_file) { + std::error_code directory_error; + fs::create_directories(ranked_file->parent_path(),directory_error); + if(!directory_error)(void)save_highscore_table(*ranked_file,ranked_rows); + } + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return {}; + } + if(result.request==ui::FlowRequest::top_scorers_action&&session) { + const auto* pending=flow.pending_top_scorers(); + if(!pending||*pending!=result.top_scorers_action)return {}; + try { + auto applied=TopScorersActions(*session).dispatch(result.top_scorers_action,revision,error, + [&](CareerSession::TopScorersDispatch& action) { + if(action.closed)flow.close_top_scorers(std::move(action.page),std::move(action.preparation)); + else flow.acknowledge_top_scorers(std::move(action.page),std::move(action.preparation)); + }); + if(!applied) { + flow.reject_top_scorers(error); + } + } catch(const std::exception& e) { + if(flow.pending_top_scorers())flow.reject_top_scorers(e.what()); + return e.what(); + } + return error; + } + if(session&&session->top_scorers_active()&&result.request!=ui::FlowRequest::none) + return "top scorers: another session action is blocked while the read-only owner is open"; + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==28) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + const auto underlay=flow.desktop()->render(); + auto page=BalanceActions(*session).open(result.desk_action,revision,underlay,error, + [&](ui::BalanceState& opened) { flow.show_balance(std::move(opened),result.desk_action); }); + if(!page)flow.reject_desk_action(error); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::balance_action&&session) { + const auto* pending=flow.pending_balance(); + if(!pending||*pending!=result.balance_action)return {}; + try { + auto applied=BalanceActions(*session).dispatch(result.balance_action,revision,error, + [&](CareerSession::BalanceDispatch& action) { + if(action.closed)flow.close_balance(std::move(action.page),std::move(action.preparation)); + else flow.acknowledge_balance(std::move(action.page)); + }); + if(!applied) { + flow.reject_balance(error); + } + } catch(const std::exception& e) { + if(flow.pending_balance())flow.reject_balance(e.what()); + return e.what(); + } + return error; + } + if(session&&session->balance_active()&&result.request!=ui::FlowRequest::none) + return "balance: another session action is blocked while the Bilanz owner is open"; + const auto show_table_dispatch = [&](const CareerSession::LeagueTableDispatch& applied, + std::optional preparation = {},bool friendly_entry=false) { + const auto& id = applied.identity; + if (!session || id.manager < 0 || id.manager > 3 || id.league < 0 || id.league >= 9 || + id.revision != revision || applied.page.manager_slot != id.manager || + applied.page.league_id != id.league || !applied.page.source_controls_projection) + throw FormatError("league family: invalid authoritative Table projection"); + std::optional dialog_stage; + using Phase = CareerSession::TableDispatchPhase; + if (applied.phase == Phase::range_start) dialog_stage = ui::TableDialogStage::start; + else if (applied.phase == Phase::range_end) dialog_stage = ui::TableDialogStage::end; + else if (applied.phase != Phase::ready && applied.phase != Phase::forecast_pending_present) + throw FormatError("league family: invalid Table dispatch phase"); + if (applied.dialog.has_value() != dialog_stage.has_value()) + throw FormatError("league family: mismatched Table dialog profile"); + if (!preparation && flow.desktop() && flow.desktop()->state().revision != id.revision) + preparation = session->preparation_projection(revision); + auto tables = ui::league_tables_from_game(session->state(), id.manager); + tables[size_t(id.league)] = applied.page; + flow.show_family_table_dispatch(std::move(tables), id.league, id, applied.dialog, + dialog_stage, applied.phase == Phase::forecast_pending_present, std::move(preparation),friendly_entry); + }; + if(result.request==ui::FlowRequest::league_family_action&&session) { + const auto& action=result.league_family_action; + const auto& owner=flow.league_family_identity(); + const auto session_family=session->league_family_owner(); + if(!flow.desktop()||!owner||action.from_child<1||action.from_child>3|| + !session_family||session_family->child!=action.from_child||session_family->identity!=action.identity|| + action.identity!=*owner||flow.league_family_child()!=action.from_child|| + action.identity.revision!=revision) + return "league family: stale child request"; + if(session_family->friendly_opponent!=flow.friendly_table_active()|| + (session_family->friendly_opponent&&action.kind!=ui::LeagueFamilyRequestKind::control&& + action.kind!=ui::LeagueFamilyRequestKind::table_range_result&& + action.kind!=ui::LeagueFamilyRequestKind::table_forecast_presented&& + action.kind!=ui::LeagueFamilyRequestKind::select_league&& + action.kind!=ui::LeagueFamilyRequestKind::toggle_league_group&& + action.kind!=ui::LeagueFamilyRequestKind::select_opponent&& + action.kind!=ui::LeagueFamilyRequestKind::close)) + return "friendly table: invalid owner purpose or action"; + if(action.kind==ui::LeagueFamilyRequestKind::select_opponent) { + const auto* pending=flow.pending_league_family_action(); + if(!session_family->friendly_opponent||!pending||*pending!=action) + return "friendly table: opponent is not the pending UI row"; + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto opponent=session->resolve_friendly_table_opponent(action,revision,error); + if(!opponent)throw FormatError(error.empty()?"friendly table: opponent rejected":error); + if(*opponent==action.identity.runtime_club) { + const auto retained=session->acknowledge_friendly_own_club(action,revision,error); + if(!retained)throw FormatError(error.empty()?"friendly table: own-club return rejected":error); + flow.acknowledge_friendly_own_club(action,*retained);return true; + } + const auto visible=session->current_league_table_dispatch(error); + if(!visible)throw FormatError(error); + auto preparation=session->finish_friendly_opponent_table(action,revision,error); + if(!preparation)throw FormatError(error.empty()?"friendly table: return rejected":error); + auto friendly=club_friendly_state(*session,preparation->desktop,data,revision); + friendly.selected_opponent=*opponent;friendly.selected_league=action.identity.league; + // Preserve the final visible Source table below venue/cost questions. + friendly.leagues[size_t(action.identity.league)]=visible->page; + flow.complete_friendly_opponent_table(action,std::move(friendly),std::move(*preparation)); + return true; + }); + } catch(const std::exception& e) { + flow.reject_league_family(e.what());return e.what(); + } + return {}; + } + if (action.from_child == 1 && (action.kind == ui::LeagueFamilyRequestKind::control || + action.kind == ui::LeagueFamilyRequestKind::table_range_result || + action.kind == ui::LeagueFamilyRequestKind::table_forecast_presented)) { + const auto* pending = flow.pending_league_family_action(); + if (!pending || *pending != action) + return "league family: Table request is not the pending UI action"; + + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + std::optional applied; + if (action.kind == ui::LeagueFamilyRequestKind::control) + applied = session->dispatch_league_table_control(action, revision, error); + else if (action.kind == ui::LeagueFamilyRequestKind::table_range_result) + applied = session->dispatch_league_table_range_reply(action, revision, error); + else applied = session->acknowledge_league_forecast_present(action, revision, error); + if (!applied) throw FormatError(error.empty() ? "league family: Table action rejected" : error); + show_table_dispatch(*applied); + return true; + }); + } catch (const std::exception& e) { + flow.reject_league_family(e.what()); + return e.what(); + } + return {}; + } + if(action.kind==ui::LeagueFamilyRequestKind::team_info&&action.from_child==1) { + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto returned=session->dispatch_family_table_team_info(action,revision,error,team_info_presenter); + if(!returned)throw FormatError(error.empty()?"league family Table TeamInfo rejected":error); + const auto table = session->current_league_table_dispatch(error); + if (!table || table->identity != *returned) + throw FormatError(error.empty() ? "league family: missing Table TeamInfo return" : error); + auto preparation=session->preparation_projection(revision); + show_table_dispatch(*table, std::move(preparation)); + return true; + }); + } catch(const std::exception& e) { + flow.reject_league_family(e.what());return e.what(); + } + return {}; + } + if(action.kind==ui::LeagueFamilyRequestKind::close) { + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto* pending=flow.pending_league_family_action(); + if(session_family->friendly_opponent&&(!pending||*pending!=action)) + throw FormatError("friendly table: close is not the pending UI action"); + auto preparation=session_family->friendly_opponent + ?session->finish_friendly_opponent_table(action,revision,error) + :session->close_league_family(action,revision,error); + if(!preparation) { + flow.reject_league_family(error.empty()?"league family close rejected":error); return false; + } else flow.close_league_family(action,std::move(*preparation)); + return true; + }); + } catch(const std::exception& e) { + if(flow.league_family_identity())flow.reject_league_family(e.what()); + return e.what(); + } + return error; + } + if((action.kind==ui::LeagueFamilyRequestKind::select_league|| + action.kind==ui::LeagueFamilyRequestKind::toggle_league_group)&&action.from_child==1) { + const auto* pending=flow.pending_league_family_action(); + if(!pending||*pending!=action) + return "league family: selector request is not the pending UI action"; + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + if(!session->select_league_family_page(action,revision,error)) + throw FormatError(error.empty()?"league family selector rejected":error); + const auto table=session->current_league_table_dispatch(error); + const bool toggle=action.kind==ui::LeagueFamilyRequestKind::toggle_league_group; + const uint8_t expected_group=toggle?uint8_t(action.identity.league_group^1):action.identity.league_group; + if(!table||table->identity.league!=action.league_id|| + table->identity.league_group!=expected_group|| + table->identity.manager!=action.identity.manager|| + table->identity.runtime_club!=action.identity.runtime_club|| + table->identity.club_identity!=action.identity.club_identity|| + table->identity.day_counter!=action.identity.day_counter|| + table->identity.manager_default_league!=action.identity.manager_default_league|| + table->identity.source_param2!=action.identity.source_param2|| + table->identity.scope!=action.identity.scope|| + table->identity.sequence!=action.identity.sequence|| + table->identity.family_id!=action.identity.family_id|| + table->identity.family_sequence!=action.identity.family_sequence+1|| + table->identity.revision!=action.identity.revision) + throw FormatError(error.empty()?"league family: selector result does not match its bound operation":error); + const bool league_changed=table->identity.league!=action.identity.league; + if(league_changed) show_table_dispatch(*table); + else flow.acknowledge_family_selector(action,table->identity); + return true; + }); + } catch(const std::exception& e) { + flow.reject_league_family(e.what());return e.what(); + } + return {}; + } + + if(action.kind==ui::LeagueFamilyRequestKind::navigate&&flow.league_family_child()==action.from_child&& + (action.target_child==1||action.target_child==2||action.target_child==3)) { + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + bool suspended=false; + if(action.from_child==3)suspended=session->suspend_strengths_for_family(action,revision,error); + else if(action.from_child==2)suspended=session->suspend_pairings_for_family(action,revision,error); + else suspended=action.from_child==1; + if(!suspended)throw FormatError(error.empty()?"league family child transition rejected":error); + const auto fresh=session->strengths_open_request(revision); + if(!fresh)throw FormatError("league family: missing fresh manager projection"); + auto identity=fresh->identity; + identity.family_id=action.identity.family_id; + identity.family_sequence=action.identity.family_sequence+1; + identity.league=action.identity.league; + identity.league_group=action.identity.league_group; + identity.manager_default_league=action.identity.manager_default_league; + identity.source_param2=action.identity.source_param2; + if(action.target_child==1) { + if(!session->prepare_league_family_child(identity,1,revision,error)) + throw FormatError(error.empty()?"league family Table entry rejected":error); + identity.expected_family_word=session->state().memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2); + if(!session->advance_league_family(action,identity,1,revision,error)) + throw FormatError(error.empty()?"league family Table handoff rejected":error); + const auto table = session->current_league_table_dispatch(error); + if (!table) throw FormatError(error.empty() ? "league family: missing Table entry projection" : error); + show_table_dispatch(*table); + } else if(action.target_child==2) { + if(!session->prepare_league_family_child(identity,2,revision,error)) + throw FormatError(error.empty()?"league family Pairings entry rejected":error); + identity.expected_family_word=session->state().memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2); + const auto open=LeagueFamilyActions::pairings_entry(identity,revision); + auto page=session->open_league_pairings(open,revision,error); + if(!page)throw FormatError(error.empty()?"league family Pairings projection rejected":error); + if(page->identity.league!=identity.league) { + const auto select=LeagueFamilyActions::pairings_selection(page->identity,identity.league); + auto selected=session->dispatch_league_pairings(select,revision,error); + if(!selected||selected->closed)throw FormatError(error.empty()?"league family Pairings selection rejected":error); + page=std::move(selected->page); + } + // Pairings' Source selector can commit one page revision while + // choosing the family's requested league before first display. + identity.revision=revision; + identity.expected_family_word=session->state().memory.u16( + ::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2); + if(!session->advance_league_family(action,identity,2,revision,error)) + throw FormatError(error.empty()?"league family Pairings handoff rejected":error); + flow.show_family_league_pairings(std::move(*page),identity); + } else { + const auto open=LeagueFamilyActions::strengths_entry(*fresh,identity); + auto page=session->dispatch_strengths(open,revision,error,{},true); + if(!page||page->closed)throw FormatError(error.empty()?"league family Strengths projection rejected":error); + if(!session->advance_league_family(action,page->page.identity,3,revision,error)) + throw FormatError(error.empty()?"league family Strengths handoff rejected":error); + flow.show_family_strengths(std::move(page->page),std::move(page->preparation)); + } + return true; + }); + } catch(const std::exception& e) { + flow.reject_league_family(e.what());return e.what(); + } + return error; + } + flow.reject_league_family("league family action is not yet supported by this owner"); + return "league family action is not yet supported by this owner"; + } + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==2) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto semantic=session->strengths_open_request(revision); + const auto& desk=flow.desktop()->state(); + if(!semantic||semantic->identity.manager!=desk.manager_slot||semantic->identity.runtime_club!=desk.runtime_club|| + semantic->identity.day_counter!=desk.day_counter||desk.manager_slot<0||size_t(desk.manager_slot)>=desk.managers.size()|| + semantic->identity.club_identity!=desk.managers[size_t(desk.manager_slot)].club_identity_key) + throw FormatError("strengths: stale desktop identity"); + const auto applied=session->dispatch_strengths(*semantic,revision,error); + if(!applied)throw FormatError(error.empty()?"league family Strengths entry rejected":error); + else { + const auto family=session->begin_league_family(applied->page.identity,3,revision,error); + if(!family)throw FormatError(error.empty()?"league family Strengths owner rejected":error); + auto page=applied->page;page.identity=*family; + flow.show_strengths(std::move(page),applied->preparation,result.desk_action); + } + return true; + }); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==0) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto& desk=flow.desktop()->state(); + const auto request=session->strengths_open_request(revision); + if(!request||request->identity.manager!=desk.manager_slot||request->identity.runtime_club!=desk.runtime_club|| + request->identity.day_counter!=desk.day_counter) + throw FormatError("league family: stale Table entry identity"); + auto identity=request->identity; + if(!session->prepare_league_family_child(identity,1,revision,error)) + throw FormatError(error.empty()?"league family Table entry rejected":error); + identity.expected_family_word=session->state().memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(identity.manager)*2); + const auto bound=session->begin_league_family(identity,1,revision,error); + if(!bound)throw FormatError(error.empty()?"league family Table owner rejected":error); + const auto table = session->current_league_table_dispatch(error); + if (!table || table->identity != *bound) + throw FormatError(error.empty() ? "league family: missing bound Table projection" : error); + show_table_dispatch(*table); + return true; + }); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::strengths_action&&session) { + const auto* pending=flow.pending_strengths(); + if(!pending||*pending!=result.strengths_action)return {}; + const auto family_before=session->league_family_owner(); + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + auto applied=session->dispatch_strengths(result.strengths_action,revision,error,team_info_presenter); + if(!applied) { + flow.reject_strengths(error); return false; + } else if(applied->closed)flow.close_strengths(std::move(applied->page),std::move(applied->preparation)); + else { + if(family_before) { + if(!session->refresh_family_after_child(family_before->identity,3,applied->page.identity,revision,error)) + throw FormatError(error.empty()?"league family Strengths refresh rejected":error); + applied->page.identity=session->league_family_owner()->identity; + } + flow.acknowledge_strengths(std::move(applied->page),std::move(applied->preparation)); + } + return true; + }); + } catch(const std::exception& e) { + if(flow.pending_strengths())flow.reject_strengths(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::desk_action&&session&& + result.desk_action.kind==ui::DeskRequestKind::open_menu&&result.desk_action.menu_kind==1) { + if(!flow.desktop()||!flow.desktop()->pending()||*flow.desktop()->pending()!=result.desk_action|| + result.desk_action.revision!=revision)return {}; + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + const auto family_request=session->strengths_open_request(revision); + if(!family_request||family_request->identity.manager!=result.desk_action.manager_slot|| + family_request->identity.runtime_club!=flow.desktop()->state().runtime_club|| + family_request->identity.day_counter!=flow.desktop()->state().day_counter) + throw FormatError("league family: stale Pairings entry identity"); + if(!session->prepare_league_family_child(family_request->identity,2,revision,error)) + throw FormatError(error); + auto family_identity=family_request->identity; + family_identity.expected_family_word=session->state().memory.u16(::bmh::layout::LeagueTableDisplayModes+uint32_t(family_identity.manager)*2); + auto page=session->open_league_pairings(result.desk_action,revision,error); + if(!page)throw FormatError(error.empty()?"league family Pairings entry rejected":error); + else { + const auto bound=session->begin_league_family(family_identity,2,revision,error); + if(!bound)throw FormatError(error.empty()?"league family Pairings owner rejected":error); + family_identity=*bound; + flow.show_family_league_pairings(std::move(*page),family_identity); + } + return true; + }); + } catch(const std::exception& e) { + if(flow.desktop()&&flow.desktop()->pending())flow.reject_desk_action(e.what()); + return e.what(); + } + return error; + } + if(result.request==ui::FlowRequest::league_pairings_action&&session) { + const auto* pending=flow.pending_league_pairings(); + if(!pending||*pending!=result.league_pairings_action)return {}; + const auto family_before=session->league_family_owner(); + try { + LeagueFamilyActions(*session).apply(revision, [&]() -> bool { + auto applied=session->dispatch_league_pairings(result.league_pairings_action,revision,error,team_info_presenter); + if(!applied) { + flow.reject_league_pairings(error); return false; + } else if(applied->closed)flow.close_league_pairings(std::move(applied->preparation)); + else { + std::optional refreshed; + if(family_before) { + auto next=family_before->identity; + next.revision=revision;next.scope=applied->page.identity.scope; + next.sequence=applied->page.identity.sequence;next.league=applied->page.identity.league; + next.league_group=uint8_t(applied->page.source.owner.league_group); + if(!session->refresh_family_after_child(family_before->identity,2,next,revision,error)) + throw FormatError(error.empty()?"league family Pairings refresh rejected":error); + refreshed=session->league_family_owner()->identity; + } + flow.acknowledge_league_pairings(std::move(applied->page),refreshed); + } + return true; + }); + } catch(const std::exception& e) { + if(flow.pending_league_pairings())flow.reject_league_pairings(e.what()); + return e.what(); + } + return error; + } + if (result.request == ui::FlowRequest::desk_action && session && + result.desk_action.kind == ui::DeskRequestKind::open_menu && result.desk_action.menu_kind == 29) { + if (!flow.desktop() || !flow.desktop()->pending() || *flow.desktop()->pending() != result.desk_action || + result.desk_action.revision != revision) return {}; + try { flow.show_manager_join(session->manager_choices(revision),session->selection_context(revision)); } + catch (const std::exception&) { flow.reject_desk_action("Der neue Manager kann hier nicht angelegt werden."); } + } else if (result.request == ui::FlowRequest::join_cancel && session) { + if (!flow.join_origin() || *flow.join_origin() != result.desk_action) return {}; + session->cancel_manager_join(); flow.reject_manager_join({}); + } else if ((result.request == ui::FlowRequest::join_options || result.request == ui::FlowRequest::join_manager) && session) { + if (!flow.join_origin() || *flow.join_origin() != result.desk_action || result.desk_action.revision != revision) + return {}; + bool accepted=false; + if (result.request == ui::FlowRequest::join_options) { + const auto* pending=flow.pending_join_options(); + if (!pending || *pending != result.join_options) return {}; + accepted=session->begin_manager_join(result.desk_action,result.join_options,revision,error); + } else { + const auto* pending=flow.pending_join_manager(); + if (!pending || *pending != result.join_manager) return {}; + accepted=session->confirm_manager_join(result.join_manager,error); + } + if (!accepted) { + session->cancel_manager_join(); flow.reject_manager_join("Der neue Manager konnte nicht übernommen werden."); + return "manager join: " + error; + } + if (!session->manager_join_complete()) { + try { flow.resume_manager_join(session->manager_join_context()); } + catch (const std::exception& e) { + session->cancel_manager_join(); flow.reject_manager_join("Die Mannschaftsauswahl konnte nicht geöffnet werden."); + return "manager join: " + std::string(e.what()); + } + } else { + try { + if (!ManagerJoinActions(*session).commit(revision,error,[&](ui::CareerInitializationResult& joined) { + flow.acknowledge_manager_join(std::move(joined)); + })) { + session->cancel_manager_join(); flow.reject_manager_join("Der Spielstand konnte nicht übernommen werden."); + return "manager join: " + error; + } + } + catch (const std::exception& e) { + flow.reject_manager_join("Der Spielstand konnte nicht angezeigt werden."); + return "manager join: " + std::string(e.what()); + } + } + } else + if (result.request == ui::FlowRequest::manager_confirmed) { + if (!session) session = std::make_unique(data, seed); + if (enable_autosave) session->configure_autosave_directory(save_directory); + const ui::ManagerChoice* choice = flow.pending_manager(); + if (!choice || !session->confirm_manager(flow.options(), *choice, error)) return "manager: " + error; + flow.resume_manager_selection(session->selection_context(++revision)); + } else if (result.request == ui::FlowRequest::new_career) { + if (!session) session = std::make_unique(data, seed); + if (enable_autosave) session->configure_autosave_directory(save_directory); + const ui::NewCareerRequest* request = flow.pending_career(); + if (!request) return "no pending career"; + for (size_t m = size_t(session->confirmed()); m < request->managers.size(); m++) + if (!session->confirm_manager(request->options, request->managers[m], error)) return "manager: " + error; + ui::CareerInitializationResult init; + // Initial setup reaches the same native draw boundaries as annual turns. + // Scope presentation hooks to this request, including failure paths. + struct InitialHookReset { + CareerSession* session; + ~InitialHookReset() { + session->set_season_pause({}); + session->set_season_cup_draw({}); + } + } initial_reset{session.get()}; + session->set_season_pause(season_presenter); + session->set_season_cup_draw(cup_draw_presenter); + if (!session->finish(init, error)) return "career: " + error; + playback.reset_session(session->session_id()); + audio_session = session->session_id(); + revision = init.desktop.revision; + auto preparation = std::move(init.preparation); + flow.attach_initialized_career(std::move(init)); + flow.attach_preparation_context(std::move(preparation)); + session->configure_sound_capabilities(playback.original_ready() && playback.available(), + playback.original_ready() && playback.available()); + start_original_desk_audio(playback, session->state(), music_enabled); + } else if(result.request==ui::FlowRequest::national_friendly_selected&&session) { + serve_national_friendly_selection(flow,*session,result.national_friendly_opponent,revision,data, + national_friendly_question_presenter); + } else if (result.request == ui::FlowRequest::friendly_action && session) { + serve_friendly_action(flow, *session, result.friendly_action, revision,data); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + serve_transfer_action(flow, *session, std::get(result.submenu_action), revision, + market_sale_presenter, market_entry_policy, poach_player_selector, poach_notice_presenter); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + serve_transfer_offer(flow, *session, std::get(result.submenu_action), revision, + market_sale_presenter, market_entry_policy, team_info_presenter, player_info_presenter); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!flow.matches_pending_lineup(request)) return {}; + try { + if (!LineupActions(*session).lineup(request, revision, error, [&] { + flow.acknowledge_preparation(session->preparation_projection(revision)); + })) { + flow.reject_preparation_action(error.empty() ? "Die Aufstellungsaktion ist veraltet." : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_preparation_action("Diese Aufstellungsaktion konnte nicht übernommen werden."); + } + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!flow.matches_pending_pitch(request)) return {}; + try { + if (!LineupActions(*session).pitch(request, revision, error, [&] { + flow.acknowledge_preparation(session->preparation_projection(revision)); + })) { + flow.reject_preparation_action(error.empty() ? "Diese Spielfeldaktion ist noch nicht verfügbar." : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_preparation_action("Diese Aufstellungsaktion konnte nicht übernommen werden."); + } + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!session->dispatch_training(request, revision, error)) { + flow.reject_preparation_action(error); + return {}; + } + flow.acknowledge_preparation(session->preparation_projection(revision)); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!session->dispatch_tactics(request, revision, error)) { + flow.reject_preparation_action(error); + return {}; + } + flow.acknowledge_preparation(session->preparation_projection(revision)); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!session->dispatch_training_camp(request, revision, error)) { + flow.reject_preparation_action(error); + return {}; + } + flow.acknowledge_preparation(session->preparation_projection(revision)); + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto* pending = flow.pending_bank_action(); + if (!pending) return {}; + const auto request = *pending; + const auto& supplied = std::get(result.submenu_action); + if (request != supplied) { + flow.reject_preparation_action("stale_bank_request"); + return {}; + } + try { + if (!BankActions(*session).dispatch(request, revision, error, [&] { + flow.acknowledge_preparation(session->preparation_projection(revision)); + })) { + flow.reject_preparation_action(error.empty() ? "bank_action_failed" : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_preparation_action("bank_ack_failed"); + } + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!flow.matches_pending_stadium(request)) return {}; + try { + if (!StadiumActions(*session).dispatch(request, revision, error, construction_notice_presenter, + compensation_notice_presenter, [&] { + flow.acknowledge_preparation(session->preparation_projection(revision)); + })) { + flow.reject_preparation_action(error.empty() ? "stadium_action_failed" : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_preparation_action("stadium_ack_failed"); + } + } else if (result.request == ui::FlowRequest::submenu_action && session && + std::holds_alternative(result.submenu_action)) { + const auto& request = std::get(result.submenu_action); + if (!session->dispatch_toto(request, revision, error)) { + flow.reject_preparation_action(error); + return {}; + } + flow.acknowledge_preparation(session->preparation_projection(revision)); + } else if (result.request == ui::FlowRequest::kickoff) { + // A consumed/replayed request no longer owns a pending desk action. Ignore + // it before installing borrowed presenters or trying to reject that desk. + if (!flow.desktop() || !flow.desktop()->pending() || + *flow.desktop()->pending() != result.desk_action || result.desk_action.revision != revision) return {}; + if (!session) { + flow.reject_desk_action("turn_driver_unavailable"); + return "turn: no active career session"; + } + struct LiveHookReset { + CareerSession* session; + TransferOfferPresenter previous_transfer; + bool transfer_installed; + std::function previous_decision; + bool decision_installed; + PendingOfferHooks previous_pending; + PendingOfferEntryPolicy previous_pending_policy; + SportschauPresentationHooks previous_sportschau; + bool contract_expiry_installed; + bool loan_return_installed; + bool loan_return_offer_installed; + ~LiveHookReset() { + if (!session) return; + session->set_live_minute({}); + session->set_original_sound({}); + session->set_live_event({}); + session->set_live_ball({}); + session->set_live_reality({}); + session->set_phase_results({}); + session->set_live_chance({}); + session->set_live_shot({}); + session->set_live_set_piece({}); + session->set_live_booking({}); + session->set_live_shootout({}); + session->set_season_pause({}); + session->set_season_tax({}); + session->set_season_highscore({}); + session->set_season_promotion({}); + session->set_season_cup_draw({}); + session->set_pending_offer_hooks(std::move(previous_pending)); + session->set_pending_offer_entry_policy(previous_pending_policy); + session->set_sportschau_presentation_hooks(std::move(previous_sportschau)); + if (contract_expiry_installed) session->set_contract_expiry_presenter({}); + if (loan_return_installed) session->set_loan_return_presenter({}); + if (loan_return_offer_installed) session->set_loan_return_offer_presenter({}); + if (transfer_installed) session->set_transfer_offer_selector(std::move(previous_transfer)); + if (decision_installed) session->set_transfer_decision_observer(std::move(previous_decision)); + } + } reset{session.get(), session->state().transfer_offer_selector, bool(transfer_presenter), + session->state().transfer_decision_observer, bool(transfer_decision_presenter), + session->pending_offer_hooks(), session->pending_offer_entry_policy(), + session->sportschau_presentation_hooks(), bool(contract_expiry_presenter), + bool(loan_return_presenter), bool(loan_return_offer_presenter)}; + session->set_pending_offer_hooks(std::move(pending_offer_presenter)); + session->set_pending_offer_entry_policy(pending_entry_policy); + if (contract_expiry_presenter) + session->set_contract_expiry_presenter(std::move(contract_expiry_presenter)); + if (loan_return_presenter) + session->set_loan_return_presenter(std::move(loan_return_presenter)); + if (loan_return_offer_presenter) + session->set_loan_return_offer_presenter(std::move(loan_return_offer_presenter), market_sale_presenter); + if (transfer_presenter) session->set_transfer_offer_selector(transfer_presenter); + if (transfer_decision_presenter) { + session->set_transfer_decision_observer([active = session.get(), &transfer_decision_presenter] + (const TransferDecisionEvent& event) { + transfer_decision_presenter(active->state(), event); + }); + } + uint64_t live_revision = revision; + session->set_live_ball(std::move(live_ball_presenter)); + session->set_live_reality(std::move(live_reality_presenter)); + session->set_phase_results(std::move(phase_result_presenter)); + session->set_live_chance(std::move(live_chance_presenter)); + session->set_live_shot(std::move(live_shot_presenter)); + session->set_live_set_piece(std::move(live_set_piece_presenter)); + session->set_live_booking(std::move(live_booking_presenter)); + session->set_live_shootout(std::move(live_shootout_presenter)); + if (live_presenter || live_intervention_presenter) { + session->set_live_minute([&live_presenter, &live_intervention_presenter, active = session.get(), &live_revision] + (int minute, MatchEngine& engine, + std::vector& groups, GameState& state) mutable { + if (live_presenter) live_presenter(minute, groups, state); + if (live_intervention_presenter) { + const auto dispatch = [active, minute, &engine, &live_revision] + (const ui::LineupRequest& request) { + if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, + "Die Karrieresitzung ist nicht verfügbar."}; + return active->dispatch_live_substitution_result(request, minute, 2, + engine, live_revision); + }; + const auto dispatch_tactic = [active, minute, &engine, &live_revision] + (const ui::TacticsRequest& request, std::string& error) { + return active && active->dispatch_live_tactic(request, minute, 8, + engine, live_revision, error); + }; + const auto dispatch_pitch = [active, minute, &engine, &live_revision] + (const ui::PitchRequest& request) { + if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, + "Die Karrieresitzung ist nicht verfügbar."}; + return active->dispatch_live_pitch_result(request, minute, 2, + engine, live_revision); + }; + const auto dispatch_scope = [active, minute, &engine, &live_revision] + (LiveInterventionBoundary boundary, int mode, int manager, int team, + std::string& error) { + if (!active) { error = "Die Karrieresitzung ist nicht verfügbar."; return false; } + switch (boundary) { + case LiveInterventionBoundary::begin: + return active->begin_live_intervention(minute, mode, manager, team, + engine, live_revision, error); + case LiveInterventionBoundary::finish: + return active->finish_live_intervention(minute, mode, manager, team, + engine, live_revision, error); + case LiveInterventionBoundary::abort: + active->abort_live_intervention(minute, mode, manager, team, + engine, live_revision); + return true; + } + return false; + }; + live_intervention_presenter(minute, engine, groups, state, live_revision, + dispatch, dispatch_tactic, dispatch_pitch, dispatch_scope); + } + }); + } + if (live_match_event_presenter) { + session->set_live_event([&live_match_event_presenter, active = session.get(), &live_revision] + (const LiveMatchEvent& event, MatchEngine& engine, + std::vector& groups, GameState& state) { + if (!active) return; + const auto dispatch = [active, &event, &engine, &live_revision](const ui::LineupRequest& request) { + return active->dispatch_live_substitution_result(request, event.minute, 2, engine, live_revision); + }; + const auto dispatch_tactic = [active, &event, &engine, &live_revision] + (const ui::TacticsRequest& request, std::string& error) { + return active && active->dispatch_live_tactic(request, event.minute, 8, + engine, live_revision, error); + }; + const auto dispatch_pitch = [active, &event, &engine, &live_revision] + (const ui::PitchRequest& request) { + if (!active) return LiveSubstitutionResult{LiveSubstitutionStatus::rejected, 0, -1, + "Die Karrieresitzung ist nicht verfügbar."}; + return active->dispatch_live_pitch_result(request, event.minute, 2, engine, live_revision); + }; + const auto scope = [active, &event, &engine, &live_revision] + (LiveInterventionBoundary boundary, int mode, int manager, int team, std::string& error) { + if (!active || mode != 2 || manager != event.manager_slot || team != event.team) { + error = "Der Live-Ereignis-Scope gehört nicht zum authentifizierten Manager und Team."; + return false; + } + switch (boundary) { + case LiveInterventionBoundary::begin: + return active->begin_live_event_intervention(event, engine, live_revision, error); + case LiveInterventionBoundary::finish: + return active->finish_live_event_intervention(event, engine, live_revision, error); + case LiveInterventionBoundary::abort: + active->abort_live_intervention(event.minute, 2, event.manager_slot, event.team, + engine, live_revision); + return true; + } + return false; + }; + live_match_event_presenter(event, engine, groups, state, live_revision, + dispatch, dispatch_tactic, dispatch_pitch, scope); + }); + } + if (sportschau_presenter.kickoff || sportschau_presenter.intro || sportschau_presenter.fixture || + sportschau_presenter.replay.step || sportschau_presenter.replay.scene || sportschau_presenter.awards || + sportschau_presenter.team_info || sportschau_presenter.winner) { + const SportschauSourceOptions source_options = session->sportschau_source_options(); + SportschauPresentationHooks gated; + gated.winner = sportschau_presenter.winner; // I7 is independent of EXE Sportschau/CareerSession_SportschauSourceOptions_ExecutableField. + if (source_options.intro_after_matchday != 0) gated.kickoff = sportschau_presenter.kickoff; + if (source_options.intro_after_matchday != 0) gated.replay = sportschau_presenter.replay; + if (source_options.intro_after_matchday != 0) gated.awards = sportschau_presenter.awards; + if (source_options.intro_after_matchday != 0) gated.team_info = sportschau_presenter.team_info; + if (sportschau_presenter.intro) { + gated.intro = [source_options, &sportschau_presenter](const GameState& state, + const SportschauIntroView& view) { + const bool once = view.group_index < 0 && source_options.intro_after_matchday != 0; + const bool per_group = view.group_index >= 0 && source_options.intro_each_group != 0; + if (!once && !per_group) return; + if (!state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField) || state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField) != 0 || + !state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField2) || state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField2) != 0) + return; + const bool setting_visible = std::any_of(view.groups.begin(), view.groups.end(), + [&state](const SportschauCompetitionView& competition) { + if (competition.source_setting_index < 0 || competition.source_setting_index > 19) + return false; + const uint32_t setting = ::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(competition.source_setting_index) * 9; + return state.memory.has(setting) && state.memory.u8(setting) == 0; + }); + if (setting_visible) sportschau_presenter.intro(state, view); + }; + } + if (sportschau_presenter.fixture) { + gated.fixture = [source_options, &sportschau_presenter](const GameState& state, + const SportschauFixtureView& fixture) { + if (source_options.intro_after_matchday == 0 || fixture.source_setting_index < 0 || + fixture.source_setting_index > 19) + return; + const uint32_t setting = ::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9; + if (!state.memory.has(setting) || state.memory.u8(setting) != 0 || + !state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField3) || state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField3) != 0) + return; + sportschau_presenter.fixture(state, fixture); + }; + } + session->set_sportschau_presentation_hooks(std::move(gated)); + } + session->set_season_pause(std::move(season_presenter)); + session->set_season_tax(std::move(tax_presenter)); + session->set_season_highscore(std::move(highscore_presenter)); + session->set_season_promotion(std::move(promotion_presenter)); + session->set_season_cup_draw(std::move(cup_draw_presenter)); + playback.set_original_options(original_audio_options(session->state(), music_enabled)); + session->set_original_sound([&playback](uint8_t id, const GameState& state) { + original_match_audio_command(playback, state, id); + }); + const auto advanced = session->dispatch_kickoff(result.desk_action, revision, error); + start_original_desk_audio(playback, session->state(), music_enabled); + if (advanced.kind == TurnDeskKind::Failed || advanced.kind == TurnDeskKind::WaitingAtDesk) { + flow.reject_desk_action(error.empty() ? advanced.reason : error); + return {}; + } + // Source DailyInterest returns before the opening desk when duration reaches0. + // Its completed state remains owned until the app closes the final screens. + if (advanced.kind == TurnDeskKind::CareerComplete) return "career_complete"; + // Original cues run at their presentation boundary. Do not replay late + // synthetic kickoff/goal/full-time summaries after the synchronous turn. + flow.acknowledge_desk(session->desktop_projection(revision)); + flow.attach_preparation_context(session->preparation_projection(revision)); + // The Source matchday already owns its live/Sportschau/table presenters. + // Keep the completed snapshot for queries; an extra generic result modal + // has no Original caller and blocks the following desk (UI #69). + } else if (result.request == ui::FlowRequest::settings_file_action) { + const auto* pending = flow.pending_file(); + const auto& request = result.file_action; + const auto& desk_owner = flow.settings_desk_owner(); + const bool same_pending = pending && *pending == request && + request.file_kind == ui::SaveLoadFileKind::settings && + result.settings_owner_sequence == flow.settings_owner_sequence() && + request.origin_item_id == desk_owner.item_id && request.manager_slot == desk_owner.manager_slot; + if (!session || !same_pending || request.revision != revision || + !save_path_in_directory(request.path, save_directory, ".ein")) { + flow.reject_settings_file("stale_request_or_invalid_settings_path"); + return {}; + } + try { + const auto dispatched = DeskSettingsActions(*session).file(result.settings_owner_sequence, request, + revision, error, [&](CareerSession::DeskSettingsDispatch& applied) { + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_settings_file(std::move(applied.state), std::move(desk), std::move(preparation)); + }); + if (!dispatched) { + flow.reject_settings_file(error.empty() ? "settings_file_operation_rejected" : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_settings_file("settings_file_projection_or_ack_failed"); + } + } else if (result.request == ui::FlowRequest::file_action && + result.file_action.file_kind == ui::SaveLoadFileKind::menu_layout) { + const auto& request = result.file_action; + const auto* pending = flow.pending_file(); + const bool same_pending = pending && pending->action == request.action && + pending->manager_slot == request.manager_slot && pending->revision == request.revision && + pending->path == request.path && pending->overwrite == request.overwrite && + pending->file_kind == request.file_kind && pending->origin_item_id == request.origin_item_id; + if (!session || !same_pending) { + if (pending) flow.reject_file_action("menu_layout_request_not_owned"); + return {}; + } + if (request.revision != revision || + !save_path_in_directory(request.path, save_directory, ".men")) { + flow.reject_file_action("stale_request_or_invalid_menu_layout_path"); + return {}; + } + try { + if (!MenuLayoutActions(*session).dispatch(request, revision, error, [&] { + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_menu_layout(std::move(desk), std::move(preparation)); + })) { + flow.reject_file_action(error); + return {}; + } + } catch (const std::exception&) { + flow.reject_file_action("menu_layout_projection_or_ack_failed"); + } + } else if (result.request == ui::FlowRequest::file_action) { + const auto& request = result.file_action; + if (request.revision != revision || !save_path_in_directory(request.path, save_directory)) { + flow.reject_file_action("stale_request_or_invalid_save_path"); + return {}; + } + if (request.action == ui::SaveLoadAction::load) { + if (request.manager_slot >= 0 && (!session || + request.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager)))) { + flow.reject_file_action("stale_manager"); + return {}; + } + try { + auto loaded = std::make_unique(data, seed, request.path); + if (enable_autosave) loaded->configure_autosave_directory(save_directory); + const uint64_t loaded_revision = revision + 1; + auto desk = loaded->desktop_projection(loaded_revision); + auto preparation = loaded->preparation_projection(loaded_revision); + flow.attach_loaded_game(std::move(desk), std::move(preparation)); + playback.reset_session(loaded->session_id()); + audio_session = loaded->session_id(); + session = std::move(loaded); revision = loaded_revision; + session->configure_sound_capabilities(playback.original_ready() && playback.available(), + playback.original_ready() && playback.available()); + start_original_desk_audio(playback, session->state(), music_enabled); + } catch (const std::exception&) { + flow.reject_file_action("load_failed_or_unsupported_save"); + } + return {}; + } + if (!session || request.manager_slot < 0 || request.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager))) { + flow.reject_file_action("save_requires_the_active_manager"); + return {}; + } + if (!session->save_game(request.path, request.manager_slot, request.overwrite, error)) { + flow.reject_file_action(error); + return {}; + } + const uint64_t saved_revision = revision + 1; + revision = saved_revision; + try { + auto desk = session->desktop_projection(saved_revision); + auto preparation = session->preparation_projection(saved_revision); + flow.acknowledge_saved_game(std::move(desk), std::move(preparation)); + } catch (const std::exception&) { + flow.reject_file_action("save_written_but_projection_failed"); + } + } else if (result.request == ui::FlowRequest::mailbox_closed) { + const auto* pending = flow.pending_mailbox_close(); + if (!session || !pending || *pending != result.mailbox_close) return {}; + try { + if (!MailboxActions(*session).close(result.mailbox_close, revision, error, [&] { + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_mailbox_close(result.mailbox_close, std::move(desk), std::move(preparation)); + })) { + flow.reject_mailbox_close(error.empty() ? "Die Nachrichtenansicht ist veraltet." : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_mailbox_close("Die Nachrichtenansicht konnte nicht geschlossen werden."); + } + } else if (result.request == ui::FlowRequest::mailbox_action) { + // A consumed/replayed or forged event cannot write through a new modal request. + if (!session || !flow.pending_mailbox() || *flow.pending_mailbox() != result.mailbox_action) + return {}; + try { + if (!MailboxActions(*session).dispatch(result.mailbox_action, revision, error, [&] { + auto state = ui::mailbox_state_from_game(session->state(), result.mailbox_action.manager_slot, revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_mailbox(std::move(state), std::move(preparation)); + })) { + flow.reject_mailbox(error); + return {}; + } + } catch (const std::exception&) { + flow.reject_mailbox("Diese Postfachaktion konnte nicht übernommen werden."); + } + } else if (result.request == ui::FlowRequest::settings_action) { + if (!session || !flow.pending_settings() || *flow.pending_settings() != result.settings_action || + result.settings_owner_sequence != flow.settings_owner_sequence()) + return {}; + std::optional dispatched; + try { + dispatched = DeskSettingsActions(*session).write(result.settings_owner_sequence, result.settings_action, + revision, error, [&](CareerSession::DeskSettingsDispatch& applied) { + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_settings(std::move(applied.state), std::move(desk), std::move(preparation)); + }); + } catch (const std::exception&) { + flow.reject_settings("Diese Einstellung konnte nicht übernommen werden."); + return {}; + } + if (!dispatched) { + const auto notice = ui::settings_source_refusal(session->state(), result.settings_action, revision); + if (notice && environment_notice_presenter && + error == ui::original_to_utf8(message_text(session->state(), *notice))) { + auto view = ui::environment_notice_dialog(session->state(), result.settings_action.manager_slot, + message_text(session->state(), *notice)); + const bool shown = environment_notice_presenter(session->state(), std::move(view), flow.render()); + flow.reject_settings({}); + return shown ? std::string{} : "settings_source_notice_aborted"; + } + flow.reject_settings(error); + return {}; + } + } else if (result.request == ui::FlowRequest::settings_close) { + if (!session || result.settings_owner_sequence != flow.settings_owner_sequence()) return {}; + const auto& desk_request = flow.settings_desk_owner(); + try { + const auto dispatched = DeskSettingsActions(*session).close(flow.settings_owner_sequence(), + flow.settings_owner_revision(), desk_request, revision, error, + [&](CareerSession::DeskSettingsDispatch& applied) { + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_settings_closed(std::move(applied.state), std::move(desk), std::move(preparation)); + }); + if (!dispatched) { flow.reject_settings_close(error.empty() ? "Einstellungen konnten nicht geschlossen werden." : error); return {}; } + } catch (const std::exception&) { + flow.reject_settings_close("Einstellungen konnten nicht geschlossen werden."); + } + } else if (result.request == ui::FlowRequest::desk_action && session && + result.desk_action.kind == ui::DeskRequestKind::open_menu && + (result.desk_action.menu_kind == 4 || result.desk_action.menu_kind == 6 || result.desk_action.menu_kind == 7 || result.desk_action.menu_kind == 8 || result.desk_action.menu_kind == 9 || result.desk_action.menu_kind == 24 || result.desk_action.menu_kind == 27 || result.desk_action.menu_kind == 63 || result.desk_action.menu_kind == 19 || result.desk_action.menu_kind == 21)) { + const auto& request = result.desk_action; + if (!flow.desktop() || !flow.desktop()->pending() || request.revision != revision || + request.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager)) || + ui::desk_request_json(request) != ui::desk_request_json(*flow.desktop()->pending())) { + if (flow.desktop() && flow.desktop()->pending()) flow.reject_desk_action("stale_readonly_navigation"); + return {}; + } + try { + if (request.menu_kind == 4) { + const auto& game=session->state(); + if(!ui::achievements_available(game)) { + if(!environment_notice_presenter)throw FormatError("achievements: Original first-match notice presenter unavailable"); + const auto view=ui::environment_notice_dialog(game,request.manager_slot,message_text(game,::bmh::layout::Controller_FormatError_TextPointer)); + const Image backdrop=flow.desktop()->render(); + flow.acknowledge_desk_notice(request); + if(!environment_notice_presenter(game,view,backdrop)) + throw FormatError("achievements: Source first-match notice stopped"); + } else { + const auto exe=load_le(ui::asset_path(data,"BMH.exe")); + auto state=ui::achievements_from_game(game,exe,request,flow.desktop()->render()); + flow.show_achievements(std::move(state),request); + } + } else if (request.menu_kind == 7 || request.menu_kind == 8) { + const auto& game = session->state(); + const auto& desk = flow.desktop()->state(); + const int manager = request.manager_slot; + const size_t record = size_t(manager) * 0xb0c; + const auto live = session->desktop_projection(revision); + if (session->career_complete() || manager < 0 || manager > 3 || + size_t(manager) >= game.manager_teams.size() || record + 0x291 >= game.manager_records.size() || + (uint16_t(game.manager_records[record + 0x290]) | + uint16_t(game.manager_records[record + 0x291]) << 8) != game.manager_teams[size_t(manager)] || + live.manager_slot != desk.manager_slot || live.runtime_club != desk.runtime_club || + live.manager_teams != desk.manager_teams || live.managers != desk.managers || + live.day_counter != desk.day_counter || live.season_day != desk.season_day || + live.season_index != desk.season_index || live.national_team != desk.national_team || + live.badge != desk.badge || live.manager_name != desk.manager_name || live.options != desk.options) + throw FormatError("calendar: stale manager or season context"); + const auto executable = load_le(ui::asset_path(data, "BMH.exe")); + auto calendar = request.menu_kind == 7 + ? ui::reschedule_calendar_from_game(game, executable, manager) + : ui::calendar_from_game(game, executable); + flow.show_calendar(std::move(calendar), request); + } else if (request.menu_kind == 9) { + flow.show_indoor_standings(ui::indoor_standings_from_game(session->state(), + load_le(ui::asset_path(data, "BMH.exe")), + load_textd(ui::asset_path(data, "TEXTD.BLK")), request), request); + } else if (request.menu_kind == 63) { + flow.show_mailbox(ui::mailbox_state_from_game(session->state(), request.manager_slot, revision)); + } else if (request.menu_kind == 21) { + flow.show_advertising(ui::advertising_from_game(session->state(), request.manager_slot, revision)); + } else if (request.menu_kind == 24) { + flow.show_environment(ui::environment_from_game(session->state(), revision), request); + } else if (request.menu_kind == 27) { + session->clear_contract_quote(); + flow.show_contracts(ui::contracts_from_game(session->state(), request.manager_slot, revision)); + } else if (request.menu_kind == 6) { + const auto& game = session->state(); + const auto& desk = flow.desktop()->state(); + const int manager=request.manager_slot; + if(manager>=0&&size_t(manager)begin_friendly_opponent_table(revision,error); + if(!identity)throw FormatError(error.empty()?"friendly table entry rejected":error); + const auto table=session->current_league_table_dispatch(error); + if(!table||table->identity!=*identity)throw FormatError(error.empty()?"friendly table page missing":error); + show_table_dispatch(*table,{},true); + return true; + }); + } else if (request.menu_kind == 19) { + auto opened = DeskSettingsActions(*session).open(request, revision, error, + [&](CareerSession::DeskSettingsProjection& applied) { + flow.show_settings(std::move(applied.state), applied.owner.sequence, request); + }); + if (!opened) throw FormatError(error.empty() ? "settings_owner_rejected" : error); + } else { + flow.show_settings(session->settings_projection(request.manager_slot, revision)); + } + } catch (const std::exception& e) { + flow.reject_desk_action("Diese Ansicht konnte nicht geladen werden."); + std::fprintf(stderr,"desk menu %d: %s\n",request.menu_kind,e.what()); + } + } else if (result.request == ui::FlowRequest::reschedule_action && session) { + const auto* pending = flow.pending_reschedule_action(); + const auto* screen = flow.calendar(); + const auto& request = result.reschedule_action; + if (!pending || !screen || *pending != request || request.owner != screen->owner() || + request.owner.menu_kind != 7 || request.owner.kind != ui::DeskRequestKind::open_menu || + request.owner.revision != revision || request.owner.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager)) || + screen->state().reschedule_manager != request.owner.manager_slot || revision == UINT64_MAX) { + if (pending) flow.reject_reschedule(); + return "stale_reschedule_request"; + } + RescheduleStatus status=RescheduleStatus::invalid_match; + try { + status=RescheduleActions(*session).dispatch(request,revision,[&] { + const auto executable=load_le(ui::asset_path(data,"BMH.exe")); + auto calendar=ui::reschedule_calendar_from_game(session->state(),executable,request.owner.manager_slot); + auto owner=request.owner;owner.revision=revision; + auto desktop=session->desktop_projection(revision); + auto preparation=session->preparation_projection(revision); + flow.acknowledge_reschedule(std::move(calendar),owner,std::move(desktop),std::move(preparation)); + }); + } catch(const std::exception&) { + if(flow.pending_reschedule_action())flow.reject_reschedule(); + return "reschedule_projection_failed"; + } + if (status != RescheduleStatus::moved) { + if (status == RescheduleStatus::day_full || status == RescheduleStatus::team_clash) { + if (environment_notice_presenter) { + const auto body = message_text(session->state(), ::bmh::layout::Controller_CalendarFromGame_TextPointer); + auto notice = ui::environment_notice_dialog(session->state(), request.owner.manager_slot, body); + const bool presented = environment_notice_presenter(session->state(), std::move(notice), screen->render()); + flow.reject_reschedule(); + return presented ? std::string{} : "reschedule_source_notice_aborted"; + } + } + flow.reject_reschedule(); + return {}; + } + } else if (result.request == ui::FlowRequest::environment_action && session) { + const auto* pending = flow.pending_environment(); + const auto* screen = flow.environment(); + const auto& request = result.environment_action; + if (!pending || !screen || *pending != request || + ui::environment_request_json(*pending) != ui::environment_request_json(request) || + request.kind != ui::EnvironmentRequestKind::set_item || request.owner.kind != ui::DeskRequestKind::open_menu || + request.owner.menu_kind != 24 || request.manager_slot < 0 || request.manager_slot > 3 || + request.manager_slot != int(session->state().memory.u8(::bmh::layout::ActiveManager)) || + request.runtime_club != screen->state().runtime_club || + request.manager_slot != screen->state().manager_slot || request.revision != revision || + request.owner.revision != request.revision || request.owner.manager_slot != request.manager_slot || + screen->state().revision != revision || screen->state().owner != request.owner || + size_t(request.manager_slot) >= session->state().manager_teams.size() || + session->state().manager_teams[size_t(request.manager_slot)] != request.runtime_club) { + if (flow.pending_environment()) flow.reject_environment_action({}); + return "stale_environment_owner"; + } + try { + const auto outcome=EnvironmentActions(*session).set(request,revision,error, + [&](const GameState& staged,const std::string& message) { + if(!environment_notice_presenter) { + error="environment_source_notice_presenter_unavailable"; + return false; + } + auto notice=ui::environment_notice_dialog(staged,request.manager_slot,message); + if(!environment_notice_presenter(staged,std::move(notice),screen->render())) { + error="environment_source_notice_aborted"; + return false; + } + return true; + },[&](bool changed) { + auto view=ui::environment_from_game(session->state(),revision); + view.owner=request.owner; + if(changed) { + view.owner.revision=revision; + flow.acknowledge_environment(std::move(view),session->preparation_projection(revision)); + } else flow.acknowledge_environment(std::move(view)); + }); + if(!outcome) { + flow.reject_environment_action({}); + return error; + } + if(*outcome==EnvironmentResult::invalid) + throw FormatError("environment request is outside the Source tile range"); + } catch(const std::exception& e) { + if(flow.pending_environment())flow.reject_environment_action({}); + return e.what(); + } + } else if (result.request == ui::FlowRequest::advertising_action && session) { + const auto* pending = flow.pending_advertising_action(); + if (!pending) return {}; + if (*pending != result.advertising_action) { + flow.reject_advertising_action("Dieses Werbeangebot ist nicht mehr aktuell."); + return {}; + } + const ui::AdvertisingRequest request = *pending; + error.clear(); + try { + CareerSession::AdvertisingRenewalPresenter presenter; + if (request.kind == ui::AdvertisingActionKind::check_renewal && advertising_renewal_presenter) { + const Image backdrop = flow.render(); + presenter = [&, backdrop](const GameState& staged, const AdvertisingRenewal& question) { + return advertising_renewal_presenter(staged, question, backdrop); + }; + } + const auto acknowledge = [&](const CareerSession::AdvertisingActionResult& applied) { + auto state = ui::advertising_from_game(session->state(), request.manager_slot, revision); + if (request.kind == ui::AdvertisingActionKind::set_spending && applied.spending.message_address != 0) { + const auto& game = session->state(); + if (!game.texts || applied.spending.message_address < ::bmh::layout::TextPointerTable) + throw FormatError("advertising: missing original notification text"); + state.notification_text = ui::original_to_utf8( + (*game.texts)[(applied.spending.message_address - ::bmh::layout::TextPointerTable) / 4]); + state.notification_warning = applied.spending.status == AdvertisingSpendingStatus::insufficient_funds; + } + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + flow.acknowledge_advertising(std::move(state), std::move(desk), std::move(preparation)); + }; + if (!session->apply_advertising(request, revision, error, acknowledge, presenter)) + flow.reject_advertising_action(error.empty() + ? (request.kind == ui::AdvertisingActionKind::check_renewal + ? "Die Werbeverlängerung wurde abgelehnt." : "Das Werbeangebot wurde abgelehnt.") : error); + } catch (const std::exception&) { + flow.reject_advertising_action("Die Werbeänderung konnte nicht bestätigt werden."); + } + } else if (result.request == ui::FlowRequest::contracts_closed && session) { + session->clear_contract_quote(); + } else if (result.request == ui::FlowRequest::contract_action && session) { + const auto* pending = flow.pending_contract_action(); + if (!pending) return {}; + if (*pending != result.contract_action) { + flow.reject_contract_action("Diese Vertragsaktion ist nicht mehr aktuell."); + return {}; + } + const ui::ContractRequest request = *pending; + ui::ContractActionResult action; + error.clear(); + try { + if (!ContractActions(*session).dispatch(request, revision, action, error, [&] { + auto state = ui::contracts_from_game(session->state(), request.manager_slot, revision); + auto desk = session->desktop_projection(revision); + auto preparation = session->preparation_projection(revision); + if (request.kind == ui::ContractActionKind::request_demands) { + state.selected_row = request.row; + state.quote_row = request.row; + state.quote_id = action.quote_id; + state.demands = action.demands; + flow.acknowledge_contract_quote(std::move(state), std::move(desk), std::move(preparation)); + } else { + state.selected_row = request.row; + state.feedback = action.feedback; + if (request.kind == ui::ContractActionKind::insure_player) { + state.quote_row = request.row; + state.quote_id = action.quote_id; + state.demands = action.demands; + } + if (request.kind == ui::ContractActionKind::insure_player) + flow.acknowledge_contract_insurance(std::move(state), std::move(desk), std::move(preparation)); + else if (request.kind == ui::ContractActionKind::submit_bonuses) + flow.acknowledge_contract_bonuses(std::move(state), std::move(desk), std::move(preparation)); + else + flow.acknowledge_contract_offer(std::move(state), std::move(desk), std::move(preparation)); + } + })) { + flow.reject_contract_action(error.empty() ? "Der Vertragsauftrag wurde abgelehnt." : error); + return {}; + } + } catch (const std::exception&) { + flow.reject_contract_action("Die Vertragsänderung konnte nicht bestätigt werden."); + } + } else if (result.request == ui::FlowRequest::desk_action && session && + (result.desk_action.kind == ui::DeskRequestKind::change_ticket_price || + result.desk_action.kind == ui::DeskRequestKind::change_option)) { + if (!session->dispatch_desk_widget(result.desk_action, revision, error)) { + flow.reject_desk_action(error); + return {}; + } + flow.acknowledge_desk(session->desktop_projection(revision)); + flow.attach_preparation_context(session->preparation_projection(revision)); + } else if (result.request == ui::FlowRequest::submenu_action) { + // Every pending request needs an ACK or a rejection. Until its engine + // adapter exists, the screen must remain usable after this action. + flow.reject_preparation_action("Diese Aktion ist noch nicht verfügbar."); + } else if (result.request == ui::FlowRequest::desk_action) { + if (result.desk_action.kind == ui::DeskRequestKind::change_layout) { + std::string error; + if (!session->dispatch_desktop_layout(result.desk_action, revision, error)) { + flow.reject_desk_action(error); + return {}; + } + flow.acknowledge_desk(session->desktop_projection(revision)); + flow.attach_preparation_context(session->preparation_projection(revision)); + return {}; + } + flow.reject_desk_action("Dieses Menü ist noch nicht verfügbar."); + } + return {}; +} + +std::string serve_flow_request(ui::StartupFlow& flow,const ui::FlowResult& result, + std::unique_ptr& session,const fs::path& data,const fs::path& save_directory, + uint32_t seed,uint64_t& revision,openbmh::audio::Playback& playback, + std::optional& audio_session,bool music_enabled, + NationalFriendlyQuestionPresenter national_presenter) { + return serve_flow_request(flow,result,session,data,save_directory,seed,revision,playback, + audio_session,music_enabled,{}, {}, {}, {}, {}, {}, {}, {}, {}, + PendingOfferEntryPolicy::legacy_unpresented, {}, + HumanBuyerMarketEntryPolicy::legacy_unpresented, {}, {}, {}, {}, {}, {}, {}, {}, {}, + std::move(national_presenter)); +} + +} // namespace bmh::app diff --git a/src/app/controller.hpp b/src/app/controller.hpp new file mode 100644 index 0000000..bc483eb --- /dev/null +++ b/src/app/controller.hpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "app/career_session.hpp" +#include "audio/playback.hpp" +#include + +namespace bmh::app { + +using SeasonPresenter = std::function; + +using TransferOfferPresenter = std::function; +using TransferDecisionPresenter = std::function; +using PoachNoticePresenter = std::function; +using AdvertisingRenewalPresenter = std::function; +using NationalFriendlyQuestionPresenter = std::function( + const GameState&, ui::TaxDialogProjection, const Image&)>; +using ContractExpiryPresenter = CareerSession::ContractExpiryPresenter; +using LoanReturnPresenter = CareerSession::LoanReturnPresenter; +using LoanReturnOfferPresenter = CareerSession::LoanReturnOfferPresenter; +using LiveLineupDispatcher = std::function; +using LiveTacticsDispatcher = std::function; +using LivePitchDispatcher = std::function; +enum class LiveInterventionBoundary { begin, finish, abort }; +using LiveInterventionScopeDispatcher = std::function; +using LiveInterventionPresenter = std::function&, + GameState&, uint64_t&, const LiveLineupDispatcher&, const LiveTacticsDispatcher&, + const LivePitchDispatcher&, const LiveInterventionScopeDispatcher&)>; +using LiveMatchEventPresenter = std::function&, GameState&, uint64_t&, const LiveLineupDispatcher&, + const LiveTacticsDispatcher&, const LivePitchDispatcher&, + const LiveInterventionScopeDispatcher&)>; +using EnvironmentNoticePresenter = std::function; +using LiveRealityPresenter = decltype(TurnDriver::live_reality); +using PhaseResultPresenter = decltype(TurnDriver::phase_results); +using LiveBallPresenter = std::function&, const GameState&)>; +using LiveChancePresenter = std::function&, const GameState&)>; +using LiveShotPresenter = std::function&, const GameState&)>; +using LiveSetPiecePresenter = std::function&, const GameState&)>; +using LiveBookingPresenter = std::function&, const GameState&)>; +using LiveShootoutPresenter = std::function&, const GameState&)>; + +// Shared, synchronous request boundary of the SDL app. Tests drive the same +// controller without a window; rendering and navigation never advance the engine. +std::string serve_flow_request(ui::StartupFlow&, const ui::FlowResult&, + std::unique_ptr&, const std::filesystem::path& data, + const std::filesystem::path& save_directory, uint32_t seed, uint64_t& revision, + openbmh::audio::Playback&, std::optional& audio_session, bool music_enabled, + std::function&, const GameState&)> live_presenter = {}, + TransferOfferPresenter transfer_presenter = {}, + TransferDecisionPresenter transfer_decision_presenter = {}, + SeasonPresenter season_presenter = {}, + SeasonTaxHooks tax_presenter = {}, + SeasonHighscoreHook highscore_presenter = {}, + SeasonPromotionHook promotion_presenter = {}, + SeasonCupDrawHook cup_draw_presenter = {}, + PendingOfferHooks pending_offer_presenter = {}, + PendingOfferEntryPolicy pending_entry_policy = PendingOfferEntryPolicy::legacy_unpresented, + HumanBuyerSaleHooks market_sale_presenter = {}, + HumanBuyerMarketEntryPolicy market_entry_policy = HumanBuyerMarketEntryPolicy::legacy_unpresented, + TransferOfferTeamInfoPresenter team_info_presenter = {}, + TransferOfferPlayerInfoPresenter player_info_presenter = {}, + ConstructionNoticeHook construction_notice_presenter = {}, + SeasonTicketCompensationNoticeHook compensation_notice_presenter = {}, + SportschauPresentationHooks sportschau_presenter = {}, + AdvertisingRenewalPresenter advertising_renewal_presenter = {}, + CareerSession::PoachPlayerSelector poach_player_selector = {}, + PoachNoticePresenter poach_notice_presenter = {}, + ContractExpiryPresenter contract_expiry_presenter = {}, + NationalFriendlyQuestionPresenter national_friendly_question_presenter = {}, + LoanReturnPresenter loan_return_presenter = {}, + LoanReturnOfferPresenter loan_return_offer_presenter = {}, + LiveInterventionPresenter live_intervention_presenter = {}, + EnvironmentNoticePresenter environment_notice_presenter = {}, + LiveMatchEventPresenter live_match_event_presenter = {}, + LiveBallPresenter live_ball_presenter = {}, + LiveChancePresenter live_chance_presenter = {}, + LiveShotPresenter live_shot_presenter = {}, + LiveSetPiecePresenter live_set_piece_presenter = {}, + LiveBookingPresenter live_booking_presenter = {}, + LiveShootoutPresenter live_shootout_presenter = {}, + LiveRealityPresenter live_reality_presenter = {}, + PhaseResultPresenter phase_result_presenter = {}, bool enable_autosave = false); + +// Focused controller entry for callers that only need to inject the original +// yes/no question presenter; all unrelated synchronous hooks keep defaults. +std::string serve_flow_request(ui::StartupFlow&, const ui::FlowResult&, + std::unique_ptr&, const std::filesystem::path& data, + const std::filesystem::path& save_directory, uint32_t seed, uint64_t& revision, + openbmh::audio::Playback&, std::optional& audio_session, bool music_enabled, + NationalFriendlyQuestionPresenter national_friendly_question_presenter); + +} // namespace bmh::app diff --git a/src/app/desktop_actions.cpp b/src/app/desktop_actions.cpp new file mode 100644 index 0000000..39b5323 --- /dev/null +++ b/src/app/desktop_actions.cpp @@ -0,0 +1,564 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "app/desktop_actions.hpp" +#include "app/action_transaction.hpp" + +#include + +namespace bmh::app { + +ui::DeskRequest DesktopActions::menu(const ui::DeskState& observed, int kind) { + ui::DeskRequest request; + request.kind = ui::DeskRequestKind::open_menu; + request.menu_kind = kind; + request.manager_slot = observed.manager_slot; + request.revision = observed.revision; + for (const auto& item : observed.items) + if (item.kind == kind) request.item_id = item.id; + return request; +} + +bool DeskSettingsActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.desk_settings_checkpoint(revision), + [&](CareerSession::DeskSettingsCheckpoint before) { + session_.restore_desk_settings_checkpoint(std::move(before), revision); + }, action); +} + +std::optional DeskSettingsActions::open( + const ui::DeskRequest& request, uint64_t& revision, std::string& error, const OpenAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_desk_settings(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional DeskSettingsActions::dispatch( + const CareerSession::DeskSettingsAction& request, uint64_t& revision, std::string& error, + const Accept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_desk_settings(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional DeskSettingsActions::write(uint64_t sequence, + const ui::SettingsWriteRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { + return dispatch(CareerSession::DeskSettingsWrite{sequence, request}, revision, error, acknowledge); +} + +std::optional DeskSettingsActions::file(uint64_t sequence, + const ui::SaveLoadRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { + return dispatch(CareerSession::DeskSettingsFile{sequence, request}, revision, error, acknowledge); +} + +std::optional DeskSettingsActions::close(uint64_t sequence, + uint64_t owner_revision, const ui::DeskRequest& observed, uint64_t& revision, std::string& error, + const Accept& acknowledge) { + const CareerSession::DeskSettingsOwner owner{sequence, owner_revision, observed.manager_slot, observed.item_id}; + return dispatch(CareerSession::DeskSettingsClose{owner}, revision, error, acknowledge); +} + +bool DeskSettingsActions::edit(const ui::SettingsState& observed, int row, int column, ui::SettingsEdit operation, + uint64_t& revision, std::string& error) { + ui::SettingsWriteRequest request; + request.manager_slot = observed.manager_slot; + request.revision = observed.revision; + request.expected_raw = observed.cells; + request.row = uint8_t(row); + request.column = uint8_t(column); + request.operation = operation; + return apply(revision, [&] { return session_.dispatch_settings(request, revision, error); }); +} + +bool BalanceActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.balance_checkpoint(), + [&](CareerSession::BalanceCheckpoint before) { session_.restore_balance_checkpoint(std::move(before)); }, action); +} + +std::optional BalanceActions::open(const ui::DeskRequest& request, + uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_balance_plan(request, revision, underlay, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional BalanceActions::dispatch(const ui::BalanceRequest& request, + uint64_t& revision, std::string& error, const Accept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_balance_plan(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +BalancePlanDraft BalanceActions::open_draft(int manager) const { return bmh::open_balance_plan(session_.state(), manager); } +void BalanceActions::cycle_draft(BalancePlanDraft& draft) const { cycle_balance_view(session_.state(), draft); } +void BalanceActions::reset_draft(BalancePlanDraft& draft) const { reset_balance_plan(session_.state(), draft); } +BalanceEditStatus BalanceActions::edit_draft(BalancePlanDraft& draft, int row, int32_t value) const { + return edit_balance_plan(session_.state(), draft, row, value); +} + +bool BalanceActions::close_draft(const BalancePlanDraft& draft, uint64_t& revision) { + bool warning = false; + apply(revision, [&] { + warning = bmh::close_balance_plan(session_.state(), draft); + ++revision; + return true; + }); + return warning; +} + +bool OtherGamesActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.other_games_checkpoint(), + [&](CareerSession::OtherGamesCheckpoint before) { session_.restore_other_games_checkpoint(std::move(before)); }, action); +} + +std::optional OtherGamesActions::open(const ui::DeskRequest& request, + uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_other_games(request, revision, underlay, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional OtherGamesActions::dispatch(const ui::OtherGamesRequest& request, + uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info, const Accept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_other_games(request, revision, error, team_info); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +bool TopScorersActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.top_scorers_checkpoint(), + [&](CareerSession::TopScorersCheckpoint before) { session_.restore_top_scorers_checkpoint(std::move(before)); }, action); +} + +std::optional TopScorersActions::open(const ui::DeskRequest& request, + uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_top_scorers(request, revision, underlay, error); + if (!result) return false; + ++revision; // Preserve the existing menu-20 opening revision. + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional TopScorersActions::dispatch(const ui::TopScorersRequest& request, + uint64_t& revision, std::string& error, const Accept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_top_scorers(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +bool OpportunitiesActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.opportunities_checkpoint(), + [&](CareerSession::OpportunitiesCheckpoint before) { session_.restore_opportunities_checkpoint(std::move(before)); }, action); +} + +std::optional OpportunitiesActions::open(const ui::DeskRequest& request, + uint64_t& revision, const Image& underlay, std::string& error, bool national_source_case, + int stable_identity, const OpenAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_opportunities(request, revision, underlay, error, national_source_case, stable_identity); + if (!result) return false; + ++revision; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional OpportunitiesActions::dispatch(const ui::OpportunitiesRequest& request, + uint64_t& revision, std::string& error, const Accept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_opportunities(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +bool OpportunitiesActions::preference(const ui::AnalyticsRequest& request, uint64_t& revision, + std::string& error, const std::function& acknowledge) { + return apply(revision, [&] { + if (!session_.apply_statistics_preference(request.owner, request.manager_slot, + request.expected_flags, request.target_flags, revision, error)) return false; + if (revision == UINT64_MAX) throw FormatError("statistics: revision exhausted"); + ++revision; + if (acknowledge) acknowledge(); + return true; + }); +} + +ui::OpportunitiesRequest OpportunitiesActions::close_request(const ui::OpportunitiesState& observed) { + return {observed.identity, ui::OpportunitiesAction::close, observed.mode}; +} + +bool ManagerJoinActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_window(session_, revision, session_.manager_join_checkpoint(), + [&](CareerSession::ManagerJoinCheckpoint before) { session_.restore_manager_join_checkpoint(std::move(before)); }, action); +} + +bool ManagerJoinActions::commit(uint64_t& revision, std::string& error, + const std::function& acknowledge) { + return apply(revision, [&] { + ui::CareerInitializationResult joined; + if (!session_.commit_manager_join(joined, revision, error)) return false; + if (acknowledge) acknowledge(joined); + return true; + }); +} + +bool MailboxActions::dispatch(const ui::MailboxActionRequest& request, uint64_t& revision, + std::string& error, const std::function& acknowledge) { + return detail::apply_native(session_, revision, [&] { + if (!session_.dispatch_mailbox(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +bool MailboxActions::close(const ui::MailboxCloseRequest& request, uint64_t& revision, + std::string& error, const std::function& acknowledge) { + return detail::apply_native(session_, revision, [&] { + if (!session_.acknowledge_mailbox_close(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +ui::MailboxActionRequest MailboxActions::request(int manager, uint64_t revision, + ui::MailboxActionKind kind, const ui::MailboxMessage& observed) { + ui::MailboxActionRequest request; + request.kind = kind; + request.manager_slot = manager; + request.revision = revision; + request.entry_index = observed.entry_index; + request.expected_entry = observed.raw_entry; + return request; +} + +bool MenuLayoutActions::dispatch(const ui::SaveLoadRequest& request, uint64_t& revision, + std::string& error, const std::function& acknowledge) { + return detail::apply_native(session_, revision, [&] { + if (!session_.dispatch_menu_layout(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +std::optional EnvironmentActions::set(const ui::EnvironmentRequest& request, + uint64_t& revision, std::string& error, const Notice& notice, const std::function& acknowledge) { + return set_impl(request, revision, error, notice, acknowledge, false); +} + +std::optional EnvironmentActions::set_console(const ui::EnvironmentView& observed, + int item, int level, uint64_t& revision, std::string& error, const Notice& notice) { + return set_impl(request(observed, item, level), revision, error, notice, {}, true); +} + +std::optional EnvironmentActions::set_impl(const ui::EnvironmentRequest& request, + uint64_t& revision, std::string& error, const Notice& notice, const std::function& acknowledge, + bool publish_console_result) { + error.clear(); + std::optional result; + const bool accepted = detail::apply_native(session_, revision, [&] { + const auto& state = session_.state(); + if (request.kind != ui::EnvironmentRequestKind::set_item || request.revision != revision || + request.manager_slot < 0 || request.manager_slot > 3 || !state.memory.has(::bmh::layout::ActiveManager) || + state.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + size_t(request.manager_slot) >= state.manager_teams.size() || + state.manager_teams[size_t(request.manager_slot)] != request.runtime_club) { + error = "stale_environment_owner"; + return false; + } + auto staged = state; + std::string message; + result = set_environment(staged, request.manager_slot, request.item, request.level, &message); + if (*result == EnvironmentResult::invalid) return true; + if (publish_console_result) session_.state() = staged; + if (!message.empty() && (!notice || !notice(staged, message))) { + if (error.empty()) error = "environment_source_notice_aborted"; + return false; + } + const bool changed = *result == EnvironmentResult::changed; + if (changed) { + if (revision == UINT64_MAX) throw FormatError("environment revision exhausted"); + ++revision; + } + // The old Console called Core directly even for its handled refusals; + // SDL only published a changed result. Preserve both caller semantics. + if (changed || publish_console_result) session_.state() = std::move(staged); + if (acknowledge) acknowledge(changed); + return true; + }); + if (!accepted) result.reset(); + return result; +} + +ui::EnvironmentRequest EnvironmentActions::request(const ui::EnvironmentView& observed, int item, int level) { + ui::EnvironmentRequest request; + request.kind = ui::EnvironmentRequestKind::set_item; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.revision = observed.revision; + request.owner = observed.owner; + request.item = item; + request.level = level; + return request; +} + +bool RescheduleActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_native(session_, revision, action); +} + +RescheduleStatus RescheduleActions::change(GameState& state, int manager, const LeagueMatchRef& match, + int day, ui::RescheduleActionKind kind) { + if (kind == ui::RescheduleActionKind::move) return reschedule_league_match(state, manager, match, day); + if (kind == ui::RescheduleActionKind::undo && undo_reschedule(state, manager, day)) return RescheduleStatus::moved; + return RescheduleStatus::invalid_match; +} + +RescheduleStatus RescheduleActions::dispatch(const ui::RescheduleAction& request, uint64_t& revision, + const std::function& acknowledge) { + auto status = RescheduleStatus::invalid_match; + apply(revision, [&] { + const auto& before = session_.state(); + const int manager = request.owner.manager_slot; + if (request.owner.kind != ui::DeskRequestKind::open_menu || request.owner.menu_kind != 7 || + request.owner.revision != revision || revision == UINT64_MAX || !before.memory.has(::bmh::layout::ActiveManager) || + manager != int(before.memory.u8(::bmh::layout::ActiveManager))) return false; + auto staged = before; + const auto eligible = request.kind == ui::RescheduleActionKind::move + ? reschedulable_matches(before, manager) : moved_matches(before, manager); + if (std::find(eligible.begin(), eligible.end(), request.match) != eligible.end()) + status = change(staged, manager, request.match, request.target_day, request.kind); + if (status != RescheduleStatus::moved) return false; + session_.state() = std::move(staged); + ++revision; + if (acknowledge) acknowledge(); + return true; + }); + return status; +} + +RescheduleStatus RescheduleActions::move(int manager, const LeagueMatchRef& match, int day, uint64_t& revision) { + auto status = RescheduleStatus::invalid_match; + apply(revision, [&] { + status = change(session_.state(), manager, match, day, ui::RescheduleActionKind::move); + if (status != RescheduleStatus::moved) return false; + ++revision; + return true; + }); + return status; +} + +void RescheduleActions::undo_console(int manager, int day, uint64_t& revision) { + apply(revision, [&] { + // Keep the Console's existing accepted-command revision after its own + // observed moved-match selection, including Core's Boolean result. + (void)change(session_.state(), manager, {}, day, ui::RescheduleActionKind::undo); + ++revision; + return true; + }); +} + +bool ContractActions::dispatch(const ui::ContractRequest& request, uint64_t& revision, + ui::ContractActionResult& result, std::string& error, const std::function& acknowledge) { + bool accepted = false; + try { + return detail::apply_native(session_, revision, [&] { + if (!session_.dispatch_contract(request, revision, result, error)) return false; + accepted = true; + if (acknowledge) acknowledge(); + return true; + }); + } catch (...) { + // Preserve the old SDL rejection's quote cleanup and consumed-ID policy. + if (accepted) session_.clear_contract_quote(); + throw; + } +} + +ui::ContractRequest ContractActions::bind(const ui::ContractsState& observed, + ui::ContractActionKind kind, uint64_t request_id) { + ui::ContractRequest request; + request.kind = kind; + request.request_id = request_id; + request.revision = observed.revision; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + return request; +} + +ui::ContractRequest ContractActions::demands(const ui::ContractsState& observed, + const ui::ContractPlayer& player, uint64_t request_id) { + auto request = bind(observed, ui::ContractActionKind::request_demands, request_id); + request.row = player.row; + request.player_id = player.player_id; + return request; +} + +ui::ContractRequest ContractActions::team_bonus(const ui::ContractsState& observed, + int index, uint8_t percent, uint64_t request_id) { + auto request = bind(observed, ui::ContractActionKind::submit_bonuses, request_id); + request.proposed_bonuses = observed.team_premiums; + request.proposed_bonuses.at(size_t(index)) = percent; + return request; +} + +ui::ContractRequest ContractActions::insurance(const ui::ContractsState& observed, int row, + int player, uint64_t quote, uint8_t form, uint8_t months, uint64_t request_id) { + auto request = bind(observed, ui::ContractActionKind::insure_player, request_id); + request.row = row; request.player_id = player; request.quote_id = quote; + request.term_column = form; request.insurance_months = months; + return request; +} + +ui::ContractRequest ContractActions::offer(const ui::ContractsState& observed, int row, + int player, uint64_t quote, const std::array& bonuses, int years, uint32_t salary, + const std::array& demands, uint64_t request_id) { + auto request = bind(observed, years > 0 ? ui::ContractActionKind::submit_offer : ui::ContractActionKind::submit_bonuses, request_id); + request.row = row; request.player_id = player; request.quote_id = quote; + request.proposed_bonuses = bonuses; + if (years > 0) { + request.term_column = uint8_t(years - 1); + request.demand = demands.at(size_t(years - 1)); + request.monthly_salary = salary; + } + return request; +} + +bool FriendlyActions::apply(uint64_t& revision, const std::function& action) { + return detail::apply_native(session_, revision, action); +} + +FriendlyBookingRequest FriendlyActions::booking_request(const ui::FriendlyMatchRequest& observed) { + FriendlyBookingQuote quote; + quote.status = FriendlyQuoteStatus::quoted; + quote.manager = observed.manager_slot; + quote.opponent = observed.opponent; + quote.manager_team = observed.runtime_team; + quote.manager_home = observed.manager_home; + quote.home_team = observed.home_team; + quote.away_team = observed.away_team; + quote.payer_manager = observed.payer_manager; + quote.opponent_manager = observed.opponent_manager; + quote.cost = observed.cost; + quote.planner_count = uint8_t(observed.planner_count); + return {quote, uint16_t(observed.season_day), observed.accept_opponent, observed.consenting_manager, + observed.accept_cost, observed.approving_manager}; +} + +ui::FriendlyBookingAck FriendlyActions::acknowledgement(const ui::FriendlyMatchRequest& request, + const FriendlyBookingResult& outcome, uint64_t revision) const { + ui::FriendlyBookingAck ack; + ack.request_id = request.request_id; ack.quote_id = request.quote_id; ack.revision = revision; + ack.accepted = true; ack.manager_slot = request.manager_slot; ack.runtime_team = request.runtime_team; + ack.opponent = request.opponent; ack.opponent_manager = outcome.opponent_manager; + ack.season_day = request.season_day; ack.payer_manager = outcome.payer_manager; + ack.home_team = outcome.home_team; ack.away_team = outcome.away_team; ack.cost = outcome.cost; + ack.planner_count = session_.state().memory.u8(::bmh::layout::FriendlyPlanCount); + return ack; +} + +FriendlyActions::Booking FriendlyActions::book(const ui::FriendlyMatchRequest& request, + uint64_t& revision, bool national, const Accept& acknowledge) { + Booking result; + result.applied = apply(revision, [&] { + if (request.kind != ui::FriendlyRequestKind::book || request.revision != revision || revision == UINT64_MAX) { + result.result.status = FriendlyBookingStatus::stale_quote; + return false; + } + if (national) { + if (!request.national_booking) return false; + result.result = book_national_friendly_match(session_.state(), *request.national_booking, session_.rand(), session_.game()); + } else result.result = book_friendly_match(session_.state(), booking_request(request)); + if (result.result.status != FriendlyBookingStatus::booked) return false; + const auto next_revision = revision + 1; + const auto ack = acknowledgement(request, result.result, next_revision); + if (ack.planner_count != request.planner_count + 2) { + result.planner_mismatch = true; + return false; + } + if (acknowledge) acknowledge(ack); + // Preserve the old UI caller's revision during its acknowledgement. + revision = next_revision; + return true; + }); + return result; +} + +FriendlyActions::Booking FriendlyActions::book_club(const ui::FriendlyMatchRequest& request, + uint64_t& revision, const Accept& acknowledge) { return book(request, revision, false, acknowledge); } +FriendlyActions::Booking FriendlyActions::book_national(const ui::FriendlyMatchRequest& request, + uint64_t& revision, const Accept& acknowledge) { return book(request, revision, true, acknowledge); } + +FriendlyBookingResult FriendlyActions::book_console(const FriendlyBookingQuote& quote, uint16_t day, + bool accept_opponent, int consenting_manager, bool accept_cost, int approving_manager, uint64_t& revision) { + FriendlyBookingResult result; + apply(revision, [&] { + result = book_friendly_match(session_.state(), + {quote, day, accept_opponent, consenting_manager, accept_cost, approving_manager}); + if (result.status != FriendlyBookingStatus::booked) return false; + ++revision; + return true; + }); + return result; +} + +FriendlyBookingQuote FriendlyActions::quote(int manager, int opponent, bool home) const { + return quote_friendly_match(session_.state(), manager, opponent, home); +} +NationalFriendlyQuote FriendlyActions::national_quote(const NationalFriendlyOwner& owner, int opponent, bool home) { + return quote_national_friendly_match(session_.state(), owner, opponent, home, session_.rand()); +} +FriendlyDateStatus FriendlyActions::date_status(const FriendlyBookingQuote& quote, uint16_t day) const { + return friendly_match_date_status(session_.state(), quote, day); +} +FriendlyDateStatus FriendlyActions::national_date_status(const NationalFriendlyQuote& quote, + const NationalFriendlyOwner& owner, uint16_t day) const { + return national_friendly_match_date_status(session_.state(), quote, owner, session_.rand(), day); +} +NationalFriendlyOwner FriendlyActions::national_owner(const ui::FriendlyMatchRequest& request) { + return {request.quote_id, request.revision, request.manager_slot, 0x165, 6}; +} + +} // namespace bmh::app diff --git a/src/app/desktop_actions.hpp b/src/app/desktop_actions.hpp new file mode 100644 index 0000000..abc37ee --- /dev/null +++ b/src/app/desktop_actions.hpp @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "app/career_session.hpp" + +namespace bmh::app { + +class DesktopActions { +public: + static ui::DeskRequest menu(const ui::DeskState& observed, int kind); +}; + +class DeskSettingsActions { +public: + explicit DeskSettingsActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + using OpenAccept = std::function; + using Accept = std::function; + std::optional open(const ui::DeskRequest&, + uint64_t& revision, std::string& error, const OpenAccept& = {}); + std::optional write(uint64_t owner_sequence, + const ui::SettingsWriteRequest&, uint64_t& revision, std::string& error, const Accept& = {}); + std::optional file(uint64_t owner_sequence, + const ui::SaveLoadRequest&, uint64_t& revision, std::string& error, const Accept& = {}); + std::optional close(uint64_t owner_sequence, + uint64_t owner_revision, const ui::DeskRequest& observed, + uint64_t& revision, std::string& error, const Accept& = {}); + bool edit(const ui::SettingsState& observed, int row, int column, ui::SettingsEdit, + uint64_t& revision, std::string& error); +private: + std::optional dispatch(const CareerSession::DeskSettingsAction&, + uint64_t& revision, std::string& error, const Accept&); + CareerSession& session_; +}; + +class BalanceActions { +public: + explicit BalanceActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + using OpenAccept = std::function; + using Accept = std::function; + std::optional open(const ui::DeskRequest&, uint64_t& revision, + const Image& underlay, std::string& error, const OpenAccept& = {}); + std::optional dispatch(const ui::BalanceRequest&, + uint64_t& revision, std::string& error, const Accept& = {}); + BalancePlanDraft open_draft(int manager) const; + void cycle_draft(BalancePlanDraft&) const; + void reset_draft(BalancePlanDraft&) const; + BalanceEditStatus edit_draft(BalancePlanDraft&, int row, int32_t value) const; + bool close_draft(const BalancePlanDraft&, uint64_t& revision); +private: + CareerSession& session_; +}; + +class OtherGamesActions { +public: + explicit OtherGamesActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + using OpenAccept = std::function; + using Accept = std::function; + std::optional open(const ui::DeskRequest&, uint64_t& revision, + const Image& underlay, std::string& error, const OpenAccept& = {}); + std::optional dispatch(const ui::OtherGamesRequest&, + uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& = {}, const Accept& = {}); +private: + CareerSession& session_; +}; + +class TopScorersActions { +public: + explicit TopScorersActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + using OpenAccept = std::function; + using Accept = std::function; + std::optional open(const ui::DeskRequest&, uint64_t& revision, + const Image& underlay, std::string& error, const OpenAccept& = {}); + std::optional dispatch(const ui::TopScorersRequest&, + uint64_t& revision, std::string& error, const Accept& = {}); +private: + CareerSession& session_; +}; + +class OpportunitiesActions { +public: + explicit OpportunitiesActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + using OpenAccept = std::function; + using Accept = std::function; + std::optional open(const ui::DeskRequest&, uint64_t& revision, + const Image& underlay, std::string& error, bool national_source_case = false, + int stable_identity = -1, const OpenAccept& = {}); + std::optional dispatch(const ui::OpportunitiesRequest&, + uint64_t& revision, std::string& error, const Accept& = {}); + bool preference(const ui::AnalyticsRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + static ui::OpportunitiesRequest close_request(const ui::OpportunitiesState& observed); +private: + CareerSession& session_; +}; + +class ManagerJoinActions { +public: + explicit ManagerJoinActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + bool commit(uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); +private: + CareerSession& session_; +}; + +class MailboxActions { +public: + explicit MailboxActions(CareerSession& session) : session_(session) {} + bool dispatch(const ui::MailboxActionRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + bool close(const ui::MailboxCloseRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + static ui::MailboxActionRequest request(int manager, uint64_t revision, + ui::MailboxActionKind, const ui::MailboxMessage& observed); +private: + CareerSession& session_; +}; + +class MenuLayoutActions { +public: + explicit MenuLayoutActions(CareerSession& session) : session_(session) {} + bool dispatch(const ui::SaveLoadRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); +private: + CareerSession& session_; +}; + +class EnvironmentActions { +public: + explicit EnvironmentActions(CareerSession& session) : session_(session) {} + using Notice = std::function; + std::optional set(const ui::EnvironmentRequest&, uint64_t& revision, std::string& error, + const Notice& = {}, const std::function& acknowledge = {}); + std::optional set_console(const ui::EnvironmentView&, int item, int level, + uint64_t& revision, std::string& error, const Notice& = {}); + static ui::EnvironmentRequest request(const ui::EnvironmentView& observed, int item, int level); +private: + std::optional set_impl(const ui::EnvironmentRequest&, uint64_t&, std::string&, + const Notice&, const std::function&, bool publish_console_result); + CareerSession& session_; +}; + +class RescheduleActions { +public: + explicit RescheduleActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + RescheduleStatus dispatch(const ui::RescheduleAction&, uint64_t& revision, + const std::function& acknowledge = {}); + RescheduleStatus move(int manager, const LeagueMatchRef&, int day, uint64_t& revision); + void undo_console(int manager, int day, uint64_t& revision); +private: + static RescheduleStatus change(GameState&, int manager, const LeagueMatchRef&, int day, ui::RescheduleActionKind); + CareerSession& session_; +}; + +class ContractActions { +public: + explicit ContractActions(CareerSession& session) : session_(session) {} + bool dispatch(const ui::ContractRequest&, uint64_t& revision, ui::ContractActionResult&, std::string& error, + const std::function& acknowledge = {}); + static ui::ContractRequest demands(const ui::ContractsState&, const ui::ContractPlayer&, uint64_t request_id); + static ui::ContractRequest team_bonus(const ui::ContractsState&, int index, uint8_t percent, uint64_t request_id); + static ui::ContractRequest insurance(const ui::ContractsState&, int row, int player, uint64_t quote, + uint8_t form, uint8_t months, uint64_t request_id); + static ui::ContractRequest offer(const ui::ContractsState&, int row, int player, uint64_t quote, + const std::array& bonuses, int years, uint32_t salary, + const std::array& demands, uint64_t request_id); +private: + static ui::ContractRequest bind(const ui::ContractsState&, ui::ContractActionKind, uint64_t request_id); + CareerSession& session_; +}; + +class FriendlyActions { +public: + explicit FriendlyActions(CareerSession& session) : session_(session) {} + struct Booking { FriendlyBookingResult result; bool applied = false, planner_mismatch = false; }; + using Accept = std::function; + bool apply(uint64_t& revision, const std::function& action); + Booking book_club(const ui::FriendlyMatchRequest&, uint64_t& revision, const Accept& = {}); + Booking book_national(const ui::FriendlyMatchRequest&, uint64_t& revision, const Accept& = {}); + FriendlyBookingResult book_console(const FriendlyBookingQuote&, uint16_t day, bool accept_opponent, + int consenting_manager, bool accept_cost, int approving_manager, uint64_t& revision); + FriendlyBookingQuote quote(int manager, int opponent, bool home) const; + NationalFriendlyQuote national_quote(const NationalFriendlyOwner&, int opponent, bool home); + FriendlyDateStatus date_status(const FriendlyBookingQuote&, uint16_t day) const; + FriendlyDateStatus national_date_status(const NationalFriendlyQuote&, const NationalFriendlyOwner&, uint16_t day) const; + static NationalFriendlyOwner national_owner(const ui::FriendlyMatchRequest&); +private: + Booking book(const ui::FriendlyMatchRequest&, uint64_t& revision, bool national, const Accept&); + static FriendlyBookingRequest booking_request(const ui::FriendlyMatchRequest&); + ui::FriendlyBookingAck acknowledgement(const ui::FriendlyMatchRequest&, const FriendlyBookingResult&, uint64_t revision) const; + CareerSession& session_; +}; + +} // namespace bmh::app diff --git a/src/app/live_matchday_events.hpp b/src/app/live_matchday_events.hpp new file mode 100644 index 0000000..bd01560 --- /dev/null +++ b/src/app/live_matchday_events.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include + +#include +#include + +namespace bmh::app { + +// EndPhase accepts physical left/right DOWN after minute2, except at the +// first minute of a period. Its home interval ends at0x73, leaving0x74 out. +// Returning only a side keeps the current fixture/manager lookup in Main. +inline std::optional live_matchday_board_side(const SDL_Event& event, int minute, bool indoor) { + if (event.type != SDL_MOUSEBUTTONDOWN || + (event.button.button != SDL_BUTTON_LEFT && event.button.button != SDL_BUTTON_RIGHT) || + minute <= 2 || (indoor ? minute == 21 : (minute == 46 || minute == 91 || minute == 106))) + return {}; + if (event.button.x >= 0 && event.button.x <= 0x73) return 0; + if (event.button.x >= 0xa0 && event.button.x <= 0x113) return 1; + return {}; +} + +// Drain only while the engine is synchronously paused in its observer hook. +// ESC skips future presentation; QUIT is reported to the app. Only noninteractive +// system/window notifications are put back. User input is discarded so it cannot +// become an accidental desk/result action after the synchronous match finishes. +inline bool pump_live_matchday_events(bool& skip_presentation) { + std::vector deferred; + SDL_Event event; + bool quit = false; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + quit = true; + skip_presentation = true; + } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) { + skip_presentation = true; + } else if (event.type == SDL_USEREVENT || event.type == SDL_WINDOWEVENT || + event.type == SDL_DISPLAYEVENT || event.type == SDL_SYSWMEVENT) { + deferred.push_back(event); + } + } + for (auto pending : deferred) SDL_PushEvent(&pending); + return quit; +} + +} // namespace bmh::app diff --git a/src/app/main.cpp b/src/app/main.cpp new file mode 100644 index 0000000..864095d --- /dev/null +++ b/src/app/main.cpp @@ -0,0 +1,3969 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// openbmh_play - the UI of src/ui connected to the engine: options, manager dialogs, a new +// career initialised by the engine (app/career_session.hpp) and its desk. +// +// Usage: openbmh_play [] [--seed ] [--save-directory ] [--mute] [--volume <0..1>] [--music] [--live-frame-ms <0..1000>] +// (also as --data ): the game directory, its BMH.EXE, or a ZIP/7z archive with +// exactly one game (src/launch). Without a game the system's file dialog asks for one. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/controller.hpp" +#include "launch/archive.hpp" +#include "launch/file_dialog.hpp" +#include "launch/game_data.hpp" +#include "version.hpp" +#include "app/live_matchday_events.hpp" +#include "audio/playback.hpp" +#include "app/audio.hpp" +#include "formats/palette.hpp" +#include "formats/textd.hpp" +#include "ui/flow.hpp" +#include "ui/source_hold.hpp" +#include "ui/live_matchday.hpp" +#include "ui/live_reality.hpp" +#include "ui/reality_reporter.hpp" +#include "ui/league_table.hpp" +#include "ui/league_pairings.hpp" +#include "ui/other_games.hpp" +#include "ui/process_timer.hpp" +#include "ui/strengths.hpp" +#include "ui/league_table_range_dialog.hpp" +#include "ui/settings.hpp" +#include "ui/lineup.hpp" +#include "ui/tactics.hpp" +#include "ui/sportschau.hpp" +#include "ui/incoming_transfer.hpp" +#include "ui/outgoing_transfer.hpp" +#include "ui/pending_offer.hpp" +#include "ui/season_entrants.hpp" +#include "ui/season_promotion.hpp" +#include "ui/cup_draw.hpp" +#include "ui/club_info.hpp" +#include "ui/team_statistics.hpp" +#include "ui/club_player_detail.hpp" +#include "ui/game_end.hpp" +#include "ui/game_end_alternate.hpp" +#include "ui/game_end_tax_animation.hpp" +#include "ui/contracts.hpp" +#include "game/month.hpp" +#include "game/driver.hpp" +#include "game/messages.hpp" + +namespace fs = std::filesystem; +using namespace bmh; + +// Why the game cannot start: a message box, and the same text on stderr. +static void show_start_error(const std::string& text) { + std::fprintf(stderr, "%s\n", text.c_str()); + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "OpenBMH", text.c_str(), nullptr); +} + +#ifdef _WIN32 +// The game is a Windows GUI program (no console window on double-click). Started from a +// console, it writes --version, --help and start errors there (kernel32 AttachConsole). +extern "C" __declspec(dllimport) int __stdcall AttachConsole(unsigned long process_id); +static void attach_parent_console() { + // (an output redirected to a file or pipe stays there; a GUI program without one has no + // valid stream, fileno < 0) + const bool out_free = _fileno(stdout) < 0, err_free = _fileno(stderr) < 0; + if ((out_free || err_free) && AttachConsole(static_cast(-1))) { // ATTACH_PARENT_PROCESS + std::FILE* f = nullptr; + if (out_free) freopen_s(&f, "CONOUT$", "w", stdout); + if (err_free) freopen_s(&f, "CONOUT$", "w", stderr); + } +} +#else +static void attach_parent_console() {} +#endif + +int main(int argc, char** argv) { + attach_parent_console(); + const std::vector args = launch::utf8_arguments(argc, argv); // (file names beyond the code page) + fs::path data, save_directory; + uint32_t seed = uint32_t(std::chrono::system_clock::now().time_since_epoch().count()); + bool muted = false, music_enabled = true; + int live_frame_ms = 10; + bool live_frame_ms_explicit = false; + if (const char* configured = std::getenv("BMH_LIVE_FRAME_MS")) { + live_frame_ms = std::clamp(std::atoi(configured), 0, 1000); + live_frame_ms_explicit = true; + } + float volume = 1.0F; + for (size_t i = 1; i < args.size(); ++i) { + const auto is = [&](const char* name) { return args[i] == name; }; + const bool value = i + 1 < args.size(); + if (is("--mute")) { + muted = true; + } else if (is("--music")) { + music_enabled = true; + } else if (is("--no-music")) { + music_enabled = false; + } else if (is("--live-frame-ms") && value) { + live_frame_ms = std::clamp(std::atoi(args[++i].c_str()), 0, 1000); + live_frame_ms_explicit = true; + } else if (is("--data") && value) { + data = launch::path_from_utf8(args[++i]); + } else if (is("--seed") && value) { + seed = uint32_t(std::strtoul(args[++i].c_str(), nullptr, 0)); + } else if (is("--save-directory") && value) { + save_directory = launch::path_from_utf8(args[++i]); + } else if (is("--volume") && value) { + volume = std::strtof(args[++i].c_str(), nullptr); + } else if (is("--version")) { + std::printf("OpenBMH %s\n", bmh::kOpenBmhVersion); + return 0; + } else if (is("--help") || is("-h")) { + std::printf("usage: openbmh_play [] [--seed ] " + "[--save-directory ] [--mute] [--volume <0..1>] [--no-music] [--live-frame-ms <0..1000>]\n"); + return 0; + } else if (args[i].rfind("--", 0) != 0 && data.empty()) { + data = launch::path_from_utf8(args[i]); + } + } + // the game: as given (directory, EXE or archive); else the directory OpenBMH itself lies in, + // when it holds a playable game (the simplest install: openbmh next to BMH.EXE); else + // chosen in the file dialog + if (data.empty()) { + if (char* base = SDL_GetBasePath()) { + const fs::path here = launch::path_from_utf8(base); + SDL_free(base); + try { + const launch::ResolvedGame game = launch::resolve_game(here, launch::default_cache_directory()); + if (game.error.empty() && game.check.playable) data = here; + } catch (const std::exception&) { + // (not a game directory: fall through to the file dialog) + } + } + } + if (data.empty()) { + try { + const auto chosen = launch::choose_game_file("OpenBMH"); + if (!chosen) return 0; // cancelled + data = *chosen; + } catch (const std::exception& e) { + show_start_error(std::string(e.what()) + + "\nStart OpenBMH with the game as argument: openbmh_play "); + return 1; + } + } + bool english_game = false; // (the window title marks the English version as experimental) + { + const launch::ResolvedGame game = launch::resolve_game(data, launch::default_cache_directory()); + if (!game.error.empty() || !game.check.playable) { + show_start_error("The game cannot be started:\n" + launch::describe(game)); + return 1; + } + english_game = game.check.family == launch::GameFamily::english; + // (from an archive: its unpacked copy in the cache, which then also keeps the saves) + data = game.check.directory; + } + if (save_directory.empty()) save_directory = data; + try { + const Palette palette = load_palette(ui::asset_path(data, "M3PC.COL")); + ui::StartupFlow flow(data, save_directory); + std::unique_ptr session; + uint64_t revision = 0; + if (SDL_Init(SDL_INIT_VIDEO) != 0) throw FormatError(SDL_GetError()); + openbmh::audio::Playback playback; + std::string audio_error; + playback.initialize(audio_error); // Audio is optional; the game continues without a device. + playback.set_muted(muted); + playback.set_volume(volume); + std::optional audio_session; + SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); + const std::string window_title = std::string("OpenBMH ") + bmh::kOpenBmhVersion + + (english_game ? " - Football Limited (experimental)" : ""); + SDL_Window* window = SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE); + if (!window) throw FormatError(SDL_GetError()); + SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC); + if (!renderer) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); + if (!renderer) throw FormatError(SDL_GetError()); + SDL_RenderSetLogicalSize(renderer, 320, 240); + SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 320, 240); + if (!texture) throw FormatError(SDL_GetError()); + std::vector pixels(320 * 240); + ui::LiveMatchdayScreen live_screen(data); + ui::RealityReporterPanel reality_reporter(data); + ui::SportschauIntro sportschau_intro(data); + ui::MatchdayIntro matchday_intro(data); + ui::SportschauEleven sportschau_eleven(data); + ui::SportschauTeamInfo sportschau_team_info(data); + ui::CompetitionWinnerScreen competition_winner(data); + const auto season_exe = load_le(ui::asset_path(data, "BMH.exe")); + try { + if (!playback.initialize_original(app::original_audio_assets(data, season_exe), audio_error)) + std::fprintf(stderr, "audio: %s\n", audio_error.c_str()); + playback.set_original_options({music_enabled, true, true}); + app::original_audio_command(playback, 0); + } catch (const std::exception& error) { + std::fprintf(stderr, "audio: %s\n", error.what()); + } + app::OriginalMouseSound mouse_sound(playback); + const auto season_texts = load_textd(ui::asset_path(data, "TEXTD.BLK")); + const auto process_clock_origin = std::chrono::steady_clock::now(); + const auto process_source_seconds = [&] { + return uint64_t(std::chrono::duration_cast( + std::chrono::steady_clock::now()-process_clock_origin).count()); + }; + ui::ProcessTimer process_timer; + struct ProcessTimerOwner { + uint64_t session; + int manager; + uint32_t day; + bool operator==(const ProcessTimerOwner&) const = default; + }; + std::optional process_timer_owner; + std::optional process_timer_frame; + const auto process_timer_image = [&](Image image) { + if (!process_timer.paused() && process_timer_frame) + ui::ProcessTimer::paint(image, *process_timer_frame, season_exe); + return image; + }; + // Sample writes only y0. Nested synchronous presenters poll the + // same Desk-owned clock without re-entering Session/Flow dispatch. + const auto poll_process_timer = [&](bool update_texture, bool present) { + const auto sample = process_timer.sample(process_source_seconds()); + const bool changed_bar = sample && !sample->expired && + (!process_timer_frame || sample->percent != process_timer_frame->percent); + process_timer_frame = sample; + if (changed_bar && update_texture) { + Image bar(320,240); + ui::ProcessTimer::paint(bar,*sample,season_exe); + for (size_t x=0;x<320;++x) pixels[x]=palette.argb[bar.pixels[x]]; + const SDL_Rect top{0,0,320,1}; + if (SDL_UpdateTexture(texture,&top,pixels.data(),320*4)!=0) + throw std::runtime_error(std::string("Process timer texture: ")+SDL_GetError()); + if (present) { + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer,texture,nullptr,nullptr); + SDL_RenderPresent(renderer); + } + } + return sample && sample->expired; + }; + bool running = true, dirty = true; + struct Press { + int x, y; + uint32_t time; + std::string screen; + uint64_t source_tick, revision; + bool pitch_hold_attempted = false; + }; + std::optional press; + std::optional right_press_screen; + auto transfer_view = [](const GameState& state, const TransferOfferListView& offers, int viewer_manager) { + ui::IncomingTransferDecisionView view; + view.valid = offers.valid; + view.list_entry = offers.list_entry; + view.player = offers.player; + view.seller = offers.seller; + view.seller_manager = offers.seller_manager; + view.viewer_manager = viewer_manager; + view.preferred_bid_index = offers.preferred_bid_index; + view.has_preferred_bid = offers.preferred_bid_index >= 0; + view.preferred_bid_passed_random_check = offers.preferred_bid_passed_random_check; + if (offers.seller != 0x0fff && offers.seller != kNoTeam) view.negotiator_name = state.club_name(offers.seller); + view.asking_fee = offers.asking_fee; + view.asking_monthly_salary = offers.asking_monthly_salary; + view.quoted_fee = offers.quoted_fee; + view.quoted_monthly_salary = offers.quoted_monthly_salary; + view.quoted_years = offers.quoted_years; + view.notice_text_address = offers.notice_text_address; + for (size_t row = 0; row < view.offers.size(); ++row) { + const auto& source = offers.offers[row]; + auto& slot = view.offers[row]; + slot.bid_index = source.bid_index; + slot.buyer = source.buyer; + slot.buyer_manager = source.buyer_manager; + slot.fee = source.fee; + slot.monthly_salary = source.monthly_salary; + slot.fee_reference = source.fee_reference; + slot.salary_reference = source.salary_reference; + slot.contract_months = source.contract_months; + slot.loan = source.loan; + slot.transaction_supported = source.transaction_supported || + (source.loan && !source.loan_permitted); + slot.present = source.present; + slot.eligible = source.eligible; + slot.bonuses = source.bonuses; + } + return view; + }; + std::optional season_backdrop; + auto present_season = [&](const Image& image, const char* title, + const Palette* palette_override = nullptr) { + SDL_SetWindowTitle(window, title); + season_backdrop = image; + const Palette& frame_palette = palette_override ? *palette_override : palette; + const Image painted = process_timer_image(image); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = frame_palette.argb[painted.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + const auto present_desk_record_points = [&] { + if(!flow.desk_records_points_active())return; + while(flow.advance_desk_records_point()) + present_season(flow.render(),"OpenBMH - highscore"); + if(flow.finish_desk_records_points()) + present_season(flow.render(),"OpenBMH - highscore"); + dirty=false; + }; + auto contract_expiry_presenter = [&](GameState& staged, WatcomRandom& random, + int manager, int expired_row) -> int { + const GameState before = staged; + const WatcomRandom random_before = random; + try { + uint64_t local_revision = revision; + uint64_t next_quote_id = 1; + auto initial = ui::contracts_from_game(staged, manager, local_revision); + ui::ContractsScreen screen(data, std::move(initial)); + bool renewed_expired_player = false; + bool dirty_contracts = true; + while (running) { + if (dirty_contracts) { + present_season(screen.render(), "OpenBMH - contracts"); + dirty_contracts = false; + } + if (screen.close_requested()) return renewed_expired_player ? 1 : 0; + SDL_Event event; + bool changed = false; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + running = false; + staged = before; + random = random_before; + return -2; + } + if (event.type == SDL_MOUSEBUTTONUP && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) { + changed |= screen.click(event.button.x, event.button.y, + event.button.button == SDL_BUTTON_RIGHT); + } else if (event.type == SDL_MOUSEMOTION) { + changed |= screen.move(event.motion.x, event.motion.y); + } else if (event.type == SDL_TEXTINPUT) { + changed |= screen.text(event.text.text); + } else if (event.type == SDL_KEYDOWN) { + if (event.key.keysym.sym == SDLK_ESCAPE) changed |= screen.key("ESC"); + else if (event.key.keysym.sym == SDLK_BACKSPACE) changed |= screen.key("BACKSPACE"); + } + if (const ui::ContractRequest* pending = screen.pending()) { + const ui::ContractRequest request = *pending; + const auto old_game = staged; + const auto old_random = random; + try { + if (request.manager_slot != manager || request.runtime_club != staged.manager_teams.at(size_t(manager)) || + request.row < 0 || request.row >= 24) + throw FormatError("Vertragsaktion gehört nicht zum aktuellen Verein"); + if (request.kind == ui::ContractActionKind::request_demands) { + auto demands = contract_demands(staged, manager, request.row, false, random); + auto next = ui::contracts_from_game(staged, manager, ++local_revision); + next.demands = demands; + next.quote_id = next_quote_id++; + next.quote_row = request.row; + screen.acknowledge_quote(next); + } else if (request.kind == ui::ContractActionKind::submit_offer) { + if (request.term_column >= 4 || request.quote_id != screen.state().quote_id || + request.row != screen.state().quote_row || !screen.state().demands || + request.demand != (*screen.state().demands)[request.term_column] || + request.monthly_salary > 200000) + throw FormatError("Vertragsangebot ist nicht mehr aktuell"); + const bool accepted = contract_offer(staged, manager, request.row, + request.term_column, request.monthly_salary, request.demand, + false, request.row == expired_row, random, &request.proposed_bonuses); + auto next = ui::contracts_from_game(staged, manager, ++local_revision); + next.feedback = accepted ? "Der Vertrag wurde verlängert." : "Das Angebot wurde abgelehnt."; + screen.acknowledge_offer(next); + if (accepted && request.row == expired_row) renewed_expired_player = true; + } else if (request.kind == ui::ContractActionKind::submit_bonuses) { + const bool accepted = contract_bonuses(staged, manager, request.row, + request.proposed_bonuses); + auto next = ui::contracts_from_game(staged, manager, ++local_revision); + next.feedback = accepted ? "Die Prämien wurden übernommen." : "Die Prämien wurden nicht geändert."; + screen.acknowledge_bonus_offer(next); + } else if (request.kind == ui::ContractActionKind::insure_player) { + const auto insured = contract_insurance(staged, manager, request.row, + request.term_column, request.insurance_months); + if (!insured.accepted) { + screen.reject("Die Versicherung konnte nicht übernommen werden."); + } else { + auto next = ui::contracts_from_game(staged, manager, ++local_revision); + next.demands = screen.state().demands; + next.quote_id = screen.state().quote_id; + next.quote_row = screen.state().quote_row; + screen.acknowledge_insurance(next); + } + } else { + throw FormatError("Unbekannte Vertragsaktion"); + } + changed = true; + } catch (...) { + staged = old_game; + random = old_random; + throw; + } + } + if (screen.close_requested()) return renewed_expired_player ? 1 : 0; + if (renewed_expired_player && !screen.result_page_open()) return 1; + dirty_contracts |= changed; + } + if (playback.needs_pump()) playback.pump(audio_error); + SDL_Delay(10); + } + staged = before; + random = random_before; + return -2; + } catch (const std::exception&) { + staged = before; + random = random_before; + return -2; + } + }; + auto game_end_options = [&](const GameState& state) { + return ui::GameEndRenderOptions{ + state.memory.has(::bmh::layout::PlainBackground) && state.memory.u8(::bmh::layout::PlainBackground) != 0, + (!state.memory.has(::bmh::layout::TextGradientDisabled) || state.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2}; + }; + auto wait_season_ack = [&] { + // Source SDLFlushEvents2/SDLFlushEvents flush pending mouse events, then wait for + // a new left/right press. Physical keyboard ESC is not event8. + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + while (running) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return; } + if (event.type == SDL_MOUSEBUTTONDOWN && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) return; + } + SDL_Delay(10); + } + }; + auto wait_sportschau_ack = [&] { + // Source SDLFlushEvents2 flushes pending mouse input, then accepts fresh + // left/right input. Keyboard Escape is not an Original ACK here. + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + while (running) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return; } + if (event.type == SDL_MOUSEBUTTONDOWN && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) return; + } + SDL_Delay(10); + } + }; + auto source_tick_wait = [&](unsigned ticks) { + for (unsigned i = 0; running && i < ticks; ++i) { + SDL_Delay(20); // Source timer unit used by the traced intro path. + SDL_PumpEvents(); + SDL_Event close; + while (SDL_PeepEvents(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) + running = false; // platform close is the only intro-loop escape + } + }; + auto wait_source_retraces = [&](unsigned count) { + // SDL has no VGA status-port equivalent. Approximate Source's + // retrace waits with the active display's reported refresh period; + // keep the previous frame visible and present the next frame once. + SDL_DisplayMode mode{}; + const int display = SDL_GetWindowDisplayIndex(window); + int refresh_hz = display >= 0 && SDL_GetCurrentDisplayMode(display, &mode) == 0 + ? mode.refresh_rate : 0; + if (refresh_hz <= 0) refresh_hz = 60; // explicit host fallback; not an Original VGA claim + const Uint64 frequency = SDL_GetPerformanceFrequency(); + const Uint64 ticks_per_wait = (frequency + Uint64(refresh_hz) - 1) / Uint64(refresh_hz); + for (unsigned i = 0; running && i < count; ++i) { + const Uint64 started = SDL_GetPerformanceCounter(); + while (running && SDL_GetPerformanceCounter() - started < ticks_per_wait) { + SDL_PumpEvents(); + SDL_Event close; + while (SDL_PeepEvents(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) + running = false; // platform close is the only animation-loop escape + if (running) SDL_Delay(1); + } + } + }; + SportschauPresentationHooks sportschau_presenter; + sportschau_presenter.intro = [&](const GameState&, const SportschauIntroView&) { + if (!running) return; + // PaletteOverride installs KB132's embedded palette; SportschauIntro restores the + // normal palette on return. Keep the override local to intro frames. + const auto& intro_palette = sportschau_intro.palette_override(); + const Palette* intro_colors = intro_palette ? &*intro_palette : nullptr; + for (uint32_t frame = 0; running && frame < ui::SportschauIntro::frame_count; ++frame) { + if (frame != 0) wait_source_retraces(5); + if (!running) return; + present_season(sportschau_intro.render_frame(frame), "OpenBMH - sportschau_intro", intro_colors); + if (frame == 0) { + source_tick_wait(70); + app::original_audio_command(playback, 2); // SportschauIntro, Original S/2002 fanfare. + source_tick_wait(45); + } + } + if (!running) return; + source_tick_wait(100); + app::original_audio_command(playback, 1); + if (!running) return; + present_season(sportschau_intro.render_frame(ui::SportschauIntro::frame_count - 1), + "OpenBMH - sportschau_intro_ack", intro_colors); + wait_sportschau_ack(); + }; + const auto sportschau_context = [&](const GameState& state) { + ui::SportschauReportContext context; + context.solid_panel_background = state.memory.has(::bmh::layout::SolidPanelBackground) && state.memory.u8(::bmh::layout::SolidPanelBackground) != 0; + context.gradient_text = state.memory.has(::bmh::layout::TextGradientDisabled) && state.memory.u8(::bmh::layout::TextGradientDisabled) == 0 && + season_exe.u8(::bmh::layout::TextGradientMode) == 2; + return context; + }; + sportschau_presenter.kickoff = [&](const GameState&, const MatchdayIntroView& view) { + if (!running) return; + present_season(matchday_intro.render(view), "OpenBMH - matchday_intro", + matchday_intro.palette_override() ? &*matchday_intro.palette_override() : nullptr); + // SDLGetTicks reads BIOS ticks at BDA46c (PIT1193182 /65536 Hz), + // unlike the separate 20ms units of DecodeTaxAnimationScript2. Source waits36 ticks. + constexpr Uint32 duration = (36ull * 65536 * 1000 + 1193181) / 1193182; + const Uint32 start = SDL_GetTicks(); + SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP); + bool skipped = false; + while (running && !skipped && SDL_GetTicks() - start < duration) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) running = false; + if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_LEFT) + skipped = true; + } + if (running && !skipped) SDL_Delay(1); + } + SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP); + }; + std::optional sportschau_replay_screen; + size_t sportschau_step_index = 0; + sportschau_presenter.replay.step = [&](const GameState& state, + const SportschauFixtureView& fixture, const SportschauReportStep& step) { + if (!running) return true; + if (step.visible_log_entries == 0 && step.progress_minute == 0) { + app::original_match_audio_command(playback, state, 3); + sportschau_replay_screen.emplace(data, fixture, sportschau_context(state)); + sportschau_step_index = 0; + } + if (!sportschau_replay_screen) throw FormatError("sportschau: missing report owner"); + bool skip = false; + SDL_Event input; + if (step.minute_wait) { + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) running = false; + if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_LEFT) + skip = true; + } + } else { + SDL_PumpEvents(); + while (SDL_PeepEvents(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false; + } + if (!running) return true; + const std::string title = "OpenBMH - sportschau_replay_" + std::to_string(fixture.group) + + "_" + std::to_string(fixture.fixture) + "_" + std::to_string(sportschau_step_index++); + present_season(sportschau_replay_screen->render_report(step), title.c_str()); + const int raw = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField4) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField4) : 0; + if (step.minute_wait) source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw)); + if (step.chance_wait) source_tick_wait(50); + return skip; + }; + sportschau_presenter.replay.scene = [&](const GameState& state, + const SportschauFixtureView& fixture, const SportschauSceneView& scene) { + if (!running) return; + ui::LiveMatchdayFrame frame; + frame.gradient_text = sportschau_context(state).gradient_text; + LiveChanceEvent event; + event.group = 0; event.match = scene.shot.match; event.side = scene.shot.acting_side; + event.minute = scene.shot.minute; + const auto header = ui::live_chance_projection(event, scene.groups, state, season_exe); + const auto backdrop = live_screen.render_sportschau_header(header, + scene.home_goals_before, scene.away_goals_before, frame.gradient_text); + const auto colors = live_screen.shot_palette(palette, scene.shot, scene.groups, state); + const std::string id = std::to_string(fixture.group) + "_" + std::to_string(fixture.fixture) + + "_" + std::to_string(scene.report_step.visible_log_entries); + const auto delay = [&](int row) { + const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(row * 9); + const int raw = state.memory.has(address) ? state.memory.u8(address) : 0; + source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw)); + }; + present_season(backdrop, ("OpenBMH - sportschau_scene_header_" + id).c_str(), &colors); + delay(12); // AdvanceStep(12), header preview in ShotAnimation + if (scene.set_piece) { + const auto frames = live_screen.render_set_piece(frame, *scene.set_piece, &backdrop); + for (size_t i = 0; running && i < frames.size(); ++i) { + present_season(frames[i], ("OpenBMH - sportschau_set_piece_" + id + "_" + + std::to_string(i)).c_str(), &colors); + const unsigned retraces = i == 0 ? 40u : + (state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2) : 0u); + wait_source_retraces(retraces); // FirstThen: first40, then F8 + } + } + const auto frames = live_screen.render_shot(frame, scene.shot, &backdrop); + for (size_t i = 0; running && i < frames.size(); ++i) { + present_season(frames[i], ("OpenBMH - sportschau_shot_" + id + "_" + + std::to_string(i)).c_str(), &colors); + const int speed = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ? int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField))) : 0; + wait_source_retraces(unsigned(std::max(0, speed))); + } + source_tick_wait(10); // LiveMatchdayFrame's final ten ticks + if (!running) return; + if (app::match_sound_enabled(state)) + app::original_audio_command(playback, scene.shot.miss ? 20 : 19); // SetPieceAnimation. + if (state.memory.has(::bmh::layout::Main_FormatError_RuntimeField5) && state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField5) == 0) { + present_season(frames.back(), ("OpenBMH - sportschau_shot_ack_" + id).c_str(), &colors); + wait_sportschau_ack(); + } else delay(15); + if (!running) return; + auto restored = scene.report_step; restored.chance_wait = false; + present_season(sportschau_replay_screen->render_report(restored), + ("OpenBMH - sportschau_scene_restored_" + id).c_str()); + }; + sportschau_presenter.fixture = [&](const GameState& state, const SportschauFixtureView& fixture) { + if (!running) return; + ui::SportschauMatchReport screen(data, fixture, sportschau_context(state)); + present_season(screen.render_report(fixture.log_events.size()), "OpenBMH - sportschau_report"); + wait_sportschau_ack(); + sportschau_replay_screen.reset(); + }; + sportschau_presenter.winner = [&](const GameState& state, const CompetitionWinnerView& view) { + if (!running) return; + const auto& colors = competition_winner.palette_override(view.title); + present_season(competition_winner.render(state, view), + ("OpenBMH - competition_winner_" + std::to_string(view.title) + "_" + + std::to_string(view.team)).c_str(), colors ? &*colors : nullptr); + wait_sportschau_ack(); // SDLFlushEvents2 waits for a mouse press; ESC is ignored. + }; + sportschau_presenter.awards = [&](const GameState& state, const SportschauAwardsView& view) { + if (!running) return; + present_season(sportschau_eleven.render(view, sportschau_context(state).gradient_text), + ("OpenBMH - sportschau_eleven_" + std::to_string(view.group)).c_str()); + wait_sportschau_ack(); + }; + sportschau_presenter.team_info = [&](const GameState& state, const SportschauTeamInfoView& view) { + if (!running) return; + present_season(sportschau_team_info.render(view, sportschau_context(state).gradient_text), + ("OpenBMH - sportschau_teaminfo_" + std::to_string(view.group)).c_str()); + wait_sportschau_ack(); + }; + auto show_tax = [&](const GameState& state, const SeasonTaxEvent& event) -> bool { + if (!running) return false; + const size_t base = size_t(event.manager_slot) * 0xb0c; + ui::TaxDialogProjection view; + view.kind = event.kind == SeasonTaxEventKind::question + ? ui::TaxDialogKind::question : ui::TaxDialogKind::acknowledgement; + view.compact_dialog_frame = state.memory.has(::bmh::layout::CompactDialogFrame) && state.memory.u8(::bmh::layout::CompactDialogFrame) != 0; + for (size_t i = 0; i < 30 && state.manager_records[base + 0xa8 + i]; ++i) + view.manager_name += char(state.manager_records[base + 0xa8 + i]); + view.body = event.text; + view.portrait = state.manager_records[base + 0x221]; + view.badge_fallback = event.team == 0x0fff || (event.team > 89 && event.team < 138) || + (event.team > 167 && event.team < 357); + view.badge_sprite = view.badge_fallback ? 0 : le16(state.club_heap_78, size_t(event.team) * 2) & 0x1ff; + ui::GameEndTaxDialog screen(data, std::move(view), game_end_options(state), + event.kind == SeasonTaxEventKind::outcome ? season_backdrop : std::optional{}); + auto complete = [&](bool answer) { + present_season(screen.backdrop(), "OpenBMH - season_tax_restored"); + return answer; + }; + present_season(screen.render(), event.kind == SeasonTaxEventKind::question + ? "OpenBMH - season_tax_question" : event.kind == SeasonTaxEventKind::notice + ? "OpenBMH - season_tax_notice" : "OpenBMH - season_tax_outcome"); + auto pressed = ui::GameEndTaxDialog::Button::none; + while (running) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return false; } + if (input.type == SDL_MOUSEBUTTONDOWN) { + if (event.kind != SeasonTaxEventKind::question && + input.button.button == SDL_BUTTON_RIGHT) return complete(false); + if (input.button.button != SDL_BUTTON_LEFT) continue; + pressed = screen.hit_test(input.button.x, input.button.y); + if (event.kind != SeasonTaxEventKind::question && + pressed == ui::GameEndTaxDialog::Button::none) return complete(false); + } else if (input.type == SDL_MOUSEMOTION && + screen.hit_test(input.motion.x, input.motion.y) != pressed) { + pressed = ui::GameEndTaxDialog::Button::none; + } else if (input.type == SDL_MOUSEBUTTONUP && input.button.button == SDL_BUTTON_LEFT) { + const auto button = screen.hit_test(input.button.x, input.button.y); + if (pressed != ui::GameEndTaxDialog::Button::none && button == pressed) { + if (button == ui::GameEndTaxDialog::Button::yes) return complete(true); + return complete(false); + } + pressed = ui::GameEndTaxDialog::Button::none; + } + } + SDL_Delay(10); + } + return false; + }; + SeasonTaxHooks tax_presenter; + tax_presenter.choose = show_tax; + tax_presenter.observe = [&](const GameState& state, const SeasonTaxEvent& event) { + if (event.kind == SeasonTaxEventKind::notice || event.kind == SeasonTaxEventKind::outcome) + (void)show_tax(state, event); + if (running && event.kind == SeasonTaxEventKind::animation) { + ui::GameEndTaxAnimationScreen animation(ui::load_game_end_tax_animation_assets(data), + unsigned(event.animation_variant), season_backdrop ? *season_backdrop : flow.render(), + state.memory.has(::bmh::layout::SolidPanelBackground) && state.memory.u8(::bmh::layout::SolidPanelBackground) != 0); + while (running && animation.advance_step()) { + present_season(animation.render(), "OpenBMH - season_tax_animation"); + const auto started = SDL_GetTicks(); + while (running && Uint32(SDL_GetTicks() - started) < animation.wait_milliseconds()) { + SDL_Event input; + while (SDL_PollEvent(&input)) if (input.type == SDL_QUIT) running = false; + // Source param4=0: clicks/keys cannot change this script or RNG. + SDL_Delay(10); + } + } + // Source marker150 flips buffers without copying the visible frame. + // Outcome ACK must start on the older drawing frame in this case. + season_backdrop = animation.drawing_frame(); + } + }; + auto wait_promotion_time = [&](Uint32 milliseconds) { + const auto start = SDL_GetTicks(); + while (running && Uint32(SDL_GetTicks() - start) < milliseconds) { + // SeasonPromotionScreen does not read gameplay input. Keep queued mouse/keyboard + // events for the next Original input boundary; only handle SDL exit. + SDL_PumpEvents(); + SDL_Event quit; + if (SDL_PeepEvents(&quit, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false; + if (running) SDL_Delay(10); + } + }; + SeasonPromotionHook promotion_presenter = [&](const GameState& state, const SeasonPromotionEvent& event) { + if (!running) return; + auto view = ui::season_promotion_from_game(state, event, season_exe, season_texts); + ui::SeasonPromotionScreen screen(data, std::move(view)); + const auto show_step = [&](int step) { + const auto title = "OpenBMH - season_promotion_" + std::to_string(event.group) + "_" + std::to_string(step); + present_season(screen.render(step), title.c_str()); + }; + show_step(0); + // Original checks the manager's stored animation-skip flag once, + // after presenting the starting table, before both 50-tick waits. + if (state.memory.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) && state.memory.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) != 0) return; + wait_promotion_time(50 * 20); + for (int step = 1; running && step <= 38; ++step) show_step(step); + if (running) wait_promotion_time(50 * 20); + }; + auto present_pending_dialog = [&](const GameState& state, ui::TaxDialogProjection view, + const Image& backdrop, const char* title, + std::optional effective_options = {}) -> PendingOfferAnswer { + if (!running) return PendingOfferAnswer::unsupported; + const bool question = view.kind == ui::TaxDialogKind::question; + if (question) press.reset(); // PresentManagerDialog owns the caller's input now. + ui::GameEndTaxDialog screen(data, std::move(view), + effective_options ? *effective_options : game_end_options(state), backdrop); + const bool timed = screen.source_timed_notice(); + if (!question) app::original_audio_command(playback, timed ? 13 : 14); // PresentManagerDialog / SystemIdentity. + const Uint32 started = SDL_GetTicks(); + auto pressed = ui::GameEndTaxDialog::Button::none; + const auto show = [&] { + std::string name = title; + if (pressed == ui::GameEndTaxDialog::Button::yes) name += "_pressed_yes"; + else if (pressed == ui::GameEndTaxDialog::Button::no) name += "_pressed_no"; + else if (pressed == ui::GameEndTaxDialog::Button::acknowledge) name += "_pressed_ack"; + present_season(screen.render(pressed), name.c_str()); + }; + const auto complete = [&](PendingOfferAnswer answer) { + present_season(screen.backdrop(), "OpenBMH - pending_offer_dialog_restored"); + return answer; + }; + show(); + if (!state.memory.has(::bmh::layout::Main_Screen_RuntimeField2) || state.memory.u8(::bmh::layout::Main_Screen_RuntimeField2) == 0) + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + while (running) { + // PresentManagerDialog polls2de66 after its initial Present.ExpireQuestion keeps + // a held left control until its UP/leave while the clock runs. + if (question && poll_process_timer(true,true) && + pressed == ui::GameEndTaxDialog::Button::none) + return complete(PendingOfferAnswer::no); + if (timed && Uint32(SDL_GetTicks() - started) >= 70 * 3 * 20) + return complete(PendingOfferAnswer::yes); + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return PendingOfferAnswer::unsupported; } + const bool question_deadline = question && poll_process_timer(true,true); + if (question_deadline && pressed == ui::GameEndTaxDialog::Button::none) + return complete(PendingOfferAnswer::no); + if (input.type == SDL_MOUSEBUTTONDOWN) { + if (timed && (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) + return complete(PendingOfferAnswer::yes); + // ExpireQuestion consumes the paired left release. Right/ESC + // do not choose a question answer or interrupt that hold. + if (!question && pressed == ui::GameEndTaxDialog::Button::none && + input.button.button == SDL_BUTTON_RIGHT) + return complete(PendingOfferAnswer::yes); + if (input.button.button != SDL_BUTTON_LEFT) continue; + pressed = screen.hit_test(input.button.x, input.button.y); + if (!question && pressed == ui::GameEndTaxDialog::Button::none) + return complete(PendingOfferAnswer::yes); + show(); + } else if (input.type == SDL_MOUSEMOTION && + pressed != ui::GameEndTaxDialog::Button::none && + screen.hit_test(input.motion.x, input.motion.y) != pressed) { + if (!question) return complete(PendingOfferAnswer::yes); + pressed = ui::GameEndTaxDialog::Button::none; + show(); + } else if (input.type == SDL_MOUSEBUTTONUP && input.button.button == SDL_BUTTON_LEFT) { + //PresentManagerDialog forces button1/No after4885b returns when the + //signed Source deadline is negative, even after Yes UP. + if (question_deadline) return complete(PendingOfferAnswer::no); + const auto released = screen.hit_test(input.button.x, input.button.y); + if (pressed != ui::GameEndTaxDialog::Button::none && released == pressed) + return complete(pressed == ui::GameEndTaxDialog::Button::no + ? PendingOfferAnswer::no : PendingOfferAnswer::yes); + if (!question && pressed != ui::GameEndTaxDialog::Button::none) + return complete(PendingOfferAnswer::yes); + pressed = ui::GameEndTaxDialog::Button::none; + show(); + } + } + SDL_Delay(10); + } + return PendingOfferAnswer::unsupported; + }; + auto loan_return_presenter = [&](GameState& state, WatcomRandom&, int manager, + const std::string& question) -> int { + if (!running) return -1; + const Image backdrop = season_backdrop ? *season_backdrop : flow.render(); + const auto answer = present_pending_dialog(state, + ui::loan_return_question_dialog(state, manager, question), backdrop, + "OpenBMH - loan_return_question"); + if (answer == PendingOfferAnswer::yes) return 1; + if (answer == PendingOfferAnswer::no) return 0; + return -1; + }; + auto make_pending_offer_hooks = [&](Image backdrop) { + auto pending_backdrop = std::make_shared(std::move(backdrop)); + PendingOfferHooks hooks; + hooks.answer = [&, pending_backdrop](const GameState& staged, const PendingOfferQuestion& question) { + return present_pending_dialog(staged, ui::pending_offer_question_dialog(staged, question), + *pending_backdrop, question.kind == PendingOfferQuestionKind::salary_demand + ? "OpenBMH - pending_offer_salary_question" : "OpenBMH - pending_offer_severance_question"); + }; + hooks.select_transfer = [&, pending_backdrop](const GameState& staged, const TransferOfferListView& offers) { + ui::IncomingTransferScreen screen(data, + ui::pending_offer_transfer_decision_from_game(staged, offers), + staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0); + *pending_backdrop = screen.render(); + present_season(*pending_backdrop, "OpenBMH - pending_offer_transfer"); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); // DecodeTaxAnimationScript/SDLFlushEvents redraw boundary + while (running) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return PendingOfferTransferChoice{}; } + std::optional bid; + if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) + bid = screen.click(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + // IncomingTransferScreen reads event2/8 directly: release and + // physical ESC never select or decline this row. + if (bid) return PendingOfferTransferChoice{ + *bid < 0 ? PendingOfferTransferChoiceKind::decline : PendingOfferTransferChoiceKind::bid, *bid}; + } + SDL_Delay(10); + } + return PendingOfferTransferChoice{}; + }; + hooks.notice = [&, pending_backdrop](const GameState& staged, const PendingOfferNotice& notice) { + if (present_pending_dialog(staged, ui::pending_offer_notice_dialog(staged, notice), + *pending_backdrop, "OpenBMH - pending_offer_notice") == PendingOfferAnswer::unsupported) + throw std::runtime_error("pending offer presenter stopped"); + }; + hooks.program_error = [&, pending_backdrop](const GameState& staged, uint16_t code) { + ui::ProgramErrorScreen screen(data,code,game_end_options(staged)); + press.reset(); + SDL_FlushEvents(SDL_MOUSEMOTION,SDL_MOUSEBUTTONUP); + present_season(screen.render(),"OpenBMH - program_error"); + bool acknowledged=false; + while(running && !acknowledged) { + SDL_Event event; + while(SDL_PollEvent(&event)) { + if(event.type==SDL_QUIT){running=false;break;} + if(event.type==SDL_MOUSEBUTTONDOWN && + (event.button.button==SDL_BUTTON_LEFT || event.button.button==SDL_BUTTON_RIGHT)) { + acknowledged=true;break; + } + } + if(!acknowledged && running)SDL_Delay(10); + } + if(!running)throw std::runtime_error("program-error acknowledgement interrupted"); + present_season(*pending_backdrop,"OpenBMH - pending_offer_dialog_restored"); + }; + return hooks; + }; + auto make_market_sale_hooks = [&](Image backdrop) { + auto market_backdrop = std::make_shared(std::move(backdrop)); + HumanBuyerSaleHooks hooks; + hooks.notice = [&, market_backdrop](const GameState& staged, const HumanBuyerSaleNotice& notice) { + const PendingOfferNotice projection_notice{notice.manager, notice.raw_offer_slot, + notice.source_text_address, notice.original_message}; + if (present_pending_dialog(staged, ui::pending_offer_notice_dialog(staged, projection_notice), + *market_backdrop, "OpenBMH - transfer_market_notice") == PendingOfferAnswer::unsupported) + throw std::runtime_error("transfer market presenter stopped"); + }; + return hooks; + }; + std::function present_club_information; + std::function(app::ClubModalServices&,const ClubPlayerDetailSelection&,const Image&)> present_player_detail; + auto loan_return_offer_presenter = [&](GameState& staged, GameRandom& game_random, + WatcomRandom& watcom_random, app::ClubModalServices& services, + int manager, int source_slot, int list_entry, + const HumanBuyerSaleHooks& sale_hooks) -> int { + if (!running || manager < 0 || manager >= 4 || list_entry < 40 || list_entry >= 44 || + source_slot != 2928 + list_entry || !staged.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57)) + return -1; + const uint32_t row = ::bmh::layout::EditorList + uint32_t(list_entry) * 0x58; + const int player = staged.squad_slots.at(size_t(source_slot)) & 0x0fff; + const uint16_t seller_word = staged.memory.u16(row + 8); + int bid_slot = -1; + for (int i = 0; i < 4; ++i) { + const uint16_t word = staged.memory.u16(row + uint32_t(i) * 2); + if (word == 0xffff || word == staged.manager_teams.at(size_t(manager))) { bid_slot = i; break; } + } + TransferOfferEditorRequest input; + input.manager = manager; + input.runtime_club = staged.manager_teams.at(size_t(manager)); + input.list_entry = list_entry; + input.source_slot = source_slot; + input.expected_player = player; + input.expected_seller_word = seller_word; + input.expected_bid_slot = bid_slot; + input.loan = false; + input.loan_return_entry = true; + auto owner = open_transfer_offer_editor_source(staged, input, game_random, watcom_random); + if (!owner.supported || owner.closed) return -1; + ui::OutgoingTransferScreen screen(data, app::loan_return_offer_editor_projection( + staged, owner, revision, (!staged.memory.has(::bmh::layout::TextGradientDisabled) || staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2)); + const Image backdrop = flow.render(); + const auto draw = [&] { present_season(screen.render(), "OpenBMH - loan_return_offer"); }; + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + draw(); + while (running) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return -1; } + ui::OutgoingTransferRequest action; + if (event.type == SDL_MOUSEMOTION) continue; + if (event.type == SDL_MOUSEBUTTONDOWN) { + action = screen.click(event.button.x, event.button.y, + event.button.button == SDL_BUTTON_RIGHT, event.button.clicks > 1); + } else if (event.type == SDL_KEYDOWN) { + const char* name = SDL_GetKeyName(event.key.keysym.sym); + std::string key = name ? name : ""; + std::transform(key.begin(), key.end(), key.begin(), + [](unsigned char c) { return char(std::toupper(c)); }); + action = screen.key(key); + } else if (event.type == SDL_TEXTINPUT) { + (void)screen.text(event.text.text); + } + if (action.kind == ui::OutgoingTransferRequestKind::none) { draw(); continue; } + if (action.kind == ui::OutgoingTransferRequestKind::cancel) { + (void)cancel_transfer_offer_editor_source(staged, owner); + return 0; + } + if (action.kind == ui::OutgoingTransferRequestKind::edit_field || + action.kind == ui::OutgoingTransferRequestKind::quote_change) { + owner = app::edit_transfer_offer_from_ui(staged, owner, action, + game_random, watcom_random); + if (!owner.supported) return -1; + screen.acknowledge(app::loan_return_offer_editor_projection(staged, owner, revision, + (!staged.memory.has(::bmh::layout::TextGradientDisabled) || staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2)); + draw(); + continue; + } + if (action.kind == ui::OutgoingTransferRequestKind::team_info) { + const auto validated = cancel_transfer_offer_editor_source(staged, owner); + if (!validated.supported || !present_club_information || + !present_club_information(services, int(seller_word & 0x7fff))) return -1; + owner = resume_transfer_offer_team_info_source(staged, owner, watcom_random); + if (!owner.supported) return -1; + screen.acknowledge(app::loan_return_offer_editor_projection(staged, owner, revision, + (!staged.memory.has(::bmh::layout::TextGradientDisabled) || staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2)); + draw(); + continue; + } + if (action.kind == ui::OutgoingTransferRequestKind::player_info) { + if (!present_player_detail) return -1; + const auto selection = transfer_offer_player_info_selection_source(staged, owner); + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField, 1); + if (!present_player_detail(services, selection, screen.render()).has_value()) return -1; + owner = resume_transfer_offer_player_info_source(staged, owner, + services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField), services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), watcom_random); + if (!owner.supported) return -1; + screen.acknowledge(app::loan_return_offer_editor_projection(staged, owner, revision, + (!staged.memory.has(::bmh::layout::TextGradientDisabled) || staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2)); + draw(); + continue; + } + if (action.kind == ui::OutgoingTransferRequestKind::submit) { + MinuteReport report; + auto submitted = submit_transfer_offer_editor_source(staged, owner, watcom_random, sale_hooks, report); + if (report.unsupported || submitted.action.status == TransferActionStatus::unsupported) return -1; + if (submitted.editor.closed || submitted.action.status == TransferActionStatus::pending || + submitted.action.status == TransferActionStatus::rejected || + submitted.action.status == TransferActionStatus::insufficient_funds) return 1; + owner = std::move(submitted.editor); + screen.acknowledge(app::loan_return_offer_editor_projection(staged, owner, revision, + (!staged.memory.has(::bmh::layout::TextGradientDisabled) || staged.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2)); + draw(); + } + } + if (playback.needs_pump()) playback.pump(audio_error); + SDL_Delay(10); + } + (void)backdrop; + return -1; + }; + // Assigned to the genuine Source submodal presenters below before the + // controller advances a new career or annual transition. + std::function present_club_player; + std::function present_club_statistics; + bool poach_selection_active=false; + std::optional poach_card_selection; + present_club_information = [&](app::ClubModalServices& services, int team) -> bool { + if (!running) return false; + //ClubInfoFromGame owns the opening DOWN and consumes its paired UP inside + // this synchronous loop. The parent must not retain a held press + // after that UP has already been consumed by the child. + press.reset(); + ui::ClubInfoView selected_view = ui::ClubInfoView::data_a; + std::unique_ptr club_screen; + const auto redraw = [&] { + std::string error; + ClubInfoEntry snapshot; + if (team == kNoTeam || team < season_exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) { + snapshot = services.enter_club(team); + } + auto projection = ui::club_info_from_game(services.state(), team, snapshot, + season_exe, season_texts); + projection.view = selected_view; + club_screen = std::make_unique(data, std::move(projection)); + }; + const auto show = [&] { + auto title = "OpenBMH - cup_club_info_" + std::to_string(team) + "_" + + std::to_string(int(selected_view)) + "_category_" + + std::to_string(club_screen->projection().category); + if (club_screen->pressed_button()) + title += "_pressed_" + std::to_string(int(*club_screen->pressed_button())); + else if (club_screen->hovered_row()) + title += "_hover_" + std::to_string(*club_screen->hovered_row()); + present_season(club_screen->render(), title.c_str()); + }; + redraw(); show(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + const auto deadline_expired = [&] { + return !club_screen->pressed_button() && poll_process_timer(true, true); + }; + while (running) { + if (deadline_expired()) return true; //ClubInfoFromGame event8 returns to its owning caller. + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return false; } + if (deadline_expired()) return true; + ui::ClubInfoRequest request; + if (input.type == SDL_MOUSEMOTION) { + if (club_screen->move(input.motion.x, input.motion.y)) show(); + } else if (input.type == SDL_MOUSEBUTTONDOWN) { + if (input.button.button == SDL_BUTTON_RIGHT) return true; + if (input.button.button != SDL_BUTTON_LEFT) continue; + (void)club_screen->move(input.button.x, input.button.y); + request = club_screen->pointer_down(input.button.x, input.button.y); + if (request.kind == ui::ClubInfoRequestKind::none) { + club_screen->press(input.button.x, input.button.y); + show(); + } + } else if (input.type == SDL_MOUSEBUTTONUP && input.button.button == SDL_BUTTON_LEFT) { + request = club_screen->release(input.button.x, input.button.y); + show(); + } + switch (request.kind) { + case ui::ClubInfoRequestKind::none: break; + case ui::ClubInfoRequestKind::close: return true; + case ui::ClubInfoRequestKind::toggle_view: + selected_view = selected_view == ui::ClubInfoView::data_a + ? ui::ClubInfoView::data_b : ui::ClubInfoView::data_a; + redraw(); show(); + break; + case ui::ClubInfoRequestKind::change_category: { + std::string error; + const auto applied = services.change_category(team, request.requested_category); + // Source changes the icon without re-entering2af41 or + // altering the list's owned pre-cleanup drawing flags. + auto projection = club_screen->projection(); + projection.category = applied; + club_screen = std::make_unique(data, std::move(projection)); + show(); + break; + } + case ui::ClubInfoRequestKind::open_statistics: + if (!present_club_statistics) throw FormatError("club statistics presenter is unavailable"); + present_club_statistics(services, team, club_screen->render()); + if (!running) return false; + redraw(); show(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + break; + case ui::ClubInfoRequestKind::open_player_detail: + if (!present_club_player) throw FormatError("club player presenter is unavailable"); + if (present_club_player(services, request, club_screen->render())) return true; + if (!running) return false; + redraw(); show(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + break; + } + } + SDL_Delay(10); + } + return false; + }; + present_club_player = [&](app::ClubModalServices& services, const ui::ClubInfoRequest& selected, const Image& parent_image) { + if (!running) return false; + const ClubPlayerDetailSelection selection{selected.runtime_team, selected.player_id, + selected.rendered_row, selected.physical_row, selected.human_loan_index}; + const uint8_t prior_mode = services.runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField); + const uint8_t input_mode = club_player_detail_input_mode(prior_mode); + struct PlayerInputModeRestore { + app::ClubModalServices& services; + uint8_t prior; + ~PlayerInputModeRestore() { services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField, prior); } + } mode_restore{services, prior_mode}; + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField, input_mode); + if(!present_player_detail)throw FormatError("generic player presenter unavailable"); + return present_player_detail(services,selection,parent_image).value_or(false); + }; + present_player_detail = [&](app::ClubModalServices& services,const ClubPlayerDetailSelection& selection,const Image& parent_image) -> std::optional { + if(!running)return std::nullopt; + press.reset(); //ClubPlayerDetailFromGame now owns physical hold/release through its own Source wait. + const uint8_t input_mode=services.runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField); + size_t rebuild_count = 0; + const auto rebuild = [&] { + std::string error; + auto redraw = services.redraw_player(selection); + ++rebuild_count; + return ui::club_player_detail_from_game(services.state(), std::move(redraw), season_exe); + }; + ui::ClubPlayerDetailScreen card(data, rebuild(), parent_image); + const auto show = [&] { + const auto title = "OpenBMH - cup_player_detail_" + std::to_string(selection.runtime_team) + + "_" + std::to_string(selection.player_id) + (card.in_statistics() ? "_player_statistics_" : "_card_") + + "_statistics_flags_" + std::to_string(card.projection().statistics_flags) + + "_rebuild_" + std::to_string(rebuild_count); + present_season(card.render(), title.c_str()); + }; + const auto wait_prior_left_release = [&] { + if (input_mode == 0) return; + // Source waits only for an already set CareerSession_InitializeClubModalRuntime_ExecutableField (>25 held ticks), + // then clears it. A fresh list DOWN is not an already held flag. + const bool prior_long_hold = services.runtime_byte(::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableField) != 0; + if (!prior_long_hold) return; + SDL_PumpEvents(); + while (running && (SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) { + SDL_Event input; + while (SDL_PollEvent(&input)) + if (input.type == SDL_QUIT) { running = false; return; } + SDL_PumpEvents(); + if (running) SDL_Delay(10); + } + services.set_runtime_byte(::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableField, 0); // Source consumes the owned hold flag. + }; + show(); wait_prior_left_release(); + std::optional held_left_since; + SDL_PumpEvents(); + // ClubPlayerDetailFromGame consumes the opening DOWN when bbcde!=0. Only its + // selection mode retains that inherited DOWN as a hold candidate. + if (input_mode == 0 && (SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) + held_left_since = ui::pointer_hold_source_ticks(SDL_GetTicks64()); + const auto apply_request = [&](ui::ClubPlayerDetailRequest request) -> std::optional { + switch (request.kind) { + case ui::ClubPlayerDetailRequestKind::none: return std::nullopt; + case ui::ClubPlayerDetailRequestKind::close: + if(poach_selection_active && input_mode==0 && request.source_return>0) + poach_card_selection=request.selection; + present_season(parent_image, "OpenBMH - cup_club_player_restored"); + return request.close_parent(); + case ui::ClubPlayerDetailRequestKind::redraw_card: { + // CopyOpaqueSlice saves active-manager preferences only on exit. + const int manager = card.projection().redraw.context.active_manager; + const uint32_t flags = ::bmh::layout::Flags + uint32_t(manager) * 3 + 2; + if (!services.state().memory.has(flags)) + throw FormatError("club player statistics: active preference block missing"); + services.state().memory.set8(flags, request.statistics_flags); + card.replace_redraw(rebuild()); // One actual42dbd rebuild, never per presentation. + held_left_since.reset(); + show(); wait_prior_left_release(); + return std::nullopt; + } + case ui::ClubPlayerDetailRequestKind::national_action: { + present_season(parent_image, "OpenBMH - cup_club_player_restored"); + std::string error; + (void)services.national_action(request.selection); + // Source returnsff even when a full national squad prevents an add. + return request.close_parent(); + } + case ui::ClubPlayerDetailRequestKind::offer_action: { + // ClubPlayerDetailFromGame restores its saved parent before3140f; the + // question overlays the club list, not the departed card. + present_season(parent_image, "OpenBMH - pending_offer_parent_restored"); + const auto hooks = make_pending_offer_hooks(parent_image); + std::string error; + try { (void)services.pending_offers(request.selection, hooks); } + catch(const std::exception& e) { + if(services.transactional)throw; + if(running) {std::fprintf(stderr,"pending offer: %s\n",e.what());show();} + return std::nullopt; + } + present_season(parent_image, "OpenBMH - cup_club_player_restored"); + return request.close_parent(); + } + } + return std::nullopt; + }; + const auto expire_card = [&]() -> std::optional { + if (card.source_mouse_wait_release_pending()) return std::nullopt; + if (poll_process_timer(true, true) && card.process_timer_expired()) + return apply_request(card.take_request()); + return std::nullopt; + }; + while (running) { + if (const auto complete = expire_card()) return *complete; + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return std::nullopt; } + if (const auto complete = expire_card()) return *complete; + bool changed = false; + if (input.type == SDL_MOUSEMOTION) { + changed = card.move(input.motion.x, input.motion.y); + if (changed) held_left_since.reset(); // ExpireQuestion move-out cancels its held press. + } else if (input.type == SDL_MOUSEBUTTONDOWN) { + if (input.button.button == SDL_BUTTON_RIGHT) { + held_left_since.reset(); + changed = card.press(input.button.x, input.button.y, true); + } else if (input.button.button == SDL_BUTTON_LEFT) { + // ExpireQuestion waits for the paired release itself; + // its button hold does not run42dbd's hold shortcut. + held_left_since.reset(); + changed = card.press(input.button.x, input.button.y); + } + } else if (input.type == SDL_MOUSEBUTTONUP && input.button.button == SDL_BUTTON_LEFT) { + held_left_since.reset(); + changed = card.release(input.button.x, input.button.y); + } + const auto request = card.take_request(); + if (const auto complete = apply_request(request)) return *complete; + if (!running) return std::nullopt; + if (changed && request.kind == ui::ClubPlayerDetailRequestKind::none) show(); + } + if (held_left_since) { + SDL_PumpEvents(); + if (!(SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) held_left_since.reset(); + else if (card.held_left_ticks(uint32_t(ui::pointer_hold_source_ticks(SDL_GetTicks64()) - *held_left_since))) { + if (const auto complete = apply_request(card.take_request())) return *complete; + } + } + SDL_Delay(10); + } + return std::nullopt; + }; + present_club_statistics = [&](app::ClubModalServices& services, int team, const Image& parent_frame) { + if (!running) return; + auto mode = ui::TeamStatisticsMode::combined; + std::unique_ptr statistics; + const auto rebuild = [&] { + auto projection = ui::team_statistics_from_game(services.state(), team, mode, + season_exe, season_texts); + statistics = std::make_unique(data, + std::move(projection), parent_frame); + }; + const auto show = [&] { + auto title = "OpenBMH - cup_team_statistics_" + std::to_string(team) + + "_mode_" + std::to_string(int(mode)); + if (statistics->pressed_button()) + title += "_pressed_" + std::to_string(int(*statistics->pressed_button())); + present_season(statistics->render(), title.c_str()); + }; + rebuild(); show(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + const auto deadline_expired = [&] { + return !statistics->pressed_button() && poll_process_timer(true, true); + }; + while (running) { + if (deadline_expired()) return; //LeagueCalculations frees its child before4f548 polls again. + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return; } + if (deadline_expired()) return; + if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_RIGHT) + return; // ExpireQuestion right DOWN: do not wait for release. + if (input.type == SDL_MOUSEMOTION) { + if (statistics->move(input.motion.x, input.motion.y)) show(); + } else if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_LEFT) { + statistics->press(input.button.x, input.button.y); + show(); + } else if (input.type == SDL_MOUSEBUTTONUP && input.button.button == SDL_BUTTON_LEFT) { + const auto request = statistics->release(input.button.x, input.button.y); + if (request.kind == ui::TeamStatisticsRequestKind::close) return; + if (request.kind == ui::TeamStatisticsRequestKind::change_mode) { + mode = request.mode; + rebuild(); // Pure Source table projection; neither RNG advances. + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + } + show(); + } + // OriginalMouseSound keys, including ESC, do not select a button. + } + SDL_Delay(10); + } + }; + app::CareerSession::PoachPlayerSelector poach_player_selector = + [&](app::CareerSession& staged,app::ClubModalServices&,int manager, + uint64_t& selection_revision,const Image& transfer_backdrop) + -> std::optional { + using Phase=app::CareerSession::TableDispatchPhase; + press.reset(); // The synchronous Source player-selection loop owns its input. + std::string error; + auto page=staged.current_league_table_dispatch(error); + if(!page)throw FormatError(error); + const auto present=[&](const Image& frame,const std::string& title) { + SDL_SetWindowTitle(window,title.c_str());season_backdrop=frame; + const auto painted=process_timer_image(frame); + for(size_t i=0;i table; + const auto rebuild=[&] { + auto tables=ui::league_tables_from_game(staged.state(),manager); + tables[size_t(page->identity.league)]=page->page; + table=std::make_unique(data,std::move(tables),page->identity.league, + ui::LeagueTableScreen::FamilyMode{page->identity,1}); + }; + const auto show_table=[&] { + present(table->render(),"OpenBMH - poach_table_"+std::to_string(page->identity.league)); + if(page->phase==Phase::forecast_pending_present) { + ui::LeagueFamilyRequest ack; + ack.identity=page->identity;ack.kind=ui::LeagueFamilyRequestKind::table_forecast_presented; + ack.from_child=1; + page=staged.acknowledge_league_forecast_present(ack,selection_revision,error); + if(!page)throw FormatError(error); + rebuild(); // Retain forecast pixels, refresh only the stale-request token. + } + }; + const auto run_range=[&](Image backdrop,ui::TableRangeDialogProfile profile) + -> ui::TableRangeDialogOutcome { + ui::LeagueTableRangeDialog dialog(data,std::move(backdrop),std::move(profile)); + std::deque keys; + Uint32 clock_anchor=SDL_GetTicks(); + std::optional outcome; + const auto show=[&] { + present(dialog.render(),"OpenBMH - poach_table_range"); + outcome=dialog.after_present();clock_anchor=SDL_GetTicks(); + }; + const auto expire_range=[&] { + //BalanceFromGame polls raw event8 before its next input. Keep its + //key/N waits and accepted value owner; expose cancellation + //only after the restored backdrop has actually been shown. + if(!dialog.source_input_ready() || !poll_process_timer(true,true) || + !dialog.cancel_from_source_event())return false; + show(); + return true; + }; + show(); + while(running&&!outcome) { + if(expire_range())break; + SDL_Event input; + while(SDL_PollEvent(&input)) { + if(input.type==SDL_QUIT){running=false;break;} + if(expire_range())break; + bool changed=false; + if(input.type==SDL_TEXTINPUT) { + for(char c:std::string_view(input.text.text))if(c>='0'&&c<='9')keys.emplace_back(1,c); + } else if(input.type==SDL_KEYDOWN) { + if(input.key.keysym.sym==SDLK_RETURN)keys.push_back("ENTER"); + else if(input.key.keysym.sym==SDLK_BACKSPACE)keys.push_back("BACKSPACE"); + else if(input.key.keysym.sym==SDLK_SPACE)keys.push_back("SPACE"); + } else if(input.type==SDL_MOUSEMOTION)changed=dialog.move(input.motion.x,input.motion.y); + else if(input.type==SDL_MOUSEBUTTONDOWN&& + (input.button.button==SDL_BUTTON_LEFT||input.button.button==SDL_BUTTON_RIGHT)) + changed=dialog.pointer_down(input.button.x,input.button.y,input.button.button==SDL_BUTTON_RIGHT); + else if(input.type==SDL_MOUSEBUTTONUP&& + (input.button.button==SDL_BUTTON_LEFT||input.button.button==SDL_BUTTON_RIGHT)) + changed=dialog.pointer_up(input.button.x,input.button.y,input.button.button==SDL_BUTTON_RIGHT); + // A drag-only release does not restart an existing Source wait. + if(changed&&input.type!=SDL_MOUSEBUTTONUP)show(); + if(outcome)break; + } + if(!running||outcome)break; + while(!keys.empty()&&dialog.source_input_ready()) { + if(expire_range())break; + const auto key=std::move(keys.front());keys.pop_front(); + if(dialog.key(key))show(); + if(outcome)break; + } + const Uint32 now=SDL_GetTicks(),units=Uint32(now-clock_anchor)/20; + if(units) { + clock_anchor+=units*20; + if(dialog.tick_source_units(units))show(); + } + SDL_Delay(10); + } + if(!outcome)throw FormatError("poach: range presenter stopped"); + return *outcome; + }; + rebuild();show_table(); + poach_selection_active=true;poach_card_selection.reset(); + struct ResetSelection { bool& active;~ResetSelection(){active=false;} } reset{poach_selection_active}; + const auto deadline_expired=[&] { + if(table->pending_family_action() || table->source_mouse_wait_release_pending() || + !poll_process_timer(true,true))return false; + //Move/4ffe0 selection owner must close before19c1c resumes. + if(!table->pointer_down(0,0,true) || !table->pending_family_action() || + table->pending_family_action()->kind!=ui::LeagueFamilyRequestKind::close) + throw FormatError("poach: timer close has no table owner"); + if(!staged.close_poach_table_selection(*table->pending_family_action(),error)) + throw FormatError(error); + present(transfer_backdrop,"OpenBMH - poach_transfer_restored"); + return true; + }; + while(running) { + if(deadline_expired())return std::nullopt; + SDL_Event input; + while(SDL_PollEvent(&input)) { + if(input.type==SDL_QUIT){running=false;break;} + if(deadline_expired())return std::nullopt; + bool changed=false; + if(input.type==SDL_MOUSEBUTTONDOWN&& + (input.button.button==SDL_BUTTON_LEFT||input.button.button==SDL_BUTTON_RIGHT)) + changed=table->pointer_down(input.button.x,input.button.y,input.button.button==SDL_BUTTON_RIGHT); + else if(input.type==SDL_MOUSEBUTTONUP&&input.button.button==SDL_BUTTON_LEFT) + changed=table->click(input.button.x,input.button.y); + else if(input.type==SDL_MOUSEMOTION)changed=table->move(input.motion.x,input.motion.y); + if(!table->pending_family_action()) {if(changed)show_table();continue;} + const auto request=*table->pending_family_action(); + if(request.kind==ui::LeagueFamilyRequestKind::close) { + if(!staged.close_poach_table_selection(request,error))throw FormatError(error); + present(transfer_backdrop,"OpenBMH - poach_transfer_restored"); + return std::nullopt; + } + if(request.kind==ui::LeagueFamilyRequestKind::select_league || + request.kind==ui::LeagueFamilyRequestKind::toggle_league_group) { + const int prior_league=page->identity.league; + if(!staged.select_league_family_page(request,selection_revision,error))throw FormatError(error); + page=staged.current_league_table_dispatch(error);if(!page)throw FormatError(error); + if(page->identity.league==prior_league) { + table->acknowledge_same_league_selector(request,page->identity); + if(request.kind==ui::LeagueFamilyRequestKind::toggle_league_group)show_table(); + } else {rebuild();show_table();} + } else if(request.kind==ui::LeagueFamilyRequestKind::team_info) { + poach_card_selection.reset(); + const auto identity=staged.dispatch_family_table_team_info(request,selection_revision,error, + [&](app::ClubModalServices& services,int team,const Image&) { + return present_club_information(services,team)&&running; + },&poach_card_selection); + if(!identity)throw FormatError(error); + if(poach_card_selection) { + present(transfer_backdrop,"OpenBMH - poach_transfer_restored"); + return poach_card_selection; + } + page=staged.current_league_table_dispatch(error);if(!page)throw FormatError(error); + rebuild();show_table(); + } else if(request.kind==ui::LeagueFamilyRequestKind::control) { + const auto modal_backdrop=table->render(); + page=staged.dispatch_league_table_control(request,selection_revision,error); + if(!page)throw FormatError(error); + while(page->dialog) { + const auto stage=page->phase==Phase::range_start?ui::TableDialogStage::start:ui::TableDialogStage::end; + const auto outcome=run_range(modal_backdrop,*page->dialog); + ui::LeagueFamilyRequest reply; + reply.identity=page->identity;reply.kind=ui::LeagueFamilyRequestKind::table_range_result; + reply.from_child=1;reply.control_index=9; + reply.table_dialog_reply=ui::TableDialogReply{stage, + outcome.result==ui::TableRangeDialogResult::accept?ui::TableDialogOutcome::accept:ui::TableDialogOutcome::cancel, + outcome.result==ui::TableRangeDialogResult::accept?int(outcome.value):0,outcome.x,outcome.y}; + page=staged.dispatch_league_table_range_reply(reply,selection_revision,error); + if(!page)throw FormatError(error); + } + rebuild();show_table(); + } + } + SDL_Delay(10); + } + throw FormatError("poach: player selection presenter stopped"); + }; + // CupDrawFromGame local_14 belongs to the whole linked-record traversal. A + // skipped reveal still presents every overview; a normal reveal ACK or + // the right press leaving an overview does not skip subsequent groups. + bool group_reveal_skipped = false; + SeasonCupDrawHook cup_draw_presenter = [&](const GameState& state, const SeasonCupDrawEvent& event) { + if (!running) return; + if (event.phase == SeasonCupDrawPhase::draw) { + if (!event.group_stage || event.group_index == 0) + group_reveal_skipped = false; + if (event.group_stage && group_reveal_skipped) { + // SDLFlushEvents still runs before the native overview. + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + return; + } + } + auto view = ui::cup_draw_from_game(state, event, season_exe, season_texts); + if (!view.source_eligible) return; + ui::CupDrawScreen screen(data, std::move(view)); + bool first_draw_frame = true; + const auto show_draw = [&] { + const auto title = "OpenBMH - cup_draw_" + std::to_string(screen.revealed_count()); + present_season(screen.render(), title.c_str()); + // DecodeTaxAnimationScript(1) flushes outside script execution (Main_Screen_RuntimeField2=0). + // Script 0/1 presentations retain queued input (Main_Screen_RuntimeField2=1). + if (first_draw_frame || screen.queue_flush_needed()) + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + first_draw_frame = false; + }; + if (event.phase == SeasonCupDrawPhase::draw) { + // Source ignores the first OriginalMouseSound poll's gameplay result, then + // presents the starting scene before its ten option-delay polls. + SDL_Event initial; + if (SDL_PollEvent(&initial) && initial.type == SDL_QUIT) { running = false; return; } + show_draw(); + while (running && screen.advance_step()) { + if (screen.present_needed()) show_draw(); + wait_promotion_time(Uint32(screen.option_delay_milliseconds())); + if (!running) return; + if (screen.input_poll_needed()) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return; } + if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) { + screen.source_input(input.button.button == SDL_BUTTON_LEFT ? 2 : 8); + break; + } + } + // OriginalMouseSound synthetic left press at its normal poll + // boundary; missing transient blocks are not zero values. + if ((state.memory.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) && state.memory.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) != 0) || + (state.memory.has(::bmh::layout::CareerSession_SportschauSourceOptions_ExecutableField) && state.memory.u8(::bmh::layout::CareerSession_SportschauSourceOptions_ExecutableField) == 0)) + screen.source_input(2); + } + if (screen.held_mouse_check_needed()) { + SDL_PumpEvents(); + const auto held = SDL_GetMouseState(nullptr, nullptr); + screen.source_held_mouse(uint8_t((held & SDL_BUTTON_LMASK ? 1 : 0) | + (held & SDL_BUTTON_RMASK ? 2 : 0))); + } + if (!screen.reveal_aborted()) wait_promotion_time(Uint32(screen.wait_milliseconds())); + } + if (running && screen.reveal_complete() && !screen.reveal_aborted()) { + present_season(screen.render(), "OpenBMH - cup_draw_ack"); + wait_season_ack(); + } + if (event.group_stage && screen.reveal_aborted()) + group_reveal_skipped = true; + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); // SDLFlushEvents before native sort + return; + } + present_season(screen.render(), "OpenBMH - cup_overview"); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + while (running) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; return; } + if (input.type != SDL_MOUSEBUTTONDOWN) continue; + if (input.button.button == SDL_BUTTON_RIGHT) return; + if (input.button.button == SDL_BUTTON_LEFT) { + const auto club = screen.hit_test_team(input.button.x, input.button.y); + if (club) { + auto services=session->live_club_modal_services(revision); + (void)present_club_information(services,*club); + if (!running) return; + // Native category/squad edits belong to the clicked + // Source modal. Rebuild the overview from the current + // state while retaining its owned sorted round field. + auto current = ui::cup_draw_from_game(session->state(), event, season_exe, season_texts); + screen = ui::CupDrawScreen(data, std::move(current)); + present_season(screen.render(), "OpenBMH - cup_overview"); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + } + } + } + SDL_Delay(10); + } + }; + auto show_highscore = [&](const GameState& state, bool display) { + if (!running) return; + const auto options = game_end_options(state); + const uint16_t signature = state.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7); + if (signature == 0) { + // Source GameEndAlternateScoreScreen's alternate branch ignores display: both calls + // open the calculator, followed by one presentation for each point. + ui::GameEndAlternateScoreScreen screen(ui::load_game_end_alternate_score_assets(data), + season_backdrop ? *season_backdrop : flow.render(), options.gradient_text); + present_season(screen.render(), "OpenBMH - game_end_calculator"); + bool right_cancel = false; + while (running && screen.phase() == ui::AlternateScorePhase::Calculator) { + SDL_Event event; + bool changed = false; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return; } + if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_RIGHT) { + right_cancel = true; + changed |= screen.cancel(); // Source mouse cancellation event8 + } else if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) { + const auto button = screen.button_at(event.button.x, event.button.y); + if (button && *button < 15) { + present_season(screen.render(button), "OpenBMH - game_end_calculator"); + SDL_Delay(4 * 20); // Source DecodeTaxAnimationScript2(4), 50-Hz ticks + } + changed |= screen.mouse_down(event.button.x, event.button.y); + } else if (event.type == SDL_MOUSEMOTION) { + changed |= screen.mouse_move(event.motion.x, event.motion.y); + } else if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) { + changed |= screen.mouse_up(); + } else if (event.type == SDL_TEXTINPUT) { + changed |= screen.text(event.text.text); + } else if (event.type == SDL_KEYDOWN) { + const auto key = event.key.keysym.sym; + if (key == SDLK_RETURN) changed |= screen.key("ENTER"); + else if (key == SDLK_BACKSPACE) changed |= screen.key("BACKSPACE"); + else if (key == SDLK_SPACE) changed |= screen.key("SPACE"); + } + if (screen.phase() != ui::AlternateScorePhase::Calculator) break; + } + if (changed && screen.phase() == ui::AlternateScorePhase::Calculator) + present_season(screen.render(), "OpenBMH - game_end_calculator"); + SDL_Delay(10); + } + if (!running) return; + if (!screen.accepted_value()) { + if (!right_cancel) SDL_Delay(50 * 20); // Source N-key wait; mouse cancel skips it + present_season(screen.render(), "OpenBMH - game_end_calculator_cancelled"); + } else { + while (running && screen.advance_point()) + present_season(screen.render(), "OpenBMH - game_end_points"); + screen.finish_points(); + present_season(screen.render(), "OpenBMH - game_end_points_ack"); + wait_season_ack(); + } + } else { + const auto file = highscore_file(save_directory, signature, season_texts[889]); + auto scores = make_highscore_projection(state, load_highscore_table(file), HighscoreContext::SeasonBoundary); + // The Original stores this table outside the native FBM. Use the + // configured writable save base rather than a working-directory path. + std::error_code directory_error; + fs::create_directories(file.parent_path(), directory_error); + if (directory_error || !save_highscore_table(file, scores.rows)) + std::fprintf(stderr, "highscore: cannot write %s\n", file.string().c_str()); + if (display) { + ui::GameEndHighscoreScreen screen(data, std::move(scores), options); + present_season(screen.render(), "OpenBMH - game_end_highscore"); + wait_season_ack(); + } + } + if (display && running) { + ui::GameEndFinalScreen screen(data, options); + present_season(screen.render(), "OpenBMH - game_end_final"); + wait_season_ack(); + } + }; + std::optional timed_notice_presented_at; + std::optional timed_notice_release; + auto handle = [&](const ui::FlowResult& r) { + if (const auto* desk = flow.desktop()) + for (const auto id : desk->take_sound_ids()) app::original_audio_command(playback, id); + if (r.request == ui::FlowRequest::kickoff || r.request == ui::FlowRequest::end_session) { + // DeskDate clears CareerSession_DispatchStrengths_ExecutableField2 before returning to the match caller. + process_timer.stop(); process_timer_owner.reset(); process_timer_frame.reset(); + } else if (r.desk_action.kind == ui::DeskRequestKind::open_menu && + (r.desk_action.menu_kind == 10 || r.desk_action.menu_kind == 11 || + r.desk_action.menu_kind == 19 || r.desk_action.menu_kind == 29)) { + // ApplySettingsFile suspends save/load, settings and new-manager waits. + process_timer.pause(process_source_seconds()); process_timer_frame.reset(); + } + if (r.request == ui::FlowRequest::end_session) { + // DeskDate's confirmed socket exit tears down the running + // session without a calendar turn, RNG draw, or implicit save. + running = false; + dirty = false; + return; + } + dirty |= r.changed; + bool live_skipped = false; + uint64_t live_overview_sequence = 0; + std::optional outcome_backdrop; + auto present_live_lineup = [&](int minute, MatchEngine& engine, std::vector& groups, + GameState& state, uint64_t& live_revision, int selected_team, int selected_opponent, + const app::LiveLineupDispatcher& dispatch, const app::LiveTacticsDispatcher& dispatch_tactic, + const app::LivePitchDispatcher& dispatch_pitch, + const app::LiveInterventionScopeDispatcher& dispatch_scope, + bool live_skipped, bool event_origin) -> bool { + const auto show_live_substitution_notice = [&](const app::LiveSubstitutionResult& result, + const Image& backdrop, const char* parent_title) { + if (result.status != app::LiveSubstitutionStatus::source_notice) return; + if (result.manager_slot < 0 || result.source_text_address == 0) + throw FormatError("live substitution notice has no Source owner or text"); + const PendingOfferNotice notice{result.manager_slot, -1, result.source_text_address, + message_text(state, result.source_text_address)}; + const auto projection = ui::pending_offer_notice_dialog(state, notice); + if (present_pending_dialog(state, projection, backdrop, + "OpenBMH - live_substitution_notice") == PendingOfferAnswer::unsupported) + throw FormatError("live substitution notice presenter stopped"); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + SDL_SetWindowTitle(window, parent_title); + }; + bool completed = false; + const int selected_manager = selected_team >= 0 ? state.manager_of(selected_team) : -1; + if ((event_origin || (!live_skipped && minute > 2)) && selected_team >= 0 && selected_manager >= 0) { + bool scope_started = false, scope_finished = false; + std::string scope_error; + try { + if (!dispatch_scope(app::LiveInterventionBoundary::begin, 2, + selected_manager, selected_team, scope_error)) + throw FormatError(scope_error.empty() ? "live intervention could not begin" : scope_error); + scope_started = true; + // FindManagerForClub selects the manager owned by + // the clicked side. The live scope owns that + // manager until Source menu completion or abort. + auto lineup_state = state; + if (lineup_state.memory.has(::bmh::layout::ActiveManager)) + lineup_state.memory.set8(::bmh::layout::ActiveManager, uint8_t(selected_manager)); + auto live_lineup = ui::lineup_from_game(lineup_state, season_exe, live_revision); + live_lineup.in_match = true; + live_lineup.entry_prepared = true; + ui::LineupScreen screen(data, std::move(live_lineup)); + SDL_SetWindowTitle(window, "OpenBMH - live_lineup"); + bool closed = false; + std::optional lineup_down; + std::optional lineup_right_down; + while (running && !closed) { + const Image image = screen.render(); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + SDL_Event modal; + bool redrawn = false; + while (SDL_PollEvent(&modal)) { + if (modal.type == SDL_QUIT) { running = false; closed = true; break; } + if (modal.type == SDL_KEYDOWN && modal.key.keysym.sym == SDLK_ESCAPE) { + screen.key("ESC"); closed = true; break; + } + if (modal.type == SDL_MOUSEBUTTONDOWN && modal.button.button == SDL_BUTTON_RIGHT) + lineup_right_down = modal.button; + else if (modal.type == SDL_MOUSEBUTTONUP && lineup_right_down && + modal.button.button == SDL_BUTTON_RIGHT && + modal.button.x == lineup_right_down->x && modal.button.y == lineup_right_down->y) { + lineup_right_down.reset(); + screen.click(modal.button.x, modal.button.y, true); + if (screen.close_requested()) closed = true; + redrawn = true; + } + if (modal.type == SDL_MOUSEBUTTONDOWN && modal.button.button == SDL_BUTTON_LEFT) + lineup_down = modal.button; + else if (modal.type == SDL_MOUSEBUTTONUP && lineup_down && + modal.button.button == SDL_BUTTON_LEFT && + modal.button.x == lineup_down->x && modal.button.y == lineup_down->y) { + lineup_down.reset(); + const auto request = screen.click(modal.button.x, modal.button.y); + if (request.kind == ui::LineupRequestKind::swap_players) { + const auto result = dispatch(request); + if (result.status == app::LiveSubstitutionStatus::applied) { + auto updated = ui::lineup_from_game(state, season_exe, live_revision); + updated.in_match = true; updated.entry_prepared = true; + screen.acknowledge(std::move(updated)); + redrawn = true; + } else if (result.status == app::LiveSubstitutionStatus::source_notice) { + show_live_substitution_notice(result, screen.render(), + "OpenBMH - live_lineup"); + auto updated = ui::lineup_from_game(state, season_exe, live_revision); + updated.in_match = true; updated.entry_prepared = true; + screen = ui::LineupScreen(data, std::move(updated)); + redrawn = true; + } else { + screen.reject_action(result.error.empty() + ? "Der Spielerwechsel ist nicht freigegeben." + : result.error); + redrawn = true; + } + } else if (request.kind == ui::LineupRequestKind::open_player_info) { + const auto& player = screen.state().players.at(size_t(request.first_row)); + try { + if (player.player_id != request.first_player) + throw FormatError("live player information request is stale"); + auto services = session->live_club_modal_services(live_revision); + const ClubPlayerDetailSelection selection{selected_team, request.first_player, + request.first_row, request.first_row, -1}; + if (!present_player_detail) + throw FormatError("live player information presenter stopped"); + const auto return_parent = present_player_detail(services, selection, screen.render()); + if (!return_parent) throw FormatError("live player information presenter stopped"); + if (*return_parent) closed = true; + SDL_SetWindowTitle(window, "OpenBMH - live_lineup"); + } catch (const std::exception& e) { + std::fprintf(stderr, "live player information: %s\n", e.what()); + } + screen.resolve_local_navigation(request.kind); + redrawn = true; + } else if (request.kind == ui::LineupRequestKind::open_pitch) { + bool returned_to_lineup = false; + try { + ui::PitchScreen pitch(data, screen.state(), + ui::pitch_extras_from_game(state, season_exe, live_revision, selected_opponent)); + auto pitch_entry = pitch.request_page_control(1); + app::LiveSubstitutionResult entry_result; + if (pitch_entry.kind == ui::PitchRequestKind::none || + (entry_result = dispatch_pitch(pitch_entry)).status != + app::LiveSubstitutionStatus::applied) { + if (pitch_entry.kind != ui::PitchRequestKind::none) + pitch.reject_action(entry_result.error.empty() + ? "Source pitch entry was rejected" : entry_result.error); + throw FormatError(entry_result.error.empty() + ? "Source pitch entry could not be acknowledged" : entry_result.error); + } + auto entered_lineup = ui::lineup_from_game(state, season_exe, live_revision); + entered_lineup.in_match = true; entered_lineup.entry_prepared = true; + pitch.acknowledge(std::move(entered_lineup), + ui::pitch_extras_from_game(state, season_exe, live_revision, selected_opponent)); + SDL_SetWindowTitle(window, "OpenBMH - live_pitch"); + bool pitch_closed = false; + std::optional pitch_down; + std::optional pitch_right_down; + std::optional pitch_down_request; + Uint32 pitch_down_at = 0; + while (running && !pitch_closed) { + const Image pitch_image = pitch.render(); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[pitch_image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + SDL_Event child; + bool pitch_redrawn = false; + while (SDL_PollEvent(&child)) { + if (child.type == SDL_QUIT) { running = false; pitch_closed = true; break; } + if (child.type == SDL_KEYDOWN && child.key.keysym.sym == SDLK_ESCAPE) { + pitch.key("ESC"); pitch_closed = true; closed = true; break; + } + if (child.type == SDL_MOUSEBUTTONDOWN && child.button.button == SDL_BUTTON_LEFT) { + pitch_down = child.button; pitch_down_at = SDL_GetTicks(); + pitch_down_request = pitch.pointer_down(child.button.x, child.button.y); + } else if (child.type == SDL_MOUSEBUTTONDOWN && child.button.button == SDL_BUTTON_RIGHT) { + pitch_right_down = child.button; + (void)pitch.pointer_down(child.button.x, child.button.y, true); + } else if (child.type == SDL_MOUSEBUTTONUP && pitch_down && + child.button.button == SDL_BUTTON_LEFT && + child.button.x == pitch_down->x && child.button.y == pitch_down->y) { + pitch_down.reset(); + auto action = pitch_down_request.value_or(ui::PitchRequest{}); + pitch_down_request.reset(); + if (SDL_GetTicks() - pitch_down_at > 500) + action = pitch.save_formation(child.button.x, child.button.y); + else if (action.kind == ui::PitchRequestKind::none) + action = pitch.click(child.button.x, child.button.y); + if (action.kind == ui::PitchRequestKind::open_player_info) { + try { + if (action.row < 0 || size_t(action.row) >= pitch.state().players.size() || + pitch.state().players.at(size_t(action.row)).player_id != action.player_id) + throw FormatError("live pitch player information request is stale"); + auto services = session->live_club_modal_services(live_revision); + const ClubPlayerDetailSelection selection{selected_team, action.player_id, + action.row, action.row, -1}; + if (!present_player_detail) + throw FormatError("live pitch player information presenter stopped"); + const auto return_parent = present_player_detail(services, selection, pitch.render()); + if (!return_parent) + throw FormatError("live pitch player information presenter stopped"); + SDL_SetWindowTitle(window, "OpenBMH - live_pitch"); + if (*return_parent) { pitch_closed = true; closed = true; } + } catch (const std::exception& e) { + std::fprintf(stderr, "live pitch player information: %s\n", e.what()); + } + pitch.resolve_local_navigation(); pitch_redrawn = true; + } else if (action.kind != ui::PitchRequestKind::none) { + const auto result = dispatch_pitch(action); + if (result.status == app::LiveSubstitutionStatus::applied) { + auto updated = ui::lineup_from_game(state, season_exe, live_revision); + updated.in_match = true; updated.entry_prepared = true; + pitch.acknowledge(std::move(updated), + ui::pitch_extras_from_game(state, season_exe, live_revision, selected_opponent)); + if (action.kind == ui::PitchRequestKind::select_pitch_page && + action.page_control == 1) { + pitch_closed = true; returned_to_lineup = true; + } + } else if (result.status == app::LiveSubstitutionStatus::source_notice) { + show_live_substitution_notice(result, pitch.render(), + "OpenBMH - live_pitch"); + auto updated = ui::lineup_from_game(state, season_exe, live_revision); + updated.in_match = true; updated.entry_prepared = true; + pitch = ui::PitchScreen(data, std::move(updated), + ui::pitch_extras_from_game(state, season_exe, live_revision, selected_opponent)); + } else { + pitch.reject_action(result.error.empty() + ? "Der Spielerwechsel ist nicht freigegeben." + : result.error); + } + pitch_redrawn = true; + } else pitch_redrawn = true; + } else if (child.type == SDL_MOUSEBUTTONUP && pitch_right_down && + child.button.button == SDL_BUTTON_RIGHT && + child.button.x == pitch_right_down->x && + child.button.y == pitch_right_down->y) { + pitch_right_down.reset(); + if (pitch.close_requested()) { pitch_closed = true; closed = true; break; } + pitch_redrawn = true; + } else if (child.type == SDL_MOUSEMOTION) + pitch_redrawn |= pitch.move(child.motion.x, child.motion.y); + } + if (!pitch_redrawn && !pitch_closed && running) SDL_Delay(8); + } + SDL_SetWindowTitle(window, "OpenBMH - live_lineup"); + } catch (const std::exception& e) { + std::fprintf(stderr, "live pitch: %s\n", e.what()); + } + if (returned_to_lineup) { + auto updated = ui::lineup_from_game(state, season_exe, live_revision); + updated.in_match = true; updated.entry_prepared = true; + screen = ui::LineupScreen(data, std::move(updated)); + } else if (!closed) screen.resolve_local_navigation(request.kind); + redrawn = true; + } else redrawn = true; + } else if (modal.type == SDL_MOUSEMOTION) + redrawn |= screen.move(modal.motion.x, modal.motion.y); + } + if (!redrawn && !closed) SDL_Delay(8); + } + if (!running) { + dispatch_scope(app::LiveInterventionBoundary::abort, 2, selected_manager, + selected_team, scope_error); + scope_finished = true; + } else if (!dispatch_scope(app::LiveInterventionBoundary::finish, 2, + selected_manager, selected_team, scope_error)) { + std::fprintf(stderr, "live intervention finish: %s\n", scope_error.c_str()); + dispatch_scope(app::LiveInterventionBoundary::abort, 2, + selected_manager, selected_team, scope_error); + scope_finished = true; + } else { + scope_finished = true; + completed = true; + } + SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + } catch (const std::exception& e) { + if (scope_started && !scope_finished) + dispatch_scope(app::LiveInterventionBoundary::abort, 2, + selected_manager, selected_team, scope_error); + std::fprintf(stderr, "live lineup: %s\n", e.what()); + if (event_origin) throw; + } + } + return completed; + }; + using RunningOverviewDispatcher = std::function( + const app::CareerSession::LiveOverviewAction&, std::string&, + const app::TransferOfferTeamInfoPresenter&)>; + const auto present_running_overview = [&](std::optional projection, + const GameState& state, uint64_t& live_revision, + const RunningOverviewDispatcher& dispatch_overview, + const PhaseResultRequest* phase_result) { + const int manager = projection->owner.manager_slot; + std::unique_ptr table_screen; + std::unique_ptr pairings_screen; + std::unique_ptr strengths_screen; + std::unique_ptr cup_screen; + const auto overview_clock_start = std::chrono::steady_clock::now(); + const auto overview_source_seconds = [&] { + const auto milliseconds = std::chrono::duration_cast( + std::chrono::steady_clock::now() - overview_clock_start).count(); + return ui::league_pairings_source_seconds(uint64_t(milliseconds)); + }; + const auto rebuild_screen = [&] { + table_screen.reset(); pairings_screen.reset(); strengths_screen.reset(); cup_screen.reset(); + if (projection->kind == app::CareerSession::LiveOverviewKind::league_table && + projection->table) { + auto tables = ui::league_tables_from_game(state, manager); + const int selected = projection->table->league_id; + if (selected < 0 || selected >= int(tables.size())) + throw FormatError("live overview: Source table league is invalid"); + tables[size_t(selected)] = *projection->table; + table_screen = std::make_unique(data, + std::move(tables), selected, + ui::LeagueTableScreen::FamilyMode{projection->family_identity, 0}); + } else if (projection->kind == app::CareerSession::LiveOverviewKind::league_pairings && + projection->pairings) { + pairings_screen = std::make_unique(data, + *projection->pairings, + ui::LeaguePairingsScreen::FamilyMode{projection->family_identity}); + } else if (projection->kind == app::CareerSession::LiveOverviewKind::league_strengths && + projection->strengths) { + strengths_screen = std::make_unique(data, *projection->strengths); + } else if (projection->kind == app::CareerSession::LiveOverviewKind::cup_other_games && + projection->cup) { + cup_screen = std::make_unique(data, *projection->cup); + } else { + throw FormatError("live overview: Source presenter projection is missing"); + } + }; + const auto overview_title = [&]() -> std::string { + if (phase_result) { + const std::string prefix = "OpenBMH - phase_"; + const std::string suffix = "_" + std::to_string(phase_result->phase_end_minute) + + "_" + std::to_string(phase_result->group_index); + switch (projection->kind) { + case app::CareerSession::LiveOverviewKind::league_table: return prefix+"table"+suffix; + case app::CareerSession::LiveOverviewKind::league_pairings: return prefix+"pairings"+suffix; + case app::CareerSession::LiveOverviewKind::league_strengths: return prefix+"strengths"+suffix; + case app::CareerSession::LiveOverviewKind::cup_other_games: return prefix+"cup"+suffix; + } + } + switch (projection->kind) { + case app::CareerSession::LiveOverviewKind::league_table: + return "OpenBMH - live_league_table"; + case app::CareerSession::LiveOverviewKind::league_pairings: + return "OpenBMH - live_pairings"; + case app::CareerSession::LiveOverviewKind::league_strengths: + return "OpenBMH - live_strengths"; + case app::CareerSession::LiveOverviewKind::cup_other_games: + return "OpenBMH - live_other_games"; + } + return "OpenBMH - live_overview"; + }; + const auto render_overview = [&] { + const Image image = table_screen ? table_screen->render() + : pairings_screen ? pairings_screen->render() + : strengths_screen ? strengths_screen->render() : cup_screen->render(); + SDL_SetWindowTitle(window, overview_title().c_str()); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + if (pairings_screen) + pairings_screen->mark_presented_source_seconds(overview_source_seconds()); + }; + rebuild_screen(); + render_overview(); + bool closed = false; + std::optional down; + const auto run_table_range = [&](const Image& backdrop, + ui::TableRangeDialogProfile profile) -> ui::TableRangeDialogOutcome { + ui::LeagueTableRangeDialog dialog(data, backdrop, std::move(profile)); + std::deque keys; + Uint32 clock_anchor = SDL_GetTicks(); + std::optional outcome; + const auto show_dialog = [&] { + const Image image = dialog.render(); + SDL_SetWindowTitle(window, "OpenBMH - live_table_range"); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + outcome = dialog.after_present(); + clock_anchor = SDL_GetTicks(); + }; + show_dialog(); + while (running && !outcome) { + SDL_Event input; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; break; } + bool changed = false; + if (input.type == SDL_TEXTINPUT) { + for (char c : std::string_view(input.text.text)) + if (c >= '0' && c <= '9') keys.emplace_back(1, c); + } else if (input.type == SDL_KEYDOWN) { + if (input.key.keysym.sym == SDLK_RETURN) keys.emplace_back("ENTER"); + else if (input.key.keysym.sym == SDLK_BACKSPACE) keys.emplace_back("BACKSPACE"); + else if (input.key.keysym.sym == SDLK_SPACE) keys.emplace_back("SPACE"); + } else if (input.type == SDL_MOUSEMOTION) + changed = dialog.move(input.motion.x, input.motion.y); + else if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || + input.button.button == SDL_BUTTON_RIGHT)) + changed = dialog.pointer_down(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + else if (input.type == SDL_MOUSEBUTTONUP && + (input.button.button == SDL_BUTTON_LEFT || + input.button.button == SDL_BUTTON_RIGHT)) + changed = dialog.pointer_up(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + if (changed && input.type != SDL_MOUSEBUTTONUP) show_dialog(); + if (outcome) break; + } + if (!running || outcome) break; + while (!keys.empty() && dialog.source_input_ready()) { + const std::string key = std::move(keys.front()); + keys.pop_front(); + if (dialog.key(key)) show_dialog(); + if (outcome) break; + } + const Uint32 now = SDL_GetTicks(); + const Uint32 units = Uint32(now - clock_anchor) / 20; + if (units) { + clock_anchor += units * 20; + if (dialog.tick_source_units(units)) show_dialog(); + } + SDL_Delay(10); + } + if (!outcome) throw FormatError("live table range presenter stopped"); + return *outcome; + }; + std::function dispatch_action; + dispatch_action = [&](const app::CareerSession::LiveOverviewAction& action) { + const Image previous_table = table_screen ? table_screen->render() : Image{}; + std::string dispatch_error; + auto result = dispatch_overview(action, dispatch_error, [&](app::ClubModalServices& services, int selected_team, + const Image&) { + return present_club_information(services, selected_team) && running; + }); + if (!result) { + if (!dispatch_error.empty()) + std::fprintf(stderr, "live overview: %s\n", dispatch_error.c_str()); + rebuild_screen(); + render_overview(); + return; + } + if (result->closed) { closed = true; return; } + projection->kind = result->kind; + if (result->family_identity.manager >= 0) + projection->family_identity = result->family_identity; + projection->table = std::move(result->table); + projection->pairings = std::move(result->pairings); + projection->strengths = std::move(result->strengths); + projection->cup = std::move(result->cup); + rebuild_screen(); + const bool table_dialog_pending = + projection->kind == app::CareerSession::LiveOverviewKind::league_table && + result->table_dialog && result->table_phase != app::CareerSession::TableDispatchPhase::ready; + if (!table_dialog_pending) render_overview(); + if (table_dialog_pending) { + auto profile = *result->table_dialog; + auto range = run_table_range(previous_table, std::move(profile)); + ui::LeagueFamilyRequest reply; + reply.identity = projection->family_identity; + reply.kind = ui::LeagueFamilyRequestKind::table_range_result; + reply.from_child = 1; + reply.control_index = 9; + reply.table_dialog_reply = ui::TableDialogReply{ + result->table_phase == app::CareerSession::TableDispatchPhase::range_start + ? ui::TableDialogStage::start : ui::TableDialogStage::end, + range.result == ui::TableRangeDialogResult::accept + ? ui::TableDialogOutcome::accept : ui::TableDialogOutcome::cancel, + range.result == ui::TableRangeDialogResult::accept ? int(range.value) : 0, + range.x, range.y}; + dispatch_action(app::CareerSession::LiveOverviewAction{reply}); + } else if (projection->kind == app::CareerSession::LiveOverviewKind::league_table && + result->table_phase == app::CareerSession::TableDispatchPhase::forecast_pending_present) { + ui::LeagueFamilyRequest ack; + ack.identity = projection->family_identity; + ack.kind = ui::LeagueFamilyRequestKind::table_forecast_presented; + ack.from_child = 1; + dispatch_action(app::CareerSession::LiveOverviewAction{ack}); + } + }; + SDL_FlushEvent(SDL_KEYUP); + while (running && !closed) { + SDL_Event input; + bool redrawn = false; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; break; } + if (input.type == SDL_MOUSEMOTION) { + const bool changed = table_screen ? table_screen->move(input.motion.x, input.motion.y) + : pairings_screen ? pairings_screen->move(input.motion.x, input.motion.y) + : strengths_screen ? strengths_screen->move(input.motion.x, input.motion.y) + : cup_screen->move(input.motion.x, input.motion.y); + if (changed) { render_overview(); redrawn = true; } + } else if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) { + down = input.button; + if (table_screen) table_screen->pointer_down(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + else if (pairings_screen) pairings_screen->pointer_down(input.button.x, + input.button.y, input.button.button == SDL_BUTTON_RIGHT); + else if (strengths_screen) strengths_screen->pointer_down(input.button.x, + input.button.y, input.button.button == SDL_BUTTON_RIGHT); + else cup_screen->pointer_down(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + } else if (input.type == SDL_MOUSEBUTTONUP && down && + input.button.button == down->button && input.button.x == down->x && + input.button.y == down->y) { + down.reset(); + if (table_screen) table_screen->click(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + else if (pairings_screen) pairings_screen->release(input.button.x, input.button.y); + else if (strengths_screen) strengths_screen->release(input.button.x, input.button.y); + else cup_screen->release(input.button.x, input.button.y); + } + + std::optional action; + if (table_screen && table_screen->pending_family_action()) + action = *table_screen->pending_family_action(); + else if (pairings_screen && pairings_screen->pending_family_action()) + action = *pairings_screen->pending_family_action(); + else if (pairings_screen && pairings_screen->pending()) + action = *pairings_screen->pending(); + else if (strengths_screen && strengths_screen->pending()) + action = *strengths_screen->pending(); + else if (cup_screen && cup_screen->pending()) + action = *cup_screen->pending(); + if (action) { dispatch_action(*action); redrawn = true; } + if (closed || !running) break; + } + if (!running || closed) break; + if (pairings_screen && pairings_screen->tick_source_seconds(overview_source_seconds())) { + if (pairings_screen->pending()) + dispatch_action(app::CareerSession::LiveOverviewAction{*pairings_screen->pending()}); + redrawn = true; + } + if (closed || !running) break; + if (!redrawn) SDL_Delay(8); + } + return running && closed; + }; + std::optional live_chance_context; + std::unique_ptr reality_field; + ui::RealityReporterLayoutState reality_layout; + Image reality_pristine, reality_surface; + Palette reality_colors; + const std::string message = app::serve_flow_request(flow, r, session, data, save_directory, seed, revision, + playback, audio_session, music_enabled, + [&](int minute, const std::vector& groups, const GameState& state) { + if (!running) return; + bool live_frame_shown = false; + if (!live_skipped) { + const auto frame = ui::live_matchday_frame(minute, groups, state); + if (!frame.matches.empty()) { + SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + const Image live_image = live_screen.render(frame); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[live_image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + live_frame_shown = true; + } + } + const int frame_delay = live_frame_ms_explicit ? live_frame_ms : std::max(live_frame_ms, 250); + if (live_frame_shown && !live_skipped && frame_delay > 0) + SDL_Delay(Uint32(frame_delay)); + }, + [&](const GameState& state, const TransferOfferListView& offers) -> int { + if (!running) return -1; + auto view = transfer_view(state, offers, offers.seller_manager); + ui::IncomingTransferScreen offer_screen(data, + ui::incoming_transfer_decision_from_game(state, view), + state.memory.u8(::bmh::layout::TextGradientDisabled) == 0); + SDL_SetWindowTitle(window, "OpenBMH - incoming_transfer"); + const Uint32 notice_started = SDL_GetTicks(); + bool offer_dirty = true; + // Keep the original synchronous decision stack suspended here. + // Only this modal's input is dispatched; desk actions and saves + // cannot run against a partially processed calendar day. + while (running) { + if (offer_screen.notice_active() && SDL_GetTicks() - notice_started >= 4260) + offer_dirty |= offer_screen.dismiss_notice(); + if (!offer_screen.notice_active() && offers.offer_count == 0) return -1; + if (offer_dirty) { + const auto image = offer_screen.render(); + outcome_backdrop = image; + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + offer_dirty = false; + } + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return -1; } + std::optional answer; + if (event.type == SDL_MOUSEBUTTONUP && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) { + answer = offer_screen.click(event.button.x, event.button.y, + event.button.button == SDL_BUTTON_RIGHT); + offer_dirty = true; + } else if (event.type == SDL_KEYDOWN) { + if (offer_screen.notice_active()) { + offer_dirty |= offer_screen.dismiss_notice(); + } else if (event.key.keysym.sym == SDLK_ESCAPE) { + answer = offer_screen.key("ESC"); + } + } + if (answer) return *answer; + } + if (playback.needs_pump()) playback.pump(audio_error); + SDL_Delay(10); + } + return -1; + }, + [&](const GameState& state, const TransferDecisionEvent& decision) { + if (!running) return; + if (decision.kind == TransferDecisionEventKind::last_week) { + auto view = ui::transfer_last_week_dialog(state, decision); + const Image backdrop = outcome_backdrop ? *outcome_backdrop : + ui::GameEndTaxDialog(data, view, game_end_options(state)).backdrop(); + if (present_pending_dialog(state, std::move(view), backdrop, + "OpenBMH - transfer_last_week") == + PendingOfferAnswer::unsupported) + running = false; + return; + } + auto view = transfer_view(state, decision.offers, decision.viewer_manager); + if (decision.kind == TransferDecisionEventKind::confirmation) + view.notice_text_address = decision.result_text_address; + ui::IncomingTransferScreen decision_screen(data, + ui::incoming_transfer_decision_from_game(state, view), + state.memory.u8(::bmh::layout::TextGradientDisabled) == 0); + const bool confirmation = decision.kind == TransferDecisionEventKind::confirmation; + if (confirmation) { + const Image backdrop = outcome_backdrop ? *outcome_backdrop : decision_screen.render(); + decision_screen.show_confirmation(decision.result_text_address, backdrop); + } else { + decision_screen.begin_outcome(decision.offers.offer_count, + decision.accepted ? decision.selected_bid_index : -1, state.memory.u8(::bmh::layout::OutcomeDelayDisabled)); + } + SDL_SetWindowTitle(window, confirmation ? "OpenBMH - transfer_confirmation" : "OpenBMH - transfer_evaluation"); + const Uint32 started = SDL_GetTicks(); + uint64_t rendered_phase = UINT64_MAX; + // The observer only presents the engine's settled decision. Keep + // calendar/desk/save dispatch suspended until the original modal + // input completes; clicks cannot select or reroll a bid here. + while (running) { + const uint64_t elapsed = Uint32(SDL_GetTicks() - started); + const uint64_t phase = confirmation ? 0 : std::min(elapsed / ui::IncomingTransferScreen::outcome_phase_ms, + decision_screen.outcome_duration_ms() / ui::IncomingTransferScreen::outcome_phase_ms); + if (phase != rendered_phase) { + const auto image = decision_screen.render_at_elapsed(elapsed); + if (!confirmation) outcome_backdrop = image; + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + rendered_phase = phase; + } + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return; } + if (event.type == SDL_MOUSEBUTTONUP && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) + (void)decision_screen.click(event.button.x, event.button.y, + event.button.button == SDL_BUTTON_RIGHT, elapsed); + } + if (confirmation ? decision_screen.confirmation_dismissed() : decision_screen.outcome_dismissed()) return; + SDL_Delay(10); + } + }, + [&](const char* checkpoint, const GameState& state) { + if (!running || std::strcmp(checkpoint, "the German entrants (CompetitionWinnerScreen)") != 0) return; + // SeasonEntrantsFromGame / CompetitionWinnerScreen: show the three owned Original + // projections while the transition is suspended at its checkpoint. + // Other season animations remain separate implementation work. + for (auto view : ui::season_entrants_from_game(state, season_exe, season_texts)) { + ui::SeasonEntrantsScreen entrants_screen(data, std::move(view)); + SDL_SetWindowTitle(window, "OpenBMH - season_entrants"); + const Image image = entrants_screen.render(); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + bool dismissed = false; + while (running && !dismissed) { + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { running = false; return; } + if (event.type == SDL_MOUSEBUTTONUP && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) { + dismissed = true; + break; + } + } + if (!dismissed) SDL_Delay(10); + } + } + }, tax_presenter, show_highscore, promotion_presenter, cup_draw_presenter, + r.request == ui::FlowRequest::kickoff + ? make_pending_offer_hooks(flow.render()) : PendingOfferHooks{}, + app::PendingOfferEntryPolicy::normal_interactive, + (r.request == ui::FlowRequest::kickoff || (r.request == ui::FlowRequest::submenu_action && + (std::holds_alternative(r.submenu_action) || + std::holds_alternative(r.submenu_action)) + )) ? make_market_sale_hooks(flow.render()) : HumanBuyerSaleHooks{}, + app::HumanBuyerMarketEntryPolicy::normal_interactive, + [&](app::ClubModalServices& services,int team,const Image&) { + return present_club_information(services,team) && running; + }, [&](app::ClubModalServices& services,const ClubPlayerDetailSelection& selection,const Image& parent) { + // Direct1b556 already owns persistent bbcde=1. The shared + //ClubPlayerDetailFromGame presenter never restores a temporary club mode here. + return present_player_detail(services,selection,parent).has_value() && running; + }, [&](const GameState& staged, const ConstructionNotice& notice) { + if (!flow.stadium()) throw std::runtime_error("construction notice has no stadium owner"); + // The Original payment notices restore the investment detail, + // after the tip question has returned, before the outer ACK. + const Image backdrop = flow.stadium()->construction_notice_backdrop(); + auto view = ui::construction_notice_dialog(staged, season_exe, notice); + std::optional effective_options; + if (flow.stadium()->state().block_expansion || flow.stadium()->state().quoted_object) { + const auto& owner = flow.stadium()->state(); + view.compact_dialog_frame = owner.compact_dialog_frame; + effective_options = ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text}; + } + const char* title = notice.kind == ConstructionNoticeKind::InsufficientFunds + ? "OpenBMH - stadium_funds_notice" : "OpenBMH - stadium_sponsor_notice"; + if (present_pending_dialog(staged, view, backdrop, title, effective_options) == PendingOfferAnswer::unsupported) + throw std::runtime_error("construction notice presenter stopped"); + }, [&](const GameState& staged, const SeasonTicketCompensationNotice& notice) { + if (!flow.stadium()) throw std::runtime_error("compensation notice has no stadium owner"); + const Image backdrop = flow.stadium()->construction_notice_backdrop(); + auto view = ui::season_ticket_compensation_notice_dialog(staged, season_exe, notice); + const auto& owner = flow.stadium()->state(); + view.compact_dialog_frame = owner.compact_dialog_frame; + if (present_pending_dialog(staged, view, backdrop, + "OpenBMH - stadium_ticket_compensation_notice", + ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text}) == PendingOfferAnswer::unsupported) + throw std::runtime_error("compensation notice presenter stopped"); + }, sportschau_presenter, + [&](const GameState& staged, const AdvertisingRenewal& renewal, const Image& backdrop) + -> app::CareerSession::AdvertisingRenewalPresentation { + if (!running) return app::CareerSession::AdvertisingRenewalPresentation::abort; + const int manager = int(staged.memory.u8(::bmh::layout::ActiveManager)); + if (renewal.status == AdvertisingRenewal::Status::offered) { + const auto view = ui::advertising_renewal_question_dialog(staged, manager, renewal); + const auto answer = present_pending_dialog(staged, view, backdrop, + "OpenBMH - advertising_renewal_question"); + if (answer == PendingOfferAnswer::yes) return app::CareerSession::AdvertisingRenewalPresentation::renew; + if (answer == PendingOfferAnswer::no) return app::CareerSession::AdvertisingRenewalPresentation::decline; + return app::CareerSession::AdvertisingRenewalPresentation::abort; + } + if (renewal.status == AdvertisingRenewal::Status::declined_by_sponsor) { + const auto view = ui::advertising_renewal_notice_dialog(staged, manager, renewal); + if (present_pending_dialog(staged, view, backdrop, + "OpenBMH - advertising_renewal_notice") == PendingOfferAnswer::yes) + return app::CareerSession::AdvertisingRenewalPresentation::acknowledged; + } + return app::CareerSession::AdvertisingRenewalPresentation::abort; + }, poach_player_selector, + [&](const GameState& staged,const PoachStart& attempt,const Image& backdrop) { + for(const auto& message:attempt.messages) + if(present_pending_dialog(staged,ui::poach_notice_from_game(staged,attempt,message),backdrop, + "OpenBMH - poach_notice")==PendingOfferAnswer::unsupported) + throw FormatError("poach: notice presenter stopped"); + }, contract_expiry_presenter, + [&](const GameState& staged,ui::TaxDialogProjection view,const Image& backdrop) + ->std::optional { + if(!running)return {}; + const auto answer=present_pending_dialog(staged,std::move(view),backdrop, + "OpenBMH - national_friendly_question"); + flow.acknowledge_national_friendly_modal_release(); + // The synchronous questions already consumed their UP; + // do not retain the picker DOWN as a held parent press. + press.reset(); + if(answer==PendingOfferAnswer::unsupported)return {}; + return answer==PendingOfferAnswer::yes; + }, loan_return_presenter, loan_return_offer_presenter, + [&](int minute, MatchEngine& engine, std::vector& groups, + GameState& state, uint64_t& live_revision, + const app::LiveLineupDispatcher& dispatch, + const app::LiveTacticsDispatcher& dispatch_tactic, + const app::LivePitchDispatcher& dispatch_pitch, + const app::LiveInterventionScopeDispatcher& dispatch_scope) { + if (!running) return; + bool quit = false; + const auto show_live_substitution_notice = [&](const app::LiveSubstitutionResult& result, + const Image& backdrop, const char* parent_title) { + if (result.status != app::LiveSubstitutionStatus::source_notice) return; + if (result.manager_slot < 0 || result.source_text_address == 0) + throw FormatError("live substitution notice has no Source owner or text"); + const PendingOfferNotice notice{result.manager_slot, -1, + result.source_text_address, + message_text(state, result.source_text_address)}; + const auto projection = ui::pending_offer_notice_dialog(state, notice); + if (present_pending_dialog(state, projection, backdrop, + "OpenBMH - live_substitution_notice") == PendingOfferAnswer::unsupported) + throw FormatError("live substitution notice presenter stopped"); + // SDLFlushEvents3 is a timed Source notice. Do not let its release + // event become another click in the resumed parent screen. + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + SDL_SetWindowTitle(window, parent_title); + }; + const auto open_live_tactics = [&](int side, int y) { + const auto frame = ui::live_matchday_frame(minute, groups, state); + int selected_team = -1; + for (size_t row = 0; row < frame.matches.size() && row < 4; ++row) { + const int row_y = season_exe.u8(::bmh::layout::LiveMatchday_Render_ExecutableFieldUnsigned + uint32_t(row)); + if (y < row_y || y > row_y + 32) continue; + selected_team = side == 0 ? frame.matches[row].home_team : frame.matches[row].away_team; + break; + } + const int selected_manager = selected_team >= 0 ? state.manager_of(selected_team) : -1; + if (live_skipped || minute <= 2 || selected_team < 0 || selected_manager < 0) return; + std::string scope_error; + if (!dispatch_scope(app::LiveInterventionBoundary::begin, 8, + selected_manager, selected_team, scope_error)) { + std::fprintf(stderr, "live tactics: %s\n", scope_error.c_str()); + return; + } + bool scope_active = true; + try { + auto tactics_game = state; + if (tactics_game.memory.has(::bmh::layout::ActiveManager)) + tactics_game.memory.set8(::bmh::layout::ActiveManager, uint8_t(selected_manager)); + ui::TacticsScreen screen(data, + ui::tactics_from_game(tactics_game, season_exe, live_revision)); + SDL_SetWindowTitle(window, "OpenBMH - live_tactics"); + bool closed = false; + std::optional tactics_down; + bool source_completed = false; + while (running && !closed) { + const Image image = screen.render(); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + SDL_Event modal; + bool redrawn = false; + while (SDL_PollEvent(&modal)) { + if (modal.type == SDL_QUIT) { running = false; closed = true; break; } + if (modal.type == SDL_MOUSEBUTTONDOWN && + (modal.button.button == SDL_BUTTON_LEFT || modal.button.button == SDL_BUTTON_RIGHT)) + tactics_down = modal.button; + else if (modal.type == SDL_MOUSEBUTTONUP && tactics_down && + modal.button.button == tactics_down->button && + modal.button.x == tactics_down->x && modal.button.y == tactics_down->y) { + tactics_down.reset(); + const auto request = screen.click(modal.button.x, modal.button.y, + modal.button.button == SDL_BUTTON_RIGHT); + if (screen.close_requested()) { source_completed = true; closed = true; break; } + if (request.kind == ui::TacticsRequestKind::set_tactic) { + std::string error; + if (dispatch_tactic(request, error)) { + tactics_game = state; + if (tactics_game.memory.has(::bmh::layout::ActiveManager)) + tactics_game.memory.set8(::bmh::layout::ActiveManager, uint8_t(selected_manager)); + screen.acknowledge(ui::tactics_from_game( + tactics_game, season_exe, live_revision)); + } else screen.reject_action(error); + redrawn = true; + } + } + } + if (!redrawn && !closed) SDL_Delay(8); + } + if (scope_active && source_completed) { + if (!dispatch_scope(app::LiveInterventionBoundary::finish, 8, + selected_manager, selected_team, scope_error)) { + std::fprintf(stderr, "live tactics: %s\n", scope_error.c_str()); + dispatch_scope(app::LiveInterventionBoundary::abort, 8, + selected_manager, selected_team, scope_error); + } + scope_active = false; + } else if (scope_active) { + dispatch_scope(app::LiveInterventionBoundary::abort, 8, + selected_manager, selected_team, scope_error); + scope_active = false; + } + SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + } catch (const std::exception& e) { + if (scope_active) + dispatch_scope(app::LiveInterventionBoundary::abort, 8, + selected_manager, selected_team, scope_error); + std::fprintf(stderr, "live tactics: %s\n", e.what()); + } + }; + const uint8_t source_pause_key = season_exe.u8(::bmh::layout::Main_Screen_RuntimeField); + const bool source_pause_is_p = source_pause_key == 'p' || source_pause_key == 'P'; + const auto pause_live_match = [&] { + if (!source_pause_is_p) return; + const auto frame = ui::live_matchday_frame(minute, groups, state); + const Image image = live_screen.render(frame); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_SetWindowTitle(window, "OpenBMH - live_paused"); + SDL_RenderPresent(renderer); + + bool resumed = false; + while (running && !resumed) { + SDL_Event paused_event; + while (SDL_PollEvent(&paused_event)) { + if (paused_event.type == SDL_QUIT) { + quit = true; + live_skipped = true; + running = false; + break; + } + if (paused_event.type == SDL_KEYDOWN && !paused_event.key.repeat && + paused_event.key.keysym.sym == SDLK_p) + resumed = true; + } + if (!resumed && running) SDL_Delay(8); + } + if (running) SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + }; + const auto restore_live_frame = [&] { + if (!running) return; + const Image image = live_screen.render(ui::live_matchday_frame(minute, groups, state)); + SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + const auto show_live_overview = [&](int key_slot) { + if (!running || live_skipped || live_overview_sequence == UINT64_MAX) return; + const int manager = state.memory.has(::bmh::layout::ActiveManager) ? state.memory.u8(::bmh::layout::ActiveManager) : -1; + // EndPhase reads the keyboard overview descriptor from the + // first live group (CareerSessionRuntimeField5 = MatchdayGroupDescriptors + 0xcc). DeskPosition is + // the later per-group processing cursor and is not this owner. + const int group_index = groups.empty() ? -1 : 0; + if (manager < 0 || size_t(manager) >= state.manager_teams.size() || + group_index < 0 || size_t(group_index) >= groups.size()) return; + const int team = state.manager_teams[size_t(manager)]; + const auto frame = ui::live_matchday_frame(minute, groups, state); + const Image underlay = live_screen.render(frame); + app::CareerSession::LiveOverviewRequest request; + request.key_slot = key_slot; + request.minute = minute; + request.group_index = group_index; + request.manager_slot = manager; + request.runtime_team = team; + request.revision = live_revision; + request.sequence = live_overview_sequence + 1; + std::string error; + auto projection = session->open_live_overview(request, engine, live_revision, + underlay, error); + if (!projection) { + if (!error.empty()) std::fprintf(stderr, "live overview: %s\n", error.c_str()); + return; + } + ++live_overview_sequence; + + const bool closed = present_running_overview(std::move(projection), state, live_revision, + [&](const app::CareerSession::LiveOverviewAction& action, std::string& dispatch_error, + const app::TransferOfferTeamInfoPresenter& team_info) { + return session->dispatch_live_overview(action, engine, live_revision, dispatch_error, team_info); + }, nullptr); + if (running && closed) restore_live_frame(); + }; + const auto show_live_settings = [&](std::optional trigger = std::nullopt) { + if (!running || live_skipped || !state.memory.has(::bmh::layout::ActiveManager)) return; + const int manager = state.memory.u8(::bmh::layout::ActiveManager); + if (manager < 0 || size_t(manager) >= state.manager_teams.size()) return; + app::CareerSession::LiveSettingsRequest request; + request.minute = minute; + request.manager_slot = manager; + request.runtime_team = state.manager_teams[size_t(manager)]; + request.revision = live_revision; + request.sequence = 0; // Session assigns and returns the scoped owner nonce. + std::string error; + auto projection = session->open_live_settings(request, engine, live_revision, error); + if (!projection) { + if (!error.empty()) std::fprintf(stderr, "live settings: %s\n", error.c_str()); + return; + } + app::original_audio_command(playback, 1); // SavePathInDirectory before the live settings modal. + ui::SettingsScreen screen(data, projection->state); + std::unique_ptr readme; + const auto render_settings = [&] { + const Image image = readme ? readme->render() : screen.render(); + SDL_SetWindowTitle(window, readme ? "OpenBMH - settings_readme" : "OpenBMH - live_settings"); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + render_settings(); + const auto show_settings_file = [&] { + const auto* pending = screen.pending_file(); + if (!pending) return; + const auto menu_request = *pending; + ui::SaveLoadScreen file_screen(data, save_directory, + menu_request.action == ui::SaveLoadAction::load ? + ui::SaveLoadMode::load : ui::SaveLoadMode::save, + menu_request.manager_slot, live_revision, screen.render(), + !state.memory.has(::bmh::layout::PlainBackground) || state.memory.u8(::bmh::layout::PlainBackground) == 0, + ui::SaveLoadFileKind::settings, menu_request.origin_item_id); + const auto render_file = [&] { + const Image image = file_screen.render(); + SDL_SetWindowTitle(window, "OpenBMH - live_settings_file"); + for (size_t i = 0; i < pixels.size(); ++i) + pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + render_file(); + bool finished = false; + while (running && !finished) { + SDL_Event file_input; + bool file_changed = false; + while (SDL_PollEvent(&file_input)) { + if (file_input.type == SDL_QUIT) { running = false; break; } + if (file_input.type == SDL_MOUSEBUTTONUP && + (file_input.button.button == SDL_BUTTON_LEFT || + file_input.button.button == SDL_BUTTON_RIGHT)) { + file_changed |= file_screen.click(file_input.button.x, + file_input.button.y, + file_input.button.button == SDL_BUTTON_RIGHT); + } else if (file_input.type == SDL_KEYDOWN && !file_input.key.repeat) { + std::string_view key; + switch (file_input.key.keysym.sym) { + case SDLK_ESCAPE: key = "ESC"; break; + case SDLK_RETURN: key = "ENTER"; break; + case SDLK_BACKSPACE: key = "BACKSPACE"; break; + case SDLK_UP: key = "UP"; break; + case SDLK_DOWN: key = "DOWN"; break; + case SDLK_LEFT: key = "LEFT"; break; + case SDLK_RIGHT: key = "RIGHT"; break; + default: break; + } + if (!key.empty()) file_changed |= file_screen.key(key); + } else if (file_input.type == SDL_TEXTINPUT) { + file_changed |= file_screen.text(file_input.text.text); + } + if (const auto& file_request = file_screen.pending()) { + const app::CareerSession::LiveSettingsAction action{ + app::CareerSession::LiveSettingsFile{ + projection->owner.sequence, *file_request}}; + auto result = session->dispatch_live_settings(action, + engine, live_revision, error); + if (!result) { + file_screen.reject(error.empty() ? + "Dateiaktion fehlgeschlagen." : error); + file_changed = true; + } else { + projection->owner = result->owner; + screen.acknowledge_file(std::move(result->state)); + file_screen.acknowledge(); + finished = true; + } + } else if (file_screen.close_requested()) { + screen.cancel_file_request(); + finished = true; + } + if (!running || finished) break; + if (file_changed) render_file(); + } + if (!file_changed && running && !finished) SDL_Delay(8); + } + if (running) render_settings(); + }; + bool closed = false; + bool readme_release_barrier = false; + std::optional settings_down = trigger; + while (running && !closed) { + SDL_Event input; + bool changed = false; + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; break; } + if (readme) { + if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || + input.button.button == SDL_BUTTON_RIGHT)) { + settings_down = input.button; + readme->pointer_down(true); + if (readme->close_requested()) { + readme.reset(); + readme_release_barrier = true; + } + render_settings(); + } + // SDLFlushEvents2 waits for a mouse press; keys and + // motion do not close the Source readme viewer. + continue; + } + if (input.type == SDL_KEYDOWN && !input.key.repeat && + input.key.keysym.sym == SDLK_ESCAPE) { + screen.key("ESC"); + changed = true; + } else if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || + input.button.button == SDL_BUTTON_RIGHT)) { + settings_down = input.button; + const bool footer_button = input.button.button == SDL_BUTTON_LEFT && + input.button.x >= 1 && input.button.x < 55 && + input.button.y >= 188 && input.button.y < 224; + if (!footer_button) + changed = screen.click(input.button.x, input.button.y, + input.button.button == SDL_BUTTON_RIGHT); + } else if (input.type == SDL_MOUSEBUTTONUP && settings_down && + input.button.button == settings_down->button && + input.button.x == settings_down->x && input.button.y == settings_down->y) { + if (readme_release_barrier) { + readme_release_barrier = false; + } else if (input.button.button == SDL_BUTTON_LEFT && + input.button.x >= 1 && input.button.x < 55 && + input.button.y >= 188 && input.button.y < 224) + changed = screen.click(input.button.x, input.button.y); + settings_down.reset(); // Cells act on DOWN; file buttons on matching UP. + } + + if (!running) break; + if (screen.readme_requested()) { + screen.consume_readme_request(); + readme = std::make_unique( + data, screen.state().decorated_background); + changed = true; + } + if (screen.pending_file()) { + show_settings_file(); + changed = false; // The child restores its parent on return. + } + if (const auto* write = screen.pending()) { + const auto request_write = *write; + const app::CareerSession::LiveSettingsAction action{ + app::CareerSession::LiveSettingsWrite{projection->owner.sequence, + request_write}}; + auto result = session->dispatch_live_settings(action, engine, live_revision, error); + if (!result) { + const auto notice = ui::settings_source_refusal(state, request_write, live_revision); + if (notice && error == ui::original_to_utf8(message_text(state, *notice))) { + auto view = ui::environment_notice_dialog(state, request_write.manager_slot, + message_text(state, *notice)); + (void)present_pending_dialog(state, std::move(view), screen.render(), + "OpenBMH - live_settings_notice"); + screen.reject({}); + screen.consume_release(); + settings_down.reset(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + SDL_SetWindowTitle(window, "OpenBMH - live_settings"); + } else { + screen.reject(error.empty() ? "Diese Einstellung wurde nicht übernommen." : error); + std::fprintf(stderr, "live settings: %s\n", error.c_str()); + } + } else { + projection->owner = result->owner; + screen.acknowledge(std::move(result->state)); + playback.set_original_options( + app::original_audio_options(session->state(), music_enabled)); + } + changed = true; + } + if (screen.close_requested()) { + const app::CareerSession::LiveSettingsAction action{ + app::CareerSession::LiveSettingsCloseRequest{projection->owner}}; + auto result = session->dispatch_live_settings(action, engine, live_revision, error); + if (!result || !result->closed) { + std::fprintf(stderr, "live settings close: %s\n", + error.empty() ? "Source close rejected" : error.c_str()); + running = false; + } else { + projection->owner = result->owner; + closed = true; + } + } else if (changed) { + render_settings(); + } + if (closed || !running) break; + } + if (!running || closed) break; + if (!changed) SDL_Delay(8); + } + // A Source close may be requested on the opening/closing DOWN; + // consume its physical release before the live observer resumes. + if (closed) SDL_FlushEvent(SDL_MOUSEBUTTONUP); + if (running && closed) app::original_match_audio_command(playback, state, 3); + if (running && closed) restore_live_frame(); + }; + const bool source_phase_start = minute == 1 || + (state.indoor ? minute == 21 : (minute == 46 || minute == 91 || minute == 106)); + SDL_Event event; + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { quit = true; live_skipped = true; } + else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) + live_skipped = true; + else if (!source_phase_start && source_pause_is_p && event.type == SDL_KEYDOWN && + !event.key.repeat && event.key.keysym.sym == SDLK_p) + pause_live_match(); + else if (!source_phase_start && event.type == SDL_KEYDOWN && !event.key.repeat && + season_exe.u8(::bmh::layout::Main_FileScreen_RuntimeField) == 'g' && event.key.keysym.sym == SDLK_g) + show_live_overview(0); + else if (!source_phase_start && event.type == SDL_KEYDOWN && !event.key.repeat && + season_exe.u8(::bmh::layout::Main_FileScreen_RuntimeField2) == 't' && event.key.keysym.sym == SDLK_t) + show_live_overview(1); + else if (!source_phase_start && event.type == SDL_KEYDOWN && !event.key.repeat && + season_exe.u8(::bmh::layout::Main_FileScreen_RuntimeField3) == 's' && event.key.keysym.sym == SDLK_s) + show_live_settings(); + else if (event.type == SDL_MOUSEBUTTONDOWN && + (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT) && + event.button.x >= 0 && event.button.x <= 63 && + event.button.y > 49 && event.button.y < 65) { + // OriginalMouseSound sets CareerSession_BeginFriendlyOpponentTable_ExecutableField2 from this physical event: left=2, + // right=8. Keep it as input context; do not persist it in GameState. + const uint8_t source_mouse_mode = + event.button.button == SDL_BUTTON_LEFT ? 2 : 8; + if ((source_mouse_mode != 2 && source_mouse_mode != 8) || + source_phase_start || minute <= 2) + continue; + // EndPhase retains the sampled coordinates while each + // modal runs. Its inclusive ranges overlap at21/42: + // after closing the first viewer, enter its neighbour + // before resuming the same match minute. + for (int candidate = 0; candidate < 3 && running; ++candidate) { + const int left = candidate * 21; + if (event.button.x >= left && event.button.x <= left + 21) { + if (candidate < 2) show_live_overview(candidate); + else show_live_settings(event.button); + } + } + } + else if (const auto side = app::live_matchday_board_side(event, minute, state.indoor)) { + if (event.button.button == SDL_BUTTON_RIGHT) { + open_live_tactics(*side, event.button.y); + continue; + } + const auto frame = ui::live_matchday_frame(minute, groups, state); + int selected_team = -1, selected_opponent = -1; + for (size_t row = 0; row < frame.matches.size() && row < 4; ++row) { + const int y = season_exe.u8(::bmh::layout::LiveMatchday_Render_ExecutableFieldUnsigned + uint32_t(row)); + if (event.button.y < y || event.button.y > y + 32) continue; + if (*side == 0) { + selected_team = frame.matches[row].home_team; + selected_opponent = frame.matches[row].away_team; + } else { + selected_team = frame.matches[row].away_team; + selected_opponent = frame.matches[row].home_team; + } + break; + } + // EndPhase: physical left-DOWN is Source mode 2; the + // matching right-DOWN is mode 8. + (void)present_live_lineup(minute, engine, groups, + state, live_revision, selected_team, selected_opponent, + dispatch, dispatch_tactic, dispatch_pitch, dispatch_scope, live_skipped, false); + } + } + if (quit) running = false; + }, [&](const GameState& staged, ui::TaxDialogProjection view, const Image& backdrop) { + if (!running) return false; + const bool settings_notice = flow.in_settings() && flow.pending_settings(); + const bool shown = present_pending_dialog(staged, std::move(view), backdrop, + settings_notice ? "OpenBMH - settings_notice" : "OpenBMH - environment_notice") + != PendingOfferAnswer::unsupported; + if (settings_notice) { + flow.acknowledge_settings_notice_release(); + press.reset(); + SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + } + return shown; + }, [&](const LiveMatchEvent& event, MatchEngine& engine, + std::vector& groups, GameState& state, uint64_t& live_revision, + const app::LiveLineupDispatcher& dispatch, + const app::LiveTacticsDispatcher& dispatch_tactic, + const app::LivePitchDispatcher& dispatch_pitch, + const app::LiveInterventionScopeDispatcher& dispatch_scope) { + if (!running) return; + const bool completed = present_live_lineup(event.minute, engine, groups, state, live_revision, + event.team, event.opponent, dispatch, dispatch_tactic, dispatch_pitch, + dispatch_scope, false, true); + if (!running) return; // SDL_QUIT aborts the Source scope without failing the event. + if (!completed) + throw FormatError("The Source event line-up did not complete."); + }, [&](const LiveBallEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame = ui::live_matchday_frame(event.minute, groups, state); + if (frame.matches.empty()) return; + const auto present = [&](const Image& image) { + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + const int count = ui::LiveMatchdayScreen::ball_frame_count(event.displacement); + const auto source_delay = [&](int pause) { + const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9); + const int saved = state.memory.has(address) ? state.memory.u8(address) : 0; + return (saved < 6 ? saved / 2 : saved) * 20; + }; + for (int index = 0; index < count && running; ++index) { + const std::string title = "OpenBMH - live_ball_" + std::to_string(event.minute) + "_" + + std::to_string(event.group) + "_" + std::to_string(event.match) + "_" + + std::to_string(event.displacement) + "_" + std::to_string(index); + SDL_SetWindowTitle(window, title.c_str()); + const auto* chance = live_chance_context && + live_chance_context->minute == event.minute && + live_chance_context->group == event.group && + live_chance_context->match == event.match ? &*live_chance_context : nullptr; + present(live_screen.render_ball(frame, event.displacement, index, chance)); + SDL_PumpEvents(); + SDL_Event quit_event; + if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) { + running = false; + break; + } + // AdvanceStep(5) reads a252c; DecodeTaxAnimationScript2 uses 20ms ticks. + // Retain key/mouse events for the live-minute input boundary. + const int delay = live_frame_ms_explicit ? live_frame_ms : + source_delay(5); + if (delay > 0) SDL_Delay(Uint32(delay)); + } + if (running) { + const int final_delay = live_frame_ms_explicit ? live_frame_ms : source_delay(6); + if (final_delay > 0) SDL_Delay(Uint32(final_delay)); + SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); + present(live_screen.render(frame)); + } + }, [&](const LiveChanceEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame = ui::live_matchday_frame(event.minute, groups, state); + if (frame.matches.empty()) return; + const auto chance = ui::live_chance_projection(event, groups, state, season_exe); + if (event.stage == LiveChanceStage::preview) live_chance_context = chance; + const std::string title = std::string("OpenBMH - live_chance_") + + (event.stage == LiveChanceStage::preview ? "preview_" : "result_") + + std::to_string(event.minute) + "_" + std::to_string(event.group) + "_" + + std::to_string(event.match) + "_" + std::to_string(event.side) + "_" + + std::to_string(event.kind) + "_" + std::to_string(int(event.goal)); + SDL_SetWindowTitle(window, title.c_str()); + const Image image = live_screen.render_chance(frame, chance); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + SDL_PumpEvents(); + SDL_Event quit_event; + if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) { + running = false; + live_chance_context.reset(); + return; + } + const int pause = event.stage == LiveChanceStage::preview ? 12 : (event.goal ? 1 : 2); + const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9); + const int saved = state.memory.has(address) ? state.memory.u8(address) : 0; + const int delay = live_frame_ms_explicit ? live_frame_ms : + (saved < 6 ? saved / 2 : saved) * 20; + if (delay > 0) SDL_Delay(Uint32(delay)); + if (event.stage == LiveChanceStage::result) live_chance_context.reset(); + }, [&](const LiveShotEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame = ui::live_matchday_frame(event.minute, groups, state); + if (frame.matches.empty()) return; + const auto frames = live_screen.render_shot(frame, event); + const auto shot_colors = live_screen.shot_palette(palette, event, groups, state); + const std::string identity = std::to_string(event.minute) + "_" + + std::to_string(event.group) + "_" + std::to_string(event.match) + "_" + + std::to_string(event.acting_side) + "_" + std::to_string(int(event.miss)); + for (size_t index = 0; index < frames.size() && running; ++index) { + const std::string title = "OpenBMH - live_shot_" + identity + "_" + std::to_string(index); + SDL_SetWindowTitle(window, title.c_str()); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = shot_colors.argb[frames[index].pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + SDL_PumpEvents(); + SDL_Event input; + if (SDL_PeepEvents(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) { + running = false; + return; + } + // Source waits Main_FormatError_RuntimeField vertical retraces after each frame (70 Hz). + const int retraces = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ? + std::max(0, int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField)))) : 0; + const int delay = live_frame_ms_explicit ? live_frame_ms : retraces * 1000 / 70; + if (delay > 0) SDL_Delay(Uint32(delay)); + } + if (!running) return; + if (!live_frame_ms_explicit) SDL_Delay(200); // LiveMatchdayFrame -> DecodeTaxAnimationScript2(10) + if (app::match_sound_enabled(state)) + app::original_audio_command(playback, event.miss ? 20 : 19); // SetPieceAnimation, before its ACK. + if (state.memory.has(::bmh::layout::Main_FormatError_RuntimeField5) && state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField5) == 0) { + // SDLFlushEvents2 accepts a fresh left/right press, not a keyboard skip. + const std::string title = "OpenBMH - live_shot_wait_" + identity; + SDL_SetWindowTitle(window, title.c_str()); + SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP); + SDL_Event input; + bool acknowledged = false; + while (running && !acknowledged) { + while (SDL_PollEvent(&input)) { + if (input.type == SDL_QUIT) { running = false; break; } + if (input.type == SDL_MOUSEBUTTONDOWN && + (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) { + acknowledged = true; + break; + } + } + if (!acknowledged && running) SDL_Delay(10); + } + } else { + // AdvanceStep(15): the ordinary saved pause instead of a click. + const int saved = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField7) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField7) : 0; + const int delay = live_frame_ms_explicit ? live_frame_ms : (saved < 6 ? saved / 2 : saved) * 20; + if (delay > 0) SDL_Delay(Uint32(delay)); + } + }, [&](const LiveSetPieceEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame=ui::live_matchday_frame(event.minute,groups,state); + if (frame.matches.empty()) return; + const auto images=live_screen.render_set_piece(frame,event); + LiveShotEvent palette_event; + palette_event.group=event.group;palette_event.match=event.match; + const auto colors=live_screen.shot_palette(palette,palette_event,groups,state); + for (size_t index=0;index0) { running=false;return; } + // FirstThen holds the first frame for 40 retraces; later frames + // use saved Main_FormatError_RuntimeField2. Keyboard/mouse input remains for the minute hook. + const int retraces=index==0?40:(state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2):0); + const int delay=live_frame_ms_explicit?live_frame_ms:retraces*1000/70; + if (delay>0) SDL_Delay(Uint32(delay)); + } + if (running && !live_frame_ms_explicit) SDL_Delay(200); // LiveMatchdayFrame + }, [&](const LiveBookingEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame=ui::live_matchday_frame(event.minute,groups,state); + if (frame.matches.empty()) return; + const auto booking=ui::live_booking_projection(event,groups,state,season_exe); + const std::string title="OpenBMH - live_booking_"+std::to_string(event.minute)+"_"+ + std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+ + std::to_string(event.side)+"_"+std::to_string(event.kind)+"_"+std::to_string(event.player); + const auto present=[&](const Image& image) { + for (size_t i=0;i0) { running=false;return; } + const int pause=event.kind==0?3:4; + const uint32_t address=::bmh::layout::Main_FormatError_ExecutableFieldUnsigned+uint32_t(pause*9); + const int saved=state.memory.has(address)?state.memory.u8(address):0; + const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20; + if (delay>0) SDL_Delay(Uint32(delay)); + // EventImpl clears the box after its pause; no Source click wait here. + SDL_SetWindowTitle(window,"OpenBMH - live_matchday");present(live_screen.render(frame)); + }, [&](const LiveShootoutEvent& event, const std::vector& groups, + const GameState& state) { + if (!running || live_skipped) return; + const auto frame=ui::live_matchday_frame(event.minute,groups,state); + if (frame.matches.empty()) return; + const auto projection=ui::live_shootout_projection(event,groups,state,season_exe); + const std::string title="OpenBMH - live_shootout_"+std::to_string(int(event.stage))+"_"+ + std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+ + std::to_string(event.side)+"_"+std::to_string(event.round)+"_"+ + std::to_string(event.of)+"_"+std::to_string(event.player); + SDL_SetWindowTitle(window,title.c_str()); + const auto image=live_screen.render_shootout(frame,projection); + for (size_t i=0;i0) { running=false;return; } + const int repeats=event.stage==LiveShootoutStage::preview?4:2; + const int saved=state.memory.has(::bmh::layout::Main_FormatError_RuntimeField6)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField6):0; + const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20; + for (int i=0;i0) SDL_Delay(Uint32(delay)); + }, [&](const LiveRealityEvent& event, const std::vector& groups, + const GameState& state) -> bool { + if (!running || live_skipped) return false; + const auto frame = ui::live_matchday_frame(event.minute,groups,state); + const auto present = [&](const Image& image,const Palette& colors,const std::string& title) { + SDL_SetWindowTitle(window,title.c_str()); + for (size_t i=0;i0) SDL_Delay(Uint32(ms)); + }; + const std::string identity=std::to_string(event.minute)+"_"+std::to_string(event.group)+"_"+ + std::to_string(event.match)+"_"+std::to_string(event.side); + if (event.stage==LiveRealityStage::begin) { + LiveChanceEvent header_event;header_event.minute=event.minute; + header_event.group=event.group;header_event.match=event.match;header_event.side=event.side; + const auto header=ui::live_chance_projection(header_event,groups,state,season_exe); + reality_pristine=live_screen.render_reality(frame,header); + reality_surface=reality_pristine;reality_layout={}; + reality_field=std::make_unique(data, + state.memory.has(::bmh::layout::Main_FormatError_RuntimeField3)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField3):0); + LiveShotEvent colors_event;colors_event.group=event.group;colors_event.match=event.match; + reality_colors=live_screen.shot_palette(palette,colors_event,groups,state); + present(reality_surface,reality_colors,"OpenBMH - live_reality_begin_"+identity); + return false; + } + if (event.stage==LiveRealityStage::settling) { + reality_field.reset(); + const int ms=live_frame_ms_explicit?live_frame_ms:200; // DecodeTaxAnimationScript2(10) + if (ms>0) SDL_Delay(Uint32(ms)); + return false; + } + if (event.stage==LiveRealityStage::end) { + present(live_screen.render(frame),palette,"OpenBMH - live_matchday"); + return false; + } + if (!reality_field) throw FormatError("Reality presentation: round without Source header"); + for (const auto& report:event.tick.reports) + reality_reporter.append(reality_surface,reality_layout,report.text,frame.gradient_text); + const std::string round_identity=identity+"_"+std::to_string(event.tick.round); + if (event.tick.motion) { + size_t index=0; + for (const auto& motion:event.tick.motion->frames) { + auto backdrop=reality_pristine; + std::copy_n(reality_surface.pixels.begin(),320*129,backdrop.pixels.begin()); + reality_surface=reality_field->render(motion,backdrop); + present(reality_surface,reality_colors,"OpenBMH - live_reality_round_"+ + round_identity+"_"+std::to_string(index++)); + delay(::bmh::layout::Main_FormatError_ExecutableField2); // RealityFieldScreen: the saved Reality speed + } + delay(::bmh::layout::Main_FormatError_ExecutableField+10*9); // AdvanceStep(10), after all eleven frames + } else { + present(reality_surface,reality_colors,"OpenBMH - live_reality_report_"+round_identity); + } + SDL_PumpEvents();SDL_Event input; + if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) {running=false;return true;} + // Consume only the Source exit for this scene. Other input remains + // queued for the existing live-minute/manager intervention boundary. + if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_KEYDOWN,SDL_KEYDOWN)>0 && + input.key.keysym.sym==SDLK_ESCAPE) { + SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_KEYDOWN,SDL_KEYDOWN);return true; + } + if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN)>0 && + input.button.button==SDL_BUTTON_RIGHT) { + SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true; + } + return false; + }, [&](const PhaseResultRequest& request, const std::vector& groups, + const GameState& state) { + if (!running) throw FormatError("phase results: presentation stopped"); + const auto frame = ui::live_matchday_frame(request.phase_end_minute, groups, state); + std::string error; + auto projection = session->open_phase_results(revision, live_screen.render(frame), error); + if (!projection) throw FormatError(error.empty() ? "phase results: Source viewer unavailable" : error); + const bool closed = present_running_overview(std::move(projection), state, revision, + [&](const app::CareerSession::LiveOverviewAction& action, std::string& dispatch_error, + const app::TransferOfferTeamInfoPresenter& team_info) { + return session->dispatch_phase_results(action, revision, dispatch_error, team_info); + }, &request); + if (!closed) throw FormatError("phase results: viewer stopped before Source ACK"); + }, true); + if (message == "career_complete") { running = false; return; } + if (!message.empty()) std::fprintf(stderr, "engine: %s\n", message.c_str()); + if (session) { + const auto autosave_error = session->take_autosave_error(); + if (!autosave_error.empty()) std::fprintf(stderr, "autosave: %s\n", autosave_error.c_str()); + } + // Table requests own their redraw boundary. In particular a + // same-league map ACK and a forecast Present ACK retain the frame. + if (!flow.in_family_table() || !message.empty()) dirty = true; + // DeskDate checks the pending mailbox latch after the normal desk + // request has completed. Poll only on the returned, idle desk so + // load/weekly/close acknowledgements can open the Source notice + // immediately without interrupting another modal or read-only view. + if (running && session && flow.desktop() && !flow.desktop()->pending() && + !flow.in_preparation_menu() && !flow.in_results_view() && + !flow.in_readonly_view() && !flow.in_mailbox() && flow.screen_name() == "desktop") { + if (auto mailbox = session->pending_mailbox_notification(revision)) { + flow.show_notified_mailbox(std::move(*mailbox)); + dirty = true; + } + } + if(!flow.timed_notice_open())timed_notice_presented_at.reset(); + SDL_SetWindowTitle(window, ("OpenBMH - " + flow.screen_name()).c_str()); + }; + const auto present_formation_save_feedback = [&] { + for (bool restored : {false, true}) { + const auto feedback = flow.pitch_formation_save_feedback(restored); + if (!feedback) break; + const auto image = process_timer_image(*feedback); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + if (SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4) != 0 || + SDL_RenderClear(renderer) != 0 || SDL_RenderCopy(renderer, texture, nullptr, nullptr) != 0) + throw std::runtime_error(std::string("Formation save renderer: ") + SDL_GetError()); + SDL_RenderPresent(renderer); + if (!restored) SDL_Delay(ui::PitchScreen::formation_save_flash_ms); + } + }; + const auto service_pitch_hold = [&] { + if (!press || press->pitch_hold_attempted || !flow.in_pitch() || + press->screen != flow.screen_name() || press->revision != revision) return; + const auto ticks = ui::pointer_hold_source_ticks(SDL_GetTicks64()) - press->source_tick; + if (!ui::pointer_source_hold_ready(ticks)) return; + int window_x=0,window_y=0; + if (!(SDL_GetMouseState(&window_x,&window_y) & SDL_BUTTON_LMASK)) return; + float x=0,y=0; + SDL_RenderWindowToLogical(renderer,window_x,window_y,&x,&y); + if (int(x)!=press->x || int(y)!=press->y) { press.reset(); return; } + press->pitch_hold_attempted = true; + const auto held = flow.pitch_held_left(press->x,press->y,ticks); + present_formation_save_feedback(); + handle(held); + }; + const auto pairings_clock_start = std::chrono::steady_clock::now(); + const auto pairings_source_seconds = [&] { + const auto milliseconds = std::chrono::duration_cast( + std::chrono::steady_clock::now() - pairings_clock_start).count(); + return ui::league_pairings_source_seconds(uint64_t(milliseconds)); + }; + const auto balance_source_milliseconds = [&] { + return uint64_t(std::chrono::duration_cast( + std::chrono::steady_clock::now()-pairings_clock_start).count()); + }; + // DecodeTaxAnimationScript2 multiplies its argument by 20 before host timer's + // millisecond conversion. This is the host unit scale, not a claim + // of parity with the Original DOS clock's quantization. + const auto family_table_source_units = [&] { + return balance_source_milliseconds() / 20; + }; + const auto mark_family_table_presented = [&] { + const auto acknowledged = flow.in_toto_calculator() + ? flow.after_toto_present(family_table_source_units()) + : flow.after_family_table_present(family_table_source_units()); + if (acknowledged.request != ui::FlowRequest::none) handle(acknowledged); + else dirty |= acknowledged.changed; + }; + const auto present_family_table_redraw = [&] { + if ((!flow.in_family_table() && flow.screen_name() != "toto") || !dirty) return; + const auto image = process_timer_image(flow.render()); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + if (SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4) != 0 || + SDL_RenderClear(renderer) != 0 || SDL_RenderCopy(renderer, texture, nullptr, nullptr) != 0) + throw std::runtime_error(std::string("Table renderer: ") + SDL_GetError()); + SDL_RenderPresent(renderer); + dirty = false; + mark_family_table_presented(); + }; + struct TableRangeKey { + std::string key; + ui::StrengthsIdentity identity; + int toto_manager = -1; + uint64_t toto_revision = 0; + }; + std::deque table_range_keys; + const auto queue_table_range_event = [&](const SDL_Event& event) { + if (!flow.in_toto_calculator() && + (!flow.in_family_table_range_dialog() || !flow.league_family_identity())) return false; + const auto queue = [&](std::string key) { + if (flow.in_toto_calculator()) + table_range_keys.push_back({std::move(key), {}, flow.toto()->state().manager_slot, + flow.toto()->state().revision}); + else table_range_keys.push_back({std::move(key), *flow.league_family_identity()}); + }; + if (event.type == SDL_TEXTINPUT) { + const std::string_view text(event.text.text); + if (std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; })) + for (char c : text) queue(std::string(1, c)); + return true; + } + if (event.type != SDL_KEYDOWN) return false; + if (event.key.keysym.sym == SDLK_RETURN) queue("ENTER"); + else if (event.key.keysym.sym == SDLK_BACKSPACE) queue("BACKSPACE"); + else if (event.key.keysym.sym == SDLK_SPACE) queue("SPACE"); + // No SDL Escape/right-button origin for Source raw event 8 has + // been established for this modal. Unsupported keys stay owned. + return true; + }; + const auto service_family_table = [&] { + if (!flow.in_family_table() && flow.screen_name() != "toto") { table_range_keys.clear(); return; } + const auto tick = flow.in_toto_calculator() + ? flow.tick_toto_source_units(family_table_source_units()) + : flow.tick_family_table_source_units(family_table_source_units()); + if (tick.request != ui::FlowRequest::none) handle(tick); + else dirty |= tick.changed; + present_family_table_redraw(); + if (!flow.in_family_table_range_dialog() && !flow.in_toto_calculator()) table_range_keys.clear(); + while (!table_range_keys.empty() && + (flow.family_table_range_input_ready() || flow.toto_calculator_input_ready())) { + auto input = std::move(table_range_keys.front()); + table_range_keys.pop_front(); + if ((input.toto_manager >= 0 && flow.in_toto_calculator() && + input.toto_manager == flow.toto()->state().manager_slot && + input.toto_revision == flow.toto()->state().revision) || + (input.toto_manager < 0 && flow.league_family_identity() && input.identity == *flow.league_family_identity())) { + handle(flow.send_key(input.key)); + present_family_table_redraw(); + } + } + }; + std::optional presented_balance; + bool presented_balance_notice=false; + const auto present_balance_redraw = [&] { + if (!flow.in_balance()) { presented_balance.reset();presented_balance_notice=false; return; } + const auto identity=flow.balance()->state().identity; + const bool notice=flow.balance()->notice_open(); + if(presented_balance&&*presented_balance==identity&¬ice==presented_balance_notice)return; + const auto image=process_timer_image(flow.render()); + for(size_t i=0;i calculator_release; + std::optional calculator_tick_anchor; + struct CalculatorKey { + std::string key; + uint64_t revision = 0, scope = 0, sequence = 0; + }; + std::deque calculator_keys; + const auto queue_calculator_key = [&](std::string key) { + const auto& owner = flow.stadium()->state(); + calculator_keys.push_back({std::move(key), owner.revision, owner.scope, owner.sequence}); + }; + const auto queue_calculator_event = [&](const SDL_Event& event) { + if (event.type == SDL_TEXTINPUT) { + const std::string_view text(event.text.text); + if (!std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; })) + return true; + for (const char c : text) queue_calculator_key(std::string(1, c)); + return true; + } + if (event.type != SDL_KEYDOWN) return false; + if (event.key.keysym.sym == SDLK_RETURN) queue_calculator_key("ENTER"); + else if (event.key.keysym.sym == SDLK_BACKSPACE) queue_calculator_key("BACKSPACE"); + else if (event.key.keysym.sym == SDLK_SPACE) queue_calculator_key("SPACE"); + // The calculator owns every keyboard event. Unsupported keys, + // including Escape, must not reach the outer application shortcut. + // Digits arrive separately through SDL_TEXTINPUT. + return true; + }; + const auto mark_stadium_calculator_presented = [&] { + if (!flow.in_stadium() || !flow.stadium()->calculator_source_waiting()) { + calculator_tick_anchor.reset(); + return; + } + flow.mark_stadium_calculator_presented(); + if (!calculator_tick_anchor) calculator_tick_anchor = balance_source_milliseconds(); + }; + const auto service_stadium_calculator = [&] { + if (!flow.in_stadium()) { + calculator_release.reset(); calculator_tick_anchor.reset(); + calculator_keys.clear(); + return; + } + if (flow.stadium()->calculator_source_waiting() && calculator_tick_anchor) { + const uint64_t now = balance_source_milliseconds(); + const uint64_t ticks = (now - *calculator_tick_anchor) / 20; + if (ticks != 0) { + // No wait exceeds fifty ticks, so bound narrowing and keep + // the unused remainder for the next physical-clock sample. + const unsigned step = unsigned(std::min(ticks, 50)); + *calculator_tick_anchor += uint64_t(step) * 20; + const auto tick = flow.tick_stadium_calculator_source_ticks(step); + if (tick.request != ui::FlowRequest::none) handle(tick); + else dirty |= tick.changed; + } + } + if (!flow.in_stadium()) { + calculator_release.reset(); calculator_tick_anchor.reset(); + calculator_keys.clear(); + return; + } + if (!flow.stadium()->calculator_source_waiting()) { + calculator_tick_anchor.reset(); + if (calculator_release) { + const auto release = *calculator_release; + calculator_release.reset(); + const auto& owner = flow.stadium()->state(); + if (owner.scope == release.scope && owner.sequence == release.sequence && + flow.stadium()->calculator_waiting_for_key_release()) + handle(flow.click(release.button.x, release.button.y)); + press.reset(); + } + } + if (!flow.stadium()->calculator_open()) calculator_keys.clear(); + while (!calculator_keys.empty() && !flow.stadium()->calculator_source_waiting() && + !flow.stadium()->calculator_waiting_for_key_release() && !flow.stadium()->pending()) { + auto input = std::move(calculator_keys.front()); + calculator_keys.pop_front(); + const auto& owner = flow.stadium()->state(); + if (owner.revision == input.revision && owner.scope == input.scope && + owner.sequence == input.sequence) + handle(flow.send_key(input.key)); + } + }; + std::optional presented_pairings; + const auto present_pairings_redraw = [&] { + if (!flow.in_league_pairings()) { presented_pairings.reset(); return; } + const auto identity = flow.league_pairings()->state().identity; + if (presented_pairings && *presented_pairings == identity) return; + const auto image = process_timer_image(flow.render()); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + flow.mark_league_pairings_presented_source_seconds(pairings_source_seconds()); + presented_pairings = identity; + dirty = false; + }; + const auto service_pairings_timer = [&] { + present_pairings_redraw(); + const auto tick = flow.tick_league_pairings_source_seconds(pairings_source_seconds()); + if (tick.request != ui::FlowRequest::none) { + handle(tick); + // Move anchors its clock after each accepted full redraw. + present_pairings_redraw(); + } + }; + //PresentManagerDialog presents its question before polling2de66. Bind the actual + //freshly drawn frame, never an old texture or a preceding modal ACK. + using StadiumQuestionFrame = std::array; + std::optional presented_stadium_question; + const auto stadium_question_frame = [&]() -> std::optional { + if (!session || !flow.in_stadium()) return {}; + const auto& question=flow.stadium()->state(); + if (!question.construction_tip_dialog && !question.periphery_quote_dialog) return {}; + const auto& state=flow.stadium()->state(); + return StadiumQuestionFrame{session->session_id(),uint64_t(state.manager_slot),state.scope,state.sequence,state.revision}; + }; + const auto mark_stadium_question_presented = [&] { presented_stadium_question=stadium_question_frame(); }; + const auto service_stadium_deadline = [&] { + const auto owner=stadium_question_frame(); + if (!owner || owner!=presented_stadium_question) return false; + if (!session->stadium_tip_deadline_expired() && !poll_process_timer(false,false)) return false; + const auto expired = flow.expire_stadium_tip(); + if (expired.request == ui::FlowRequest::none) return false; + handle(expired); + return true; + }; + const auto service_idle_stadium_deadline = [&] { + // OriginalMouseSound/Sample can synthesize event8 on expiry, including idle. + // ExpireQuestion's held-button helper must return before57ef7 answers. + if (flow.in_stadium() && !flow.stadium()->construction_tip_held()) + service_stadium_deadline(); + }; + using NationalPickerFrame = std::pair; + std::optional presented_national_picker; + const auto national_picker_frame = [&]() -> std::optional { + if (!session || flow.screen_name() != "national_friendly_picker" || !flow.national_friendly_owner()) return {}; + return NationalPickerFrame{session->session_id(),*flow.national_friendly_owner()}; + }; + const auto mark_national_picker_presented = [&] { presented_national_picker=national_picker_frame(); }; + using FriendlyPickerFrame = std::array; + std::optional presented_friendly_picker; + const auto friendly_picker_frame = [&]() -> std::optional { + const auto* picker=flow.friendly_opponent_picker(); + if (!session || !picker || !flow.desktop()) return {}; + const auto& desk=flow.desktop()->state(); + return FriendlyPickerFrame{session->session_id(),uint64_t(desk.manager_slot), + uint64_t(desk.runtime_club),desk.revision,uint64_t(picker->selected_league())}; + }; + const auto mark_friendly_picker_presented = [&] { presented_friendly_picker=friendly_picker_frame(); }; + using FriendlyCalendarFrame = std::array; + std::optional presented_friendly_calendar; + const auto friendly_calendar_frame = [&]() -> std::optional { + if (!session || !flow.friendly_calendar_quote()) return {}; + const auto& quote=*flow.friendly_calendar_quote(); + return FriendlyCalendarFrame{session->session_id(),uint64_t(quote.manager_slot), + uint64_t(quote.runtime_team),quote.revision,quote.request_id}; + }; + const auto mark_friendly_calendar_presented = [&] { presented_friendly_calendar=friendly_calendar_frame(); }; + using FriendlyQuestionFrame = std::array; + std::optional presented_friendly_question; + const auto friendly_question_frame = [&]() -> std::optional { + const auto* question=flow.friendly_question_screen(); + if(!session||!question||!flow.desktop())return {}; + const auto& desk=flow.desktop()->state(); + return FriendlyQuestionFrame{session->session_id(),uint64_t(desk.manager_slot), + uint64_t(desk.runtime_club),desk.revision,uint64_t(question->stage()), + uint64_t(question->selected_opponent()),question->quote()?question->quote()->request_id:0, + uint64_t(question->active_question()->source_manager_flags)}; + }; + const auto mark_friendly_question_presented = [&] { presented_friendly_question=friendly_question_frame(); }; + const auto service_friendly_question_deadline = [&] { + const auto owner=friendly_question_frame(); + if(!owner||owner!=presented_friendly_question||!poll_process_timer(false,false))return false; + const auto expired=flow.expire_friendly_question(true); + if(expired.request==ui::FlowRequest::none&&!expired.changed)return false; + handle(expired);return true; + }; + const auto service_process_timer = [&] { + // SDLFlushEvents3's notice owns its wait. Keep the desk clock polling, + // but hand its outer expiry back only after this notice restores. + if(flow.timed_notice_open()) { poll_process_timer(!dirty,false); return; } + if (!session || !flow.desktop()) { + process_timer.stop(); process_timer_owner.reset(); process_timer_frame.reset(); + return; + } + if (flow.screen_name() == "desktop") { + const auto& desk = flow.desktop()->state(); + const ProcessTimerOwner owner{session->session_id(), desk.manager_slot, desk.day_counter}; + const auto minutes = session->state().memory.u8(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField); + if (!process_timer_owner || *process_timer_owner != owner) { + process_timer.start(minutes, process_source_seconds()); process_timer_owner = owner; + } else if (process_timer.paused()) { + process_timer.resume(minutes, process_source_seconds()); + } + } + // ExpireQuestion's held controls and Source calculator waits own their + // release. The outer event8 is serviced after that owner returns. + //1e06b paints its initial nation bank before the first2de66 poll. + const auto picker_owner=national_picker_frame(); + if (picker_owner && picker_owner!=presented_national_picker) return; + //50775 paints its accepted league before its first51135/OriginalMouseSound poll. + const auto friendly_picker_owner=friendly_picker_frame(); + if (!friendly_picker_owner) presented_friendly_picker.reset(); + if (friendly_picker_owner && friendly_picker_owner!=presented_friendly_picker) return; + //CalendarCell presents the initial calendar before its input loop. + const auto calendar_owner=friendly_calendar_frame(); + if (calendar_owner && calendar_owner!=presented_friendly_calendar) return; + const auto question_owner=stadium_question_frame(); + if (question_owner && question_owner!=presented_stadium_question) return; + const auto friendly_question_owner=friendly_question_frame(); + if(!friendly_question_owner)presented_friendly_question.reset(); + if(friendly_question_owner&&friendly_question_owner!=presented_friendly_question)return; + if (press || (flow.friendly_question_screen()&&flow.friendly_question_screen()->question_held())) { + //ExpireQuestion still polls the clock while holding its button. Only + //the timer row advances; the answer and frame ACK stay owned. + if (question_owner || friendly_picker_owner || friendly_question_owner) poll_process_timer(!dirty,false); + return; + } + // A clock repaint never re-enters a table/forecast draw or ACK. + if (poll_process_timer(!dirty, false)) { + int window_x=0,window_y=0; + SDL_GetMouseState(&window_x,&window_y); + float logical_x=0,logical_y=0; + SDL_RenderWindowToLogical(renderer,window_x,window_y,&logical_x,&logical_y); + const auto expired = flow.process_timer_expired(int(logical_x),int(logical_y)); + if (expired.request != ui::FlowRequest::none || expired.changed) handle(expired); + } + }; + SDL_StartTextInput(); + while (running) { + if(timed_notice_presented_at && flow.timed_notice_open() && + SDL_GetTicks64()-*timed_notice_presented_at>=70*3*20) + handle(flow.expire_timed_notice()); + service_process_timer(); + if (!running) break; + SDL_Event e; + while (SDL_PollEvent(&e)) { + if (e.type == SDL_QUIT) { + running = false; + break; + } + if(e.type==SDL_MOUSEBUTTONUP&&timed_notice_release&&e.button.button==*timed_notice_release) { + timed_notice_release.reset();continue; + } + if(flow.timed_notice_open()&&e.type==SDL_MOUSEBUTTONDOWN&& + (e.button.button==SDL_BUTTON_LEFT||e.button.button==SDL_BUTTON_RIGHT)) { + // PresentManagerDialog consumes DOWN. Do not deliver its release to + // the restored caller as a second booking/purchase. + timed_notice_release=e.button.button;press.reset(); + handle(flow.expire_timed_notice());continue; + } + if(flow.timed_notice_open()&&(e.type==SDL_KEYDOWN||e.type==SDL_TEXTINPUT))continue; + // InLeaguePairings handles a changed league selector before5147b's + // timer. Preserve that precedence without moving other inputs. + bool selector_consumed = false; + if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT && + flow.in_league_pairings()) { + const auto selection = flow.league_pairings()->selector_event(e.button.x,e.button.y); + if (selection && (selection->kind == LeaguePairingsAction::toggle_group || + selection->value != flow.league_pairings()->state().source.owner.league)) { + handle(flow.pointer_down(e.button.x,e.button.y)); + present_pairings_redraw(); + selector_consumed = true; + } + } + // Other polled input keeps the Original timer precedence; + // held controls remain blocked by release ownership. + service_process_timer(); + service_pairings_timer(); + service_balance_timer(); + service_family_table(); + service_stadium_calculator(); + service_idle_stadium_deadline(); + if (queue_table_range_event(e)) { + service_family_table(); + continue; + } + if (flow.in_stadium() && flow.stadium()->calculator_source_waiting()) { + // DecodeTaxAnimationScript2 delays without consuming keyboard input. Retain + // FIFO keys for this accepted calculator owner, including + // every digit of one SDL text-input packet. + queue_calculator_event(e); + if (e.type == SDL_MOUSEBUTTONUP && e.button.button == SDL_BUTTON_LEFT && + flow.stadium()->calculator_waiting_for_key_release() && !calculator_release) { + const auto& owner = flow.stadium()->state(); + calculator_release = CalculatorRelease{e.button, owner.scope, owner.sequence}; + } + // The Source calculator helper owns input until its wait + // completes. SDL_QUIT was serviced above this barrier. + continue; + } + if (flow.in_stadium() && flow.stadium()->calculator_open() && queue_calculator_event(e)) { + service_stadium_calculator(); + continue; + } + if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE && + !flow.in_preparation_menu() && !flow.in_results_view() && !flow.in_readonly_view()) + running = false; + if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT) + press = Press{e.button.x, e.button.y, SDL_GetTicks(), flow.screen_name(), + ui::pointer_hold_source_ticks(SDL_GetTicks64()), revision}; + if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_RIGHT) + right_press_screen = flow.screen_name(); + if(!selector_consumed&&e.type==SDL_MOUSEBUTTONDOWN&&(flow.desktop()||flow.in_balance()||flow.in_desk_records()||flow.in_achievements()||flow.in_indoor_standings()||flow.in_reschedule_calendar()||flow.in_league_pairings()||flow.in_family_table()||flow.in_toto_calculator()||flow.in_stadium()||flow.in_environment()||flow.in_strengths()||flow.in_top_scorers()||flow.in_opportunities()||flow.in_statistics_menu()||flow.in_statistics_page()||flow.in_analytics()||flow.in_other_games()||flow.in_pitch()||flow.in_settings())&& + (e.button.button==SDL_BUTTON_LEFT||e.button.button==SDL_BUTTON_RIGHT)) { + handle(flow.pointer_down(e.button.x,e.button.y,e.button.button==SDL_BUTTON_RIGHT)); + if (!running) break; + if(flow.in_family_table()) { + // This path also owns pressed KB6 frames. Upload and + // copy must succeed before their Present starts a wait + // or commits a staged forecast random stream. + present_family_table_redraw(); + } else if(flow.in_balance()||flow.in_desk_records()||flow.in_achievements()||flow.in_indoor_standings()||flow.in_reschedule_calendar()||flow.in_league_pairings()||flow.in_stadium()||flow.in_environment()||flow.in_strengths()||flow.in_top_scorers()||flow.in_opportunities()||flow.in_statistics_menu()||flow.in_statistics_page()||flow.in_analytics()||flow.in_other_games()||flow.in_pitch()||flow.in_settings()||flow.friendly_question_screen()) { + //48529/ExpireQuestion/67e80 present the held control before waiting + //for its release. The existing UP ownership remains intact. + const auto image=process_timer_image(flow.render()); + for(size_t i=0;isocket_confirmation_armed()) { + // SDLSetWindowTitle paints its pressed socket sprite before + // DeskDate waits for the physical release. + SDL_SetWindowTitle(window, "OpenBMH - desktop"); + const auto image=process_timer_image(flow.render()); + for(size_t i=0;ix && e.button.y == press->y && + press->screen == flow.screen_name() && SDL_GetTicks() - press->time >= 2000; + const auto released = held ? flow.hold(e.button.x, e.button.y, 2000) + : flow.click(e.button.x, e.button.y, e.button.button == SDL_BUTTON_RIGHT, e.button.clicks >= 2); + present_formation_save_feedback(); + handle(released); + present_desk_record_points(); + press.reset(); + } + if (e.type == SDL_MOUSEMOTION) { + if (press && (e.motion.x != press->x || e.motion.y != press->y)) press.reset(); + const auto moved = flow.move_action(e.motion.x, e.motion.y); + if (moved.request != ui::FlowRequest::none) handle(moved); + else dirty |= moved.changed; + // BalanceFromGame presents a drag move before sampling the next + // keyboard/mouse event, even when both are already queued. + present_family_table_redraw(); + } + if (e.type == SDL_TEXTINPUT) { + try { + dirty |= flow.text(e.text.text); + present_desk_record_points(); + } catch (const FormatError& err) { + std::fprintf(stderr, "input: %s\n", err.what()); + } + } + if (e.type == SDL_KEYDOWN && (e.key.keysym.sym == SDLK_RETURN || e.key.keysym.sym == SDLK_BACKSPACE || + (flow.screen_name() == "save_load" && (e.key.keysym.sym == SDLK_UP || + e.key.keysym.sym == SDLK_DOWN || e.key.keysym.sym == SDLK_PAGEUP || e.key.keysym.sym == SDLK_PAGEDOWN)) || + ((flow.in_preparation_menu() || flow.in_results_view() || flow.in_readonly_view()) && e.key.keysym.sym == SDLK_ESCAPE) || + ((flow.in_results_view() || flow.in_readonly_view() || flow.screen_name() == "friendly_match") && (e.key.keysym.sym == SDLK_LEFT || + e.key.keysym.sym == SDLK_RIGHT || e.key.keysym.sym == SDLK_SPACE)) || + ((flow.in_balance() || flow.in_stadium()) && e.key.keysym.sym == SDLK_SPACE) || + (flow.desktop() && !flow.in_balance() && e.key.keysym.sym >= SDLK_a && e.key.keysym.sym <= SDLK_z))) { + const std::string key = e.key.keysym.sym == SDLK_RETURN ? "ENTER" + : e.key.keysym.sym == SDLK_BACKSPACE ? "BACKSPACE" + : e.key.keysym.sym == SDLK_ESCAPE ? "ESC" + : e.key.keysym.sym == SDLK_LEFT ? "LEFT" + : e.key.keysym.sym == SDLK_RIGHT ? "RIGHT" + : e.key.keysym.sym == SDLK_SPACE ? "SPACE" + : e.key.keysym.sym == SDLK_UP ? "UP" + : e.key.keysym.sym == SDLK_DOWN ? "DOWN" + : e.key.keysym.sym == SDLK_PAGEUP ? "PAGEUP" + : e.key.keysym.sym == SDLK_PAGEDOWN ? "PAGEDOWN" + : std::string(1, char('A' + e.key.keysym.sym - SDLK_a)); + handle(flow.send_key(key)); + present_desk_record_points(); + } + if (!running) break; + } + if (!running) break; + service_pitch_hold(); + if (!running) break; + service_process_timer(); + service_pairings_timer(); + service_balance_timer(); + service_family_table(); + service_stadium_calculator(); + service_idle_stadium_deadline(); + if (const auto* desk = flow.desktop()) + for (const auto id : desk->take_sound_ids()) app::original_audio_command(playback, id); + if (session) playback.set_original_options(app::original_audio_options(session->state(), music_enabled)); + if (playback.needs_pump()) { + playback.pump(audio_error); + if (!audio_error.empty()) std::fprintf(stderr, "audio: %s\n", audio_error.c_str()); + } + if (flow.in_family_table()) { + // Family ACKs belong to a freshly rendered, successfully + // copied image. Do not ACK an old texture at the routine + // end-of-loop Present after an earlier ACK changed the Flow. + present_family_table_redraw(); + } else { + // A preceding service Present can request the calculator's + // restored-underlay frame. This fresh end-of-loop frame owns + // its own ACK; an unchanged texture never advances the modal. + const bool toto_calculator_redraw = dirty && flow.in_toto_calculator(); + const bool stadium_redraw = dirty && flow.in_stadium(); + const bool national_picker_redraw = dirty && national_picker_frame().has_value(); + const bool friendly_picker_redraw = dirty && friendly_picker_frame().has_value(); + const bool friendly_calendar_redraw = dirty && friendly_calendar_frame().has_value(); + const bool friendly_question_redraw = dirty && friendly_question_frame().has_value(); + const bool source_modal_redraw = toto_calculator_redraw || stadium_redraw || + national_picker_redraw || friendly_picker_redraw || friendly_calendar_redraw || friendly_question_redraw; + if (dirty) { + const auto image = process_timer_image(flow.render()); + for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; + if (SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4) != 0 && source_modal_redraw) + throw std::runtime_error(std::string("Source modal texture: ") + SDL_GetError()); + dirty = false; + } + const int cleared = SDL_RenderClear(renderer); + const int copied = SDL_RenderCopy(renderer, texture, nullptr, nullptr); + if (source_modal_redraw && (cleared != 0 || copied != 0)) + throw std::runtime_error(std::string("Source modal renderer: ") + SDL_GetError()); + SDL_RenderPresent(renderer); + if(flow.timed_notice_open()&&!timed_notice_presented_at) + timed_notice_presented_at=SDL_GetTicks64(); + if (stadium_redraw) mark_stadium_question_presented(); + if (national_picker_redraw) mark_national_picker_presented(); + if (friendly_picker_redraw) mark_friendly_picker_presented(); + if (friendly_calendar_redraw) mark_friendly_calendar_presented(); + if (friendly_question_redraw) mark_friendly_question_presented(); + if (toto_calculator_redraw) mark_family_table_presented(); + mark_stadium_calculator_presented(); + if(flow.in_balance()) { + const auto identity=flow.balance()->state().identity; + const bool notice=flow.balance()->notice_open(); + flow.mark_balance_presented_source_milliseconds(balance_source_milliseconds()); + presented_balance=identity;presented_balance_notice=notice; + } + } + SDL_Delay(10); + } + SDL_StopTextInput(); + SDL_DestroyTexture(texture); + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + mouse_sound.detach(); // Remove event producers before closing the audio device. + playback.shutdown(); + SDL_Quit(); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "error: %s\n", e.what()); + SDL_Quit(); + return 1; + } +} diff --git a/src/app/window_actions.cpp b/src/app/window_actions.cpp new file mode 100644 index 0000000..bb640dc --- /dev/null +++ b/src/app/window_actions.cpp @@ -0,0 +1,509 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "app/window_actions.hpp" +#include "app/action_transaction.hpp" +#include "game/save.hpp" +#include "game/lineup.hpp" + +#include +#include + +namespace bmh::app { +using detail::apply_window; + +bool LeagueFamilyActions::apply(uint64_t& revision, const std::function& action) { + auto before = session_.league_family_checkpoint(); + const auto old_revision = revision; + try { + if (action()) return true; + } catch (...) { + session_.restore_league_family_checkpoint(std::move(before)); + revision = old_revision; + throw; + } + session_.restore_league_family_checkpoint(std::move(before)); + revision = old_revision; + return false; +} + +std::optional LeagueFamilyActions::open_pairings( + const ui::DeskState& observed, uint64_t& revision, std::string& error) { + ui::DeskRequest request; + request.kind = ui::DeskRequestKind::open_menu; + request.menu_kind = 1; + request.manager_slot = observed.manager_slot; + request.revision = observed.revision; + for (const auto& item : observed.items) + if (item.kind == 1) request.item_id = item.id; + std::optional result; + apply(revision, [&] { + result = session_.open_league_pairings(request, revision, error); + return result.has_value(); + }); + return result; +} + +std::optional LeagueFamilyActions::pairings( + const ui::LeaguePairingsIdentity& observed, LeaguePairingsAction kind, int value, + uint64_t& revision, std::string& error) { + ui::LeaguePairingsRequest request; + request.identity = observed; + request.event.kind = kind; + request.event.value = value; + std::optional result; + apply(revision, [&] { + result = session_.dispatch_league_pairings(request, revision, error); + return result.has_value(); + }); + return result; +} + +ui::DeskRequest LeagueFamilyActions::pairings_entry(const ui::StrengthsIdentity& identity, + uint64_t revision) { + return {ui::DeskRequestKind::open_menu, identity.manager, 0, 1, -1, revision}; +} + +ui::LeaguePairingsRequest LeagueFamilyActions::pairings_selection( + const ui::LeaguePairingsIdentity& identity, int league) { + return {identity, {LeaguePairingsAction::select_league, league, -1}}; +} + +ui::StrengthsRequest LeagueFamilyActions::strengths_entry(const ui::StrengthsRequest& fresh, + const ui::StrengthsIdentity& identity) { + auto request = fresh; + request.identity = identity; + request.kind = ui::StrengthsAction::open; + return request; +} + +bool TransferActions::apply(uint64_t& revision, const std::function& action) { + auto state = session_.g_; + const auto game = session_.game_; + const auto rand = session_.rand_; + auto owner = session_.transfer_offer_editor_; + auto poach = session_.poach_; + const auto owner_revision = session_.transfer_offer_revision_; + auto runtime = session_.club_modal_runtime_; + const auto old_revision = revision; + const auto restore = [&] { + session_.g_ = std::move(state); + session_.game_ = game; + session_.rand_ = rand; + session_.transfer_offer_editor_ = std::move(owner); + session_.poach_ = std::move(poach); + session_.transfer_offer_revision_ = owner_revision; + session_.club_modal_runtime_ = std::move(runtime); + revision = old_revision; + }; + try { + if (action()) return true; + } catch (...) { + restore(); + throw; + } + restore(); + return false; +} + +std::optional TransferActions::market( + const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& hooks, + uint64_t& revision, std::string& error, HumanBuyerMarketEntryPolicy policy, + const MarketAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + const auto old_revision = revision; + if (policy == HumanBuyerMarketEntryPolicy::normal_interactive) { + const auto action = session_.dispatch_transfer_market(request, hooks, revision, error); + if (!action) return false; + result = MarketDispatch{*action, revision != old_revision}; + } else { + // Preserve the legacy caller's threshold draw even for a low offer. + // This path predates the interactive Source sale and has its own + // revision semantics; moving it must not merge the two policies. + error = rejection(request, revision, policy); + if (!error.empty()) return false; + if (request.kind != ui::TransferMarketRequestKind::list_player && + request.kind != ui::TransferMarketRequestKind::submit_bid) { + error = "Diese Transferaktion ist nicht verfügbar."; + return false; + } + const auto before = save_stream(session_.state()); + const auto game_calls = session_.game().calls(); + const auto rand_calls = session_.rand().calls(); + TransferActionResult action; + if (request.kind == ui::TransferMarketRequestKind::list_player) { + MinuteReport report; + action = list_manager_player(session_.state(), request.manager_slot, + request.squad_row, session_.rand(), report); + if (report.unsupported) throw FormatError("unsupported transfer listing"); + } else { + action = submit_transfer_bid(session_.state(), request.bid, session_.rand()); + } + const bool changed = session_.game().calls() != game_calls || + session_.rand().calls() != rand_calls || save_stream(session_.state()) != before; + if (changed) ++revision; + result = MarketDispatch{action, changed}; + } + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::string TransferActions::rejection(const ui::TransferMarketRequest& request, + uint64_t revision, HumanBuyerMarketEntryPolicy policy) const { + const auto& state = session_.state(); + if (request.manager_slot < 0 || size_t(request.manager_slot) >= state.manager_teams.size() || + request.manager_slot > 3 || !state.memory.has(::bmh::layout::ActiveManager) || + state.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot || + request.runtime_club != state.manager_teams[size_t(request.manager_slot)] || + request.revision != revision || revision == std::numeric_limits::max()) + return "Dieses Transferangebot gehört zu einem veralteten Spielstand."; + 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(), [policy](uint32_t value) { + return value > (policy == HumanBuyerMarketEntryPolicy::normal_interactive ? 255u : 100u); + })) return "Die Angaben zum Transferangebot sind ungültig."; + } 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) >= state.squad_slots.size() || + request.expected_player < 0 || request.expected_player >= 0xfff || + (state.squad_slots[range.first + size_t(request.squad_row)] & 0xfff) != request.expected_player) + return "Dieser Spieler gehört nicht mehr zur gewählten Kaderposition."; + } else if (request.kind != ui::TransferMarketRequestKind::open_offer && + request.kind != ui::TransferMarketRequestKind::preview_quote && + request.kind != ui::TransferMarketRequestKind::open_poach) + return "Diese Transferaktion ist nicht verfügbar."; + return {}; +} + +std::optional TransferActions::open_offer( + const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error, + const OfferAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.open_transfer_offer(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional TransferActions::preview( + const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error, + const PreviewAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.preview_transfer_market(request, revision, error); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional TransferActions::offer( + const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& hooks, + uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info, + const TransferOfferPlayerInfoPresenter& player_info, const OfferAccept& acknowledge) { + std::optional result; + apply(revision, [&] { + result = session_.dispatch_transfer_offer(request, hooks, revision, error, team_info, player_info); + if (!result) return false; + if (acknowledge) acknowledge(*result); + return true; + }); + return result; +} + +std::optional TransferActions::poach(int manager, int slot, + uint64_t& revision, std::string& error) { + std::optional result; + apply(revision, [&] { + result = session_.open_poach(manager, slot, revision, error); + return result.has_value(); + }); + return result; +} + +ui::TransferMarketRequest TransferActions::listing(const ui::TransferMarketState& observed, + const ui::TransferMarketSquadItem& item, bool loan) { + ui::TransferMarketRequest request; + request.kind = ui::TransferMarketRequestKind::list_player; + request.offer_is_loan = loan; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.revision = observed.revision; + request.squad_row = item.row; + request.expected_player = item.player; + request.selected_players.push_back({-1, observed.roster.squad_start_offset + item.row, + item.player, observed.runtime_club, item.row}); + return request; +} + +ui::TransferMarketRequest TransferActions::opening(const ui::TransferMarketState& observed, + const ui::TransferMarketItem& item, bool loan) { + ui::TransferMarketRequest request; + request.kind = ui::TransferMarketRequestKind::open_offer; + request.offer_is_loan = loan; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.revision = observed.revision; + if (item.own_bid) request.bid = *item.own_bid; + request.bid.manager = observed.manager_slot; + request.bid.list_entry = item.list_entry; + request.bid.player = item.player; + request.bid.source_slot = item.source_slot; + request.selected_players.push_back({item.list_entry, item.source_slot, item.player, item.seller, -1}); + return request; +} + +ui::OutgoingTransferRequest TransferActions::editor(const ui::OutgoingTransferEditorState& observed, + ui::OutgoingTransferRequestKind kind, ui::OutgoingTransferField field, uint32_t value) { + ui::OutgoingTransferRequest request; + request.kind = kind; + request.identity = {observed.manager_slot, observed.runtime_club, observed.revision, + observed.list_entry, observed.source_slot, observed.player, observed.seller, observed.bid_slot}; + request.field = field; + request.value = value; + request.quote_loan = observed.quote_loan; + request.fee = observed.fee; + request.monthly_salary = observed.monthly_salary; + request.duration_years = observed.duration_years; + request.bonuses = observed.bonuses; + request.quoted_fee = observed.panel.quoted_fee; + request.quoted_monthly_salary = observed.panel.quoted_monthly_salary; + request.quoted_years = observed.panel.quoted_years; + return request; +} + +bool BankActions::apply(uint64_t& revision, const std::function& action) { + return apply_window(session_, revision, session_.bank_checkpoint(), + [&](CareerSession::BankCheckpoint before) { session_.restore_bank_checkpoint(std::move(before)); }, action); +} + +bool BankActions::dispatch(const ui::BankRequest& request, uint64_t& revision, std::string& error, + const std::function& acknowledge) { + return apply(revision, [&] { + if (!session_.dispatch_bank(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +ui::BankRequest BankActions::bind(const ui::BankState& observed, ui::BankRequestKind kind) { + ui::BankRequest request; + request.kind = kind; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.revision = observed.revision; + return request; +} + +ui::BankRequest BankActions::savings(const ui::BankState& observed, int32_t amount) { + auto request = bind(observed, ui::BankRequestKind::move_to_deposit); + request.amount = amount; + return request; +} + +ui::BankRequest BankActions::investment(const ui::BankState& observed, ui::BankRequestKind kind, + int asset, int count) { + auto request = bind(observed, kind); + request.asset_index = asset; + request.count = count; + return request; +} + +ui::BankRequest BankActions::credit(const ui::BankState& observed, const BankCreditContext& context, + const BankCreditDraft& draft, bool accept_fees, int counterparty) { + auto request = bind(observed, ui::BankRequestKind::bank_credit); + request.expected_credit = context.saved; + request.credit_edits = draft.edits; + request.accept_credit_fees = accept_fees; + request.credit_counterparty = counterparty; + return request; +} + +bool StadiumActions::apply(uint64_t& revision, const std::function& action) { + return apply_window(session_, revision, session_.stadium_checkpoint(), + [&](CareerSession::StadiumCheckpoint before) { session_.restore_stadium_checkpoint(std::move(before)); }, action); +} + +bool StadiumActions::dispatch(const ui::StadiumRequest& request, uint64_t& revision, std::string& error, + const ConstructionNoticeHook& construction, const SeasonTicketCompensationNoticeHook& compensation, + const std::function& acknowledge) { + return apply(revision, [&] { + if (!session_.dispatch_stadium(request, revision, error, construction, compensation)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +ui::StadiumRequest StadiumActions::request(const ui::StadiumState& observed, ui::StadiumRequestKind kind, + int object, int option, int32_t price, bool accept_tip) { + ui::StadiumRequest request; + request.kind = kind; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.stable_club_identity = observed.stable_club_identity; + request.revision = observed.revision; + request.scope = observed.scope; + request.sequence = observed.sequence; + request.object = object; + request.option = option; + request.price = price; + request.accept_tip = accept_tip; + return request; +} + +bool DeskActions::ticket_price(const ui::DeskState& observed, int price, + uint64_t& revision, std::string& error) { + TicketPriceRequest request; + request.identity.manager_slot = observed.manager_slot; + request.identity.runtime_club = observed.runtime_club; + if (observed.runtime_club >= 0 && size_t(observed.runtime_club) < session_.state().club_ids.size()) + request.identity.stable_club_identity = int(session_.state().club_ids[size_t(observed.runtime_club)]); + request.identity.revision = observed.revision; + request.price = price; + return session_.dispatch_ticket_price(request, revision, error); +} + +bool LineupActions::apply(uint64_t& revision, const std::function& action) { + return apply_window(session_, revision, session_.lineup_checkpoint(), + [&](CareerSession::LineupCheckpoint before) { session_.restore_lineup_checkpoint(std::move(before)); }, action); +} + +bool LineupActions::lineup(const ui::LineupRequest& request, uint64_t& revision, std::string& error, + const std::function& acknowledge) { + return apply(revision, [&] { + if (!session_.dispatch_lineup(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +bool LineupActions::pitch(const ui::PitchRequest& request, uint64_t& revision, std::string& error, + const std::function& acknowledge) { + return apply(revision, [&] { + if (!session_.dispatch_pitch(request, revision, error)) return false; + if (acknowledge) acknowledge(); + return true; + }); +} + +bool LineupActions::pitch_swap(const ui::PitchRequest& request, uint64_t& revision, std::string& error) { + return apply(revision, [&] { return session_.dispatch_pitch_swap(request, revision, error); }); +} + +bool LineupActions::order(const ui::LineupState& observed, const ui::LineupPlayer& player, + int aspect, int value, uint64_t& revision) { + return apply(revision, [&] { + if (observed.revision != revision || !set_player_order_source(session_.state(), observed.manager_slot, + observed.runtime_club, player.row, player.player_id, aspect, value)) return false; + ++revision; + return true; + }); +} + +LineupActions::PairTarget LineupActions::pair_target(const ui::PitchRequest& request, int second_row) const { + auto preview = session_.state(); + if (!move_pitch_player_source(preview, 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)) return PairTarget::invalid; + const size_t board = size_t(request.manager_slot) * 0x840; + return preview.tactics.at(board + size_t(request.row) * 0x58 + 0x3f) == second_row && + preview.tactics.at(board + size_t(second_row) * 0x58 + 0x3f) == request.row + ? PairTarget::requested : PairTarget::other_pair; +} + +ui::LineupRequest LineupActions::prepare(const ui::LineupState& observed) { + ui::LineupRequest request; + request.kind = ui::LineupRequestKind::prepare_lineup; + request.manager_slot = observed.manager_slot; + request.runtime_club = observed.runtime_club; + request.revision = observed.revision; + return request; +} + +ui::LineupRequest LineupActions::swap(const ui::LineupState& observed, + const ui::LineupPlayer& first, const ui::LineupPlayer& second) { + auto request = prepare(observed); + request.kind = ui::LineupRequestKind::swap_players; + request.first_row = first.row; request.second_row = second.row; + request.first_player = first.player_id; request.second_player = second.player_id; + request.first_slot = first.slot; request.second_slot = second.slot; + return request; +} + +ui::PitchRequest LineupActions::bind_pitch(const ui::PreparationState& observed, ui::PitchRequestKind kind) { + if (!observed.pitch || !observed.pitch->indoor.has_value()) + throw FormatError("pitch: missing observed live mode"); + ui::PitchRequest request; + request.kind = kind; + request.manager_slot = observed.lineup.manager_slot; + request.runtime_club = observed.lineup.runtime_club; + request.revision = observed.lineup.revision; + request.indoor = observed.pitch->indoor.value(); + return request; +} + +ui::PitchRequest LineupActions::swap_pitch(const ui::PreparationState& observed, + const ui::LineupPlayer& first, const ui::LineupPlayer& second) { + auto request = bind_pitch(observed, ui::PitchRequestKind::swap_players); + request.row = first.row; request.player_id = first.player_id; request.slot = first.slot; + request.old_depth = int8_t(first.board[0x41]); request.old_lane = int8_t(first.board[0x42]); + request.second_row = second.row; request.second_player = second.player_id; request.second_slot = second.slot; + return request; +} + +ui::PitchRequest LineupActions::page(const ui::PreparationState& observed) { + auto request = bind_pitch(observed, ui::PitchRequestKind::select_pitch_page); + request.expected_mode = uint8_t(observed.pitch->mode); + request.expected_display_word = observed.pitch->native_display_word; + request.expected_set_piece_values = observed.pitch->set_piece_takers; + request.expected_set_piece_signature = observed.pitch->set_piece_signature; + request.page_control = 1; + request.new_display_word = uint16_t(request.expected_display_word ^ 0x000c); + return request; +} + +ui::PitchRequest LineupActions::formation(const ui::PreparationState& observed, + ui::PitchRequestKind kind, int slot) { + auto request = bind_pitch(observed, kind); + request.old_weights = request.new_weights = observed.pitch->automatic_weights; + request.formation = slot; + if (kind == ui::PitchRequestKind::save_formation) { + for (size_t row = 0; row < 11; ++row) { + const auto& player = observed.lineup.players.at(row); + request.formation_positions[row] = player.board[0x41]; + request.formation_positions[11 + row] = player.board[0x42]; + } + } + return request; +} + +ui::PitchRequest LineupActions::move(const ui::PreparationState& observed, const ui::LineupPlayer& player, + int depth, int lane) { + auto request = bind_pitch(observed, ui::PitchRequestKind::move_player); + request.old_weights = request.new_weights = observed.pitch->automatic_weights; + request.row = player.row; request.player_id = player.player_id; request.slot = player.slot; + request.old_depth = int8_t(player.board[0x41]); request.old_lane = int8_t(player.board[0x42]); + request.new_depth = depth; request.new_lane = lane; + return request; +} + +ui::PitchRequest LineupActions::weight(const ui::PreparationState& observed, int index) { + if (index < 0 || index > 2) throw FormatError("pitch: invalid automatic weight index"); + auto request = bind_pitch(observed, ui::PitchRequestKind::set_automatic_weight); + request.old_weights = request.new_weights = observed.pitch->automatic_weights; + request.weight_index = index; + const int shift = 2 * index; + const int next = (((request.old_weights >> shift) & 3) + 1) & 3; + request.new_weights = uint8_t((request.old_weights & ~(3 << shift)) | (next << shift)); + return request; +} + +} // namespace bmh::app diff --git a/src/app/window_actions.hpp b/src/app/window_actions.hpp new file mode 100644 index 0000000..830e11f --- /dev/null +++ b/src/app/window_actions.hpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "app/career_session.hpp" + +namespace bmh::app { + +// Shared application boundary for Table, Pairings and Strengths. The callback +// includes the frontend's acknowledgement; false or an exception rolls back. +class LeagueFamilyActions { +public: + explicit LeagueFamilyActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + std::optional open_pairings(const ui::DeskState& observed, + uint64_t& revision, std::string& error); + std::optional pairings( + const ui::LeaguePairingsIdentity& observed, LeaguePairingsAction, int value, + uint64_t& revision, std::string& error); + static ui::DeskRequest pairings_entry(const ui::StrengthsIdentity&, uint64_t revision); + static ui::LeaguePairingsRequest pairings_selection(const ui::LeaguePairingsIdentity&, int league); + static ui::StrengthsRequest strengths_entry(const ui::StrengthsRequest&, const ui::StrengthsIdentity&); +private: + CareerSession& session_; +}; + +// Market, quote and outgoing editor share this boundary, including frontend +// acknowledgement and the suspended poaching attempt behind an offer owner. +class TransferActions { +public: + explicit TransferActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + std::string rejection(const ui::TransferMarketRequest&, uint64_t revision, + HumanBuyerMarketEntryPolicy) const; + struct MarketDispatch { TransferActionResult action; bool changed = false; }; + using MarketAccept = std::function; + using OfferAccept = std::function; + using PreviewAccept = std::function; + std::optional market(const ui::TransferMarketRequest&, const HumanBuyerSaleHooks&, + uint64_t& revision, std::string& error, + HumanBuyerMarketEntryPolicy = HumanBuyerMarketEntryPolicy::normal_interactive, + const MarketAccept& = {}); + std::optional open_offer(const ui::TransferMarketRequest&, + uint64_t& revision, std::string& error, const OfferAccept& = {}); + std::optional preview(const ui::TransferMarketRequest&, + uint64_t& revision, std::string& error, const PreviewAccept& = {}); + std::optional offer(const ui::OutgoingTransferRequest&, + const HumanBuyerSaleHooks&, uint64_t& revision, std::string& error, + const TransferOfferTeamInfoPresenter& = {}, const TransferOfferPlayerInfoPresenter& = {}, + const OfferAccept& = {}); + std::optional poach(int manager, int squad_slot, + uint64_t& revision, std::string& error); + static ui::TransferMarketRequest listing(const ui::TransferMarketState&, + const ui::TransferMarketSquadItem&, bool loan); + static ui::TransferMarketRequest opening(const ui::TransferMarketState&, + const ui::TransferMarketItem&, bool loan); + static ui::OutgoingTransferRequest editor(const ui::OutgoingTransferEditorState&, + ui::OutgoingTransferRequestKind, ui::OutgoingTransferField, uint32_t value); +private: + CareerSession& session_; +}; + +class BankActions { +public: + explicit BankActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + bool dispatch(const ui::BankRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + static ui::BankRequest savings(const ui::BankState&, int32_t amount); + static ui::BankRequest investment(const ui::BankState&, ui::BankRequestKind, int asset, int count = 0); + static ui::BankRequest credit(const ui::BankState&, const BankCreditContext&, + const BankCreditDraft&, bool accept_fees, int counterparty); +private: + static ui::BankRequest bind(const ui::BankState&, ui::BankRequestKind); + CareerSession& session_; +}; + +class StadiumActions { +public: + explicit StadiumActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + bool dispatch(const ui::StadiumRequest&, uint64_t& revision, std::string& error, + const ConstructionNoticeHook& = {}, const SeasonTicketCompensationNoticeHook& = {}, + const std::function& acknowledge = {}); + static ui::StadiumRequest request(const ui::StadiumState&, ui::StadiumRequestKind, + int object = -1, int option = -1, int32_t price = 0, bool accept_tip = false); +private: + CareerSession& session_; +}; + +class DeskActions { +public: + explicit DeskActions(CareerSession& session) : session_(session) {} + bool ticket_price(const ui::DeskState& observed, int price, uint64_t& revision, std::string& error); +private: + CareerSession& session_; +}; + +class LineupActions { +public: + explicit LineupActions(CareerSession& session) : session_(session) {} + bool apply(uint64_t& revision, const std::function& action); + bool lineup(const ui::LineupRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + bool pitch(const ui::PitchRequest&, uint64_t& revision, std::string& error, + const std::function& acknowledge = {}); + bool pitch_swap(const ui::PitchRequest&, uint64_t& revision, std::string& error); + bool order(const ui::LineupState&, const ui::LineupPlayer&, int aspect, int value, uint64_t& revision); + enum class PairTarget { invalid, other_pair, requested }; + PairTarget pair_target(const ui::PitchRequest&, int second_row) const; + static ui::LineupRequest prepare(const ui::LineupState&); + static ui::LineupRequest swap(const ui::LineupState&, const ui::LineupPlayer&, const ui::LineupPlayer&); + static ui::PitchRequest swap_pitch(const ui::PreparationState&, const ui::LineupPlayer&, const ui::LineupPlayer&); + static ui::PitchRequest page(const ui::PreparationState&); + static ui::PitchRequest formation(const ui::PreparationState&, ui::PitchRequestKind, int slot); + static ui::PitchRequest move(const ui::PreparationState&, const ui::LineupPlayer&, int depth, int lane); + static ui::PitchRequest weight(const ui::PreparationState&, int index); +private: + static ui::PitchRequest bind_pitch(const ui::PreparationState&, ui::PitchRequestKind); + CareerSession& session_; +}; + +} // namespace bmh::app diff --git a/src/audio/CMakeLists.txt b/src/audio/CMakeLists.txt new file mode 100644 index 0000000..cc20769 --- /dev/null +++ b/src/audio/CMakeLists.txt @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-only +add_library(openbmh_audio STATIC container.cpp playback.cpp semantic_cues.cpp music_fallback.cpp mixer.cpp + original.cpp third_party/nuked-opl3/opl3.c) +target_include_directories(openbmh_audio PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(openbmh_audio PUBLIC ${BMH_SDL_TARGET}) + +add_executable(openbmh_sound sound_driver.cpp) +target_link_libraries(openbmh_sound PRIVATE openbmh_audio bmhcore) + +add_executable(openbmh_original_audio_validation original_validation.cpp) +target_link_libraries(openbmh_original_audio_validation PRIVATE openbmh_audio bmhcore) +bmh_add_data_test(NAME openbmh_original_audio_validation COMMAND openbmh_original_audio_validation "${BMH_DATA}") +set_tests_properties(openbmh_original_audio_validation PROPERTIES + ENVIRONMENT "SDL_AUDIODRIVER=dummy;SDL_VIDEODRIVER=dummy") + +add_executable(openbmh_audio_validation validation.cpp) +target_link_libraries(openbmh_audio_validation PRIVATE openbmh_audio) +add_test(NAME openbmh_audio_validation COMMAND openbmh_audio_validation) +set_tests_properties(openbmh_audio_validation PROPERTIES ENVIRONMENT "SDL_AUDIODRIVER=dummy;SDL_VIDEODRIVER=dummy") + +# SDL.h renames main to SDL_main on Windows: the two programs need SDL2main for the entry point +if(TARGET SDL2::SDL2main) + target_link_libraries(openbmh_sound PRIVATE SDL2::SDL2main) + target_link_libraries(openbmh_audio_validation PRIVATE SDL2::SDL2main) + target_link_libraries(openbmh_original_audio_validation PRIVATE SDL2::SDL2main) +endif() diff --git a/src/audio/container.cpp b/src/audio/container.cpp new file mode 100644 index 0000000..31594fb --- /dev/null +++ b/src/audio/container.cpp @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "container.hpp" + +#include +#include + +namespace openbmh::audio { +namespace { +std::uint32_t read_le32(std::span bytes, std::size_t at) { + return static_cast(bytes[at]) | + (static_cast(bytes[at + 1]) << 8) | + (static_cast(bytes[at + 2]) << 16) | + (static_cast(bytes[at + 3]) << 24); +} +} + +bool parse_container(std::span bytes, Container& out, + std::string& error) { + out.chunks.clear(); + error.clear(); + if (bytes.size() < 16) { + error = "truncated FORM/ALPTRAUM header"; + return false; + } + if (bytes[0] != 'F' || bytes[1] != 'O' || bytes[2] != 'R' || bytes[3] != 'M') { + error = "missing FORM signature"; + return false; + } + if (std::string(bytes.begin() + 8, bytes.begin() + 16) != "ALPTRAUM") { + error = "unsupported FORM type (expected ALPTRAUM)"; + return false; + } + const auto declared = read_le32(bytes, 4); + if (declared != bytes.size() - 8 && declared != bytes.size()) { + error = "FORM length does not match either observed ALPTRAUM convention"; + return false; + } + // The only observed full-file-size header is S/2003's SEFX variant. Keep + // this exception tied to that exact, byte-verified layout; do not silently + // accept it for the SONG/TRCK/PART music containers. + const bool sefx_variant = declared == bytes.size() && bytes.size() == 65380 && + bytes[16] == 'H' && bytes[17] == 'E' && bytes[18] == 'D' && bytes[19] == 'R' && + bytes[32] == 'S' && bytes[33] == 'E' && bytes[34] == 'F' && bytes[35] == 'X'; + if (declared == bytes.size() && !sefx_variant) { + error = "full-file FORM length is only established for the 2003 SEFX variant"; + return false; + } + + std::size_t at = 16; + while (at < bytes.size()) { + if (bytes.size() - at < 8) { + error = "truncated chunk header"; + out.chunks.clear(); + return false; + } + const std::uint32_t size = read_le32(bytes, at + 4); + const std::size_t payload = at + 8; + if (size > bytes.size() - payload) { + error = "chunk payload exceeds container bounds"; + out.chunks.clear(); + return false; + } + out.chunks.push_back({std::string(bytes.begin() + at, bytes.begin() + at + 4), + payload, size}); + at = payload + size; + } + if (sefx_variant && (out.chunks.size() != 4 || out.chunks[0].id != "HEDR" || + out.chunks[1].id != "SEFX" || out.chunks[2].id != "INST" || + out.chunks[3].id != "SAMP" || out.chunks[0].payload_size != 8 || + out.chunks[1].payload_size != 212 || out.chunks[2].payload_size != 228 || + out.chunks[3].payload_size != 64884)) { + error = "full-file FORM length does not match the observed 2003 SEFX chunk layout"; + out.chunks.clear(); + return false; + } + if (sefx_variant) { + const auto& sefx = out.chunks[1]; + const auto payload = bytes.subspan(sefx.payload_offset, sefx.payload_size); + const std::size_t records = (payload.size() - 4) / 16; + if (payload[0] != 0 || payload[1] != 0 || payload[2] != 7 || payload[3] != 0 || + (payload.size() - 4) % 16 != 0 || records != 13) { + error = "2003 SEFX prefix or fixed-record table is malformed"; + out.chunks.clear(); + return false; + } + } + return true; +} + +bool decode_sample(std::span payload, std::size_t index, + PcmSample& out, std::string& error) { + out = {}; + error.clear(); + if (payload.size() < 4) { error = "truncated SAMP header"; return false; } + const std::size_t count = static_cast(payload[2]) | + (static_cast(payload[3]) << 8); + constexpr std::size_t kRecordSize = 16; + constexpr std::size_t kMaxSamples = 256; + if (count > kMaxSamples || count > (payload.size() - 4) / kRecordSize) { + error = "SAMP descriptor table exceeds payload bounds"; return false; + } + if (index >= count) { error = "sample index is outside the SAMP table"; return false; } + const std::size_t data_offset = 4 + count * kRecordSize; + const std::size_t record = 4 + index * kRecordSize; + const std::uint32_t start = static_cast(payload[record]) | + (static_cast(payload[record + 1]) << 8); + const std::uint32_t length = static_cast(payload[record + 2]) | + (static_cast(payload[record + 3]) << 8); + const std::uint32_t rate = static_cast(payload[record + 8]) | + (static_cast(payload[record + 9]) << 8); + const std::size_t data_size = payload.size() - data_offset; + if (length == 0 || start > data_size || length > data_size - start) { + error = "SAMP sample span exceeds sample payload"; return false; + } + if (rate < 4000 || rate > 48000) { + error = "unsupported SAMP sample rate"; return false; + } + out.sample_rate = rate; + out.mono.reserve(length); + const std::size_t first = data_offset + start; + for (std::size_t i = 0; i < length; ++i) { + out.mono.push_back(static_cast( + (static_cast(payload[first + i]) - 128) * 256)); + } + return true; +} + +bool decode_original_cue(std::span bytes, + std::uint8_t original_id, OriginalCue& out, + std::string& error) { + out = {}; + error.clear(); + if (original_id < 10 || original_id > 22) { + error = "original SFX ID is outside the observed 10..22 dispatch range"; + return false; + } + Container container; + if (!parse_container(bytes, container, error)) return false; + const auto declared_form = read_le32(bytes, 4); + if (bytes.size() != 65380 || declared_form != bytes.size() || container.chunks.size() != 4 || + container.chunks[0].id != "HEDR" || container.chunks[0].payload_size != 8 || + container.chunks[1].id != "SEFX" || container.chunks[1].payload_size != 212 || + container.chunks[2].id != "INST" || container.chunks[2].payload_size != 228 || + container.chunks[3].id != "SAMP" || container.chunks[3].payload_size != 64884) { + error = "original cue decoding is limited to the exact observed 2003 SEFX bank"; + return false; + } + const auto find = [&container](const char* id) -> const Chunk* { + const auto it = std::find_if(container.chunks.begin(), container.chunks.end(), + [id](const Chunk& c) { return c.id == id; }); + return it == container.chunks.end() ? nullptr : &*it; + }; + const Chunk* sefx = find("SEFX"); + const Chunk* samp = find("SAMP"); + if (!sefx || !samp) { + error = "original cue needs both SEFX and SAMP chunks"; + return false; + } + const auto sefx_data = bytes.subspan(sefx->payload_offset, sefx->payload_size); + constexpr std::size_t kPrefixBytes = 4; + constexpr std::size_t kRecordBytes = 16; + constexpr std::size_t kRecordCount = 13; + if (sefx_data.size() != kPrefixBytes + kRecordBytes * kRecordCount || + sefx_data[0] != 0 || sefx_data[1] != 0 || sefx_data[2] != 7 || sefx_data[3] != 0) { + error = "unsupported SEFX layout for original-cue lookup"; + return false; + } + // PauseMusic subtracts 10 before dispatch. Subspan indexes that + // SEFX record; its type-9 records address the loaded sample slots 16..21. + const std::size_t sefx_index = static_cast(original_id - 10); + const std::size_t record = kPrefixBytes + sefx_index * kRecordBytes; + const std::uint8_t sample_slot = sefx_data[record]; + if (sefx_data[record + 1] != 9 || sample_slot < 16 || sample_slot > 21) { + error = "original cue is not a directly decoded type-9 SAMP effect"; + return false; + } + const auto sample_index = static_cast(sample_slot - 16); + const auto samp_data = bytes.subspan(samp->payload_offset, samp->payload_size); + if (samp_data[2] != 6 || samp_data[3] != 0) { + error = "2003 SAMP table does not have the six observed entries"; + return false; + } + if (!decode_sample(samp_data, sample_index, out.pcm, error)) return false; + out.original_id = original_id; + out.sefx_index = static_cast(sefx_index); + out.sample_index = static_cast(sample_index); + return true; +} + +} // namespace openbmh::audio diff --git a/src/audio/container.hpp b/src/audio/container.hpp new file mode 100644 index 0000000..c0fa09b --- /dev/null +++ b/src/audio/container.hpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +namespace openbmh::audio { + +struct Chunk { + std::string id; + std::size_t payload_offset{}; + std::size_t payload_size{}; +}; + +struct Container { std::vector chunks; }; + +struct PcmSample { + std::uint32_t sample_rate{}; + std::vector mono; +}; + +struct OriginalCue { + std::uint8_t original_id{}; + std::uint8_t sefx_index{}; + std::uint8_t sample_index{}; + PcmSample pcm; +}; + +// Parses the observed FORM/ALPTRAUM wrapper. Chunk lengths are little endian; +// chunks are adjacent with no alignment byte. Payloads remain in the caller's buffer. +bool parse_container(std::span bytes, Container& out, + std::string& error); + +// Converts one bounded SAMP sample span from unsigned 8-bit DMA data to signed +// 16-bit mono PCM, using the rate stored in its 16-byte descriptor. +bool decode_sample(std::span samp_payload, std::size_t index, + PcmSample& out, std::string& error); + +// Resolves only the observed PCM-backed SEFX effects (original IDs 17..22). +// IDs 10..16 use the separate instrument path and remain unsupported here. +bool decode_original_cue(std::span container_bytes, + std::uint8_t original_id, OriginalCue& out, + std::string& error); + +} // namespace openbmh::audio diff --git a/src/audio/mixer.cpp b/src/audio/mixer.cpp new file mode 100644 index 0000000..dc3ac4f --- /dev/null +++ b/src/audio/mixer.cpp @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "mixer.hpp" + +#include +#include +#include + +namespace openbmh::audio { +namespace { +constexpr std::size_t kMaxLoopBytes = 2U * 1024U * 1024U; +constexpr std::size_t kMaxVoiceBytes = 2U * 1024U * 1024U; +constexpr std::size_t kMaxPerVoiceBytes = kMaxVoiceBytes / 8; + +bool convert_rate(std::span input, std::uint32_t source_rate, + std::uint32_t output_rate, std::size_t byte_limit, + std::vector& output, std::string& error) { + output.clear(); + if (input.empty() || source_rate < 4000 || source_rate > 192000 || + output_rate < 4000 || output_rate > 192000) { + error = "invalid PCM rate or empty input"; + return false; + } + if (input.size() > (std::numeric_limits::max() - source_rate / 2) / + output_rate) { + error = "PCM input size overflows sample-rate conversion"; + return false; + } + const auto count64 = (static_cast(input.size()) * output_rate + source_rate / 2) / + source_rate; + if (!count64 || count64 > byte_limit / sizeof(std::int16_t) || + count64 > std::numeric_limits::max()) { + error = "converted PCM exceeds mixer buffer limit"; + return false; + } + const auto count = static_cast(count64); + output.resize(count); + for (std::size_t i = 0; i < count; ++i) { + const auto source_index = std::min(input.size() - 1, + static_cast((static_cast(i) * source_rate + output_rate / 2) / + output_rate)); + output[i] = input[source_index]; + } + error.clear(); + return true; +} +} + +bool Mixer::start_music_loop(const PcmSample& loop, std::uint32_t output_rate, + std::string& error) { + std::vector converted; + if (!convert_rate(loop.mono, loop.sample_rate, output_rate, kMaxLoopBytes, converted, error)) + return false; + music_ = std::move(converted); + music_cursor_ = 0; + error.clear(); + return true; +} + +void Mixer::stop_music() noexcept { + music_.clear(); + music_cursor_ = 0; +} + +bool Mixer::add_voice(std::span samples, std::uint32_t sample_rate, + std::uint32_t output_rate, std::string& error) { + std::vector converted; + if (!convert_rate(samples, sample_rate, output_rate, kMaxPerVoiceBytes, converted, error)) + return false; + if (converted.size() * sizeof(std::int16_t) > kMaxVoiceBytes - voice_bytes_) { + error = "combined active cue voices exceed mixer buffer limit"; + return false; + } + const auto free_voice = std::find_if(voices_.begin(), voices_.end(), + [](const Voice& voice) { return voice.cursor >= voice.samples.size(); }); + if (free_voice == voices_.end()) { + error = "all fixed mixer cue voices are active"; + return false; + } + voice_bytes_ += converted.size() * sizeof(std::int16_t); + free_voice->samples = std::move(converted); + free_voice->cursor = 0; + error.clear(); + return true; +} + +void Mixer::clear() noexcept { + stop_music(); + for (auto& voice : voices_) { + voice.samples.clear(); + voice.cursor = 0; + } + voice_bytes_ = 0; +} + +bool Mixer::active() const noexcept { + return !music_.empty() || active_voices() != 0; +} + +std::size_t Mixer::active_voices() const noexcept { + return static_cast(std::count_if(voices_.begin(), voices_.end(), + [](const Voice& voice) { return voice.cursor < voice.samples.size(); })); +} + +bool Mixer::mix_block(std::span output, float volume) noexcept { + if (!active() || output.empty() || !std::isfinite(volume)) return false; + const float bounded_volume = std::clamp(volume, 0.0F, 1.0F); + for (auto& dst : output) { + std::int32_t mixed = 0; + if (!music_.empty()) { + mixed += music_[music_cursor_++]; + if (music_cursor_ == music_.size()) music_cursor_ = 0; + } + for (auto& voice : voices_) { + if (voice.cursor < voice.samples.size()) { + mixed += voice.samples[voice.cursor++]; + if (voice.cursor == voice.samples.size()) { + voice_bytes_ -= voice.samples.size() * sizeof(std::int16_t); + voice.samples.clear(); + voice.cursor = 0; + } + } + } + const auto scaled = std::lround(static_cast(mixed) * bounded_volume); + dst = static_cast(std::clamp(scaled, -32768, 32767)); + } + return true; +} + +} // namespace openbmh::audio diff --git a/src/audio/mixer.hpp b/src/audio/mixer.hpp new file mode 100644 index 0000000..c3d45c6 --- /dev/null +++ b/src/audio/mixer.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "container.hpp" + +#include +#include +#include +#include +#include +#include + +namespace openbmh::audio { + +// Small allocation-bounded PCM mixer. Setup/add_voice may allocate; mix_block +// only reads its prepared buffers and writes into caller-owned storage. +class Mixer { +public: + bool start_music_loop(const PcmSample& loop, std::uint32_t output_rate, + std::string& error); + void stop_music() noexcept; + bool add_voice(std::span samples, std::uint32_t sample_rate, + std::uint32_t output_rate, std::string& error); + void clear() noexcept; + bool active() const noexcept; + bool has_music() const noexcept { return !music_.empty(); } + std::size_t active_voices() const noexcept; + bool mix_block(std::span output, float volume) noexcept; + +private: + struct Voice { std::vector samples; std::size_t cursor{}; }; + std::vector music_; + std::size_t music_cursor_{}; + std::array voices_{}; + std::size_t voice_bytes_{}; +}; + +} // namespace openbmh::audio diff --git a/src/audio/music_fallback.cpp b/src/audio/music_fallback.cpp new file mode 100644 index 0000000..bb65e65 --- /dev/null +++ b/src/audio/music_fallback.cpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "music_fallback.hpp" + +#include +#include +#include +#include + +namespace openbmh::audio { +namespace { +constexpr std::uint32_t kRate = 22050; +constexpr std::uint32_t kBeatsPerMinute = 108; +constexpr std::uint32_t kBars = 8; +constexpr std::uint32_t kBeatsPerBar = 4; +constexpr double kPi = 3.14159265358979323846; +constexpr std::size_t kLoopFrames = + static_cast(kRate) * 60 * kBars * kBeatsPerBar / kBeatsPerMinute; + +constexpr std::array kBassMidi{43, 38, 40, 36}; // G2, D2, E2, C2 +constexpr std::array, 4> kChordMidi{{ + {{55, 59, 62}}, // G major + {{50, 54, 57}}, // D major + {{52, 55, 59}}, // E minor + {{48, 52, 55}}, // C major +}}; +constexpr std::array kLeadMidi{ + 67, 71, 74, 71, 69, 74, 78, 74, + 71, 76, 79, 76, 67, 72, 76, 72, +}; + +double midi_hz(int midi) { + return 440.0 * std::pow(2.0, static_cast(midi - 69) / 12.0); +} + +std::int16_t clamp_sample(double value) { + const auto rounded = static_cast(std::lround(value)); + return static_cast(std::clamp(rounded, -32768L, 32767L)); +} +} + +bool synthesize_matchday_music_loop(PcmSample& out, std::string& error) { + out = {}; + error.clear(); + out.sample_rate = kRate; + out.mono.resize(kLoopFrames); + + const double samples_per_beat = static_cast(kRate) * 60.0 / kBeatsPerMinute; + const std::size_t lead_gate = static_cast(samples_per_beat * 0.72); + const std::size_t fade_frames = kRate / 200; // 5 ms endpoint ramp for a clean loop seam. + + for (std::size_t frame = 0; frame < kLoopFrames; ++frame) { + const double beat_position = static_cast(frame) / samples_per_beat; + const auto bar = static_cast(beat_position / kBeatsPerBar) % kBars; + const double beat_fraction = std::fmod(beat_position, 1.0); + const double bar_fraction = std::fmod(beat_position / kBeatsPerBar, 1.0); + + const double bass_phase = 2.0 * kPi * midi_hz(kBassMidi[bar % 4]) * frame / kRate; + const double bass_envelope = 0.78 + 0.22 * std::cos(kPi * beat_fraction); + double mixed = 2600.0 * bass_envelope * + (std::sin(bass_phase) + 0.18 * std::sin(2.0 * bass_phase)); + + const auto& chord = kChordMidi[bar % 4]; + const double pad_envelope = 0.58 + 0.16 * std::cos(2.0 * kPi * bar_fraction); + for (std::size_t note = 0; note < chord.size(); ++note) { + const double phase = 2.0 * kPi * midi_hz(chord[note]) * frame / kRate; + mixed += 1350.0 * pad_envelope * + (std::sin(phase) + 0.12 * std::sin(2.0 * phase)); + } + + // A short eighth-note lead gives the loop a recognizable repeated motif. + const auto step = static_cast(beat_position * 2.0) % kLeadMidi.size(); + const double step_fraction = std::fmod(beat_position * 2.0, 1.0); + const auto lead_elapsed = static_cast(step_fraction * samples_per_beat / 2.0); + if (lead_elapsed < lead_gate) { + const double phase = 2.0 * kPi * midi_hz(kLeadMidi[step]) * lead_elapsed / kRate; + const double attack = std::min(1.0, static_cast(lead_elapsed) / (kRate / 160)); + const double release = std::min(1.0, + static_cast(lead_gate - lead_elapsed) / (kRate / 35)); + const double envelope = std::min(attack, release); + mixed += 3600.0 * envelope * + (std::sin(phase) + 0.22 * std::sin(2.0 * phase)); + } + + const auto edge = std::min(frame, kLoopFrames - 1 - frame); + const double seam_envelope = std::min(1.0, static_cast(edge) / fade_frames); + out.mono[frame] = clamp_sample(mixed * seam_envelope); + } + return true; +} + +} // namespace openbmh::audio diff --git a/src/audio/music_fallback.hpp b/src/audio/music_fallback.hpp new file mode 100644 index 0000000..5c4d0e2 --- /dev/null +++ b/src/audio/music_fallback.hpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "container.hpp" + +#include + +namespace openbmh::audio { + +// Builds an explicitly synthetic, deterministic 8-bar matchday loop. This is +// presentation fallback material, not decoded original music or a Sound ID. +bool synthesize_matchday_music_loop(PcmSample& out, std::string& error); + +} // namespace openbmh::audio diff --git a/src/audio/original.cpp b/src/audio/original.cpp new file mode 100644 index 0000000..41fff6a --- /dev/null +++ b/src/audio/original.cpp @@ -0,0 +1,468 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "original.hpp" +#include "container.hpp" +#include "third_party/nuked-opl3/opl3.h" + +#include +#include +#include + +namespace openbmh::audio { +namespace { +using Bytes = std::span; +std::uint16_t word(Bytes b, std::size_t at) { + if (at > b.size() || b.size() - at < 2) throw std::runtime_error("truncated audio word"); + return std::uint16_t(b[at] | (unsigned(b[at + 1]) << 8)); +} +std::uint32_t dword(Bytes b, std::size_t at) { + return std::uint32_t(word(b, at)) | (std::uint32_t(word(b, at + 2)) << 16); +} +Bytes chunk(Bytes bytes, const Container& c, const char* name) { + const Chunk* found = nullptr; + for (const auto& p : c.chunks) if (p.id == name) { + if (found) throw std::runtime_error("duplicate Original audio chunk"); + found = &p; + } + if (!found) throw std::runtime_error(std::string("missing Original audio chunk ") + name); + return bytes.subspan(found->payload_offset, found->payload_size); +} +bool room(Bytes b, std::size_t at, std::size_t n) noexcept { + return at <= b.size() && n <= b.size() - at; +} +} + +struct OriginalSynth::State { + struct Sample { Bytes data, loop; std::uint8_t time_constant{}; }; + struct Bank { + std::vector> instruments; + std::vector samples; + }; + struct Song : Bank { + Bytes tracks, parts; + std::array start{}, loop{}; + std::vector patterns; + std::uint16_t tempo{}, end{}, repeat{}; + }; + struct Track { + std::size_t next{}, loop{}, cursor{}; + std::uint8_t tick{}, instrument{}, volume{}, transpose{}, first{}, end{}, channel{}; + bool active{}; + }; + struct Channel { + std::uint8_t duration{}, instrument{255}, level{255}, high{}, reserved{}, release{255}, priority{}; + std::uint8_t modulator{}, carrier{}; + }; + OriginalAssets assets; + std::array songs; + Bank effects; + std::array, 13> sfx{}; + std::array tracks{}; + std::array channels{}; + opl3_chip chip{}; + OriginalAudioOptions options; + OriginalAudioStats stats; + std::uint32_t rate{}; + std::uint64_t pit_phase{}, dma_phase{}; + Bytes dma; + std::size_t dma_cursor{}; + std::uint8_t dma_constant{}, dma_priority{}, dma_slot{}, ambient_slot{255}; + bool dma_loop{}, dma_effect{}, dry{}; + unsigned tempo_tick{}; + std::function register_observer; + std::function sample_observer; + + void write(std::uint8_t reg, std::uint8_t value) noexcept { + if (dry) return; + ++stats.register_writes; + OPL3_WriteRegBuffered(&chip, reg, value); + if (register_observer) register_observer(reg, value); + } + void reset_chip() noexcept { + OPL3_Reset(&chip, rate); + for (const auto [r, v] : std::array, 7>{{ + {1, 0x20}, {8, 0}, {2, 0}, {3, 0}, {4, 0x60}, {4, 0x80}, {0xbd, 0}}}) write(r, v); + } + static Bank read_bank(Bytes raw, const Container& container) { + Bank bank; + const auto inst = chunk(raw, container, "INST"); + const auto count = word(inst, 2); + if (word(inst, 0) != 0 || count > 128 || inst.size() != 4u + 32u * count) + throw std::runtime_error("invalid Original INST table"); + bank.instruments.resize(count); + for (unsigned i = 0; i < count; ++i) + std::copy_n(inst.begin() + 4 + i * 32, 32, bank.instruments[i].begin()); + const auto samp = chunk(raw, container, "SAMP"); + const auto n = word(samp, 2); + if (word(samp, 0) != 0 || n > 16 || !room(samp, 4, std::size_t(n) * 16)) + throw std::runtime_error("invalid Original SAMP table"); + const auto data = samp.subspan(4 + n * 16); + for (unsigned i = 0; i < n; ++i) { + const auto desc = samp.subspan(4 + i * 16, 16); + const auto begin = word(desc, 0), length = word(desc, 2); + if (!length || !room(data, begin, length)) throw std::runtime_error("invalid Original sample span"); + Sample s{data.subspan(begin, length), {}, desc[11]}; + if (desc[10]) { + const auto start = word(desc, 4), size = word(desc, 6); + if (!size || !room(data, start, size)) throw std::runtime_error("invalid Original sample loop"); + s.loop = data.subspan(start, size); + } + bank.samples.push_back(s); + } + return bank; + } + bool parse(std::string& error) { + for (unsigned i = 0; i < 4; ++i) { + const Bytes raw = assets.containers[i]; + Container container; + if (!parse_container(raw, container, error)) return false; + const auto header = chunk(raw, container, "HEDR"); + if (header.size() != 8 || word(header, 0) != 1 || word(header, 2) != 0 || + word(header, 4) != 1 || word(header, 6) != 1) + throw std::runtime_error("unsupported Original sound driver variant"); + auto bank = read_bank(raw, container); + if (i == 3) { + effects = std::move(bank); + const auto fx = chunk(raw, container, "SEFX"); + if (fx.size() != 4 + sfx.size() * 16) throw std::runtime_error("invalid Original SEFX table"); + for (unsigned n = 0; n < sfx.size(); ++n) { + std::copy_n(fx.begin() + 4 + n * 16, 16, sfx[n].begin()); + const auto& f = sfx[n]; + if (f[1] == 9) { + if (f[0] < 16 || f[0] - 16 >= effects.samples.size()) + throw std::runtime_error("SEFX sample outside bank"); + } else if (f[1] >= 9 || !(f[0] & 128) || (f[0] & 127) >= effects.instruments.size() || + f[2] >= assets.tables.frequencies.size() || f[4] > 63) + throw std::runtime_error("SEFX instrument, channel, note or level outside bank"); + } + continue; + } + Song& song = songs[i]; + static_cast(song) = std::move(bank); + const auto info = chunk(raw, container, "SONG"); + if (info.size() != 10 || word(info, 0) != 0) throw std::runtime_error("invalid Original SONG header"); + song.tempo = word(info, 4); song.end = word(info, 6); song.repeat = word(info, 8); + if (!song.tempo || song.tempo > 1024 || !song.end || song.end > 8192 || song.repeat > song.end) + throw std::runtime_error("invalid Original song timing"); + const auto tr = chunk(raw, container, "TRCK"); + if (word(tr, 0) != 0 || word(tr, 2) != 16 || tr.size() < 132) + throw std::runtime_error("invalid Original TRCK table"); + song.tracks = tr.subspan(132); + for (unsigned t = 0; t < 16; ++t) { + song.start[t] = dword(tr, 4 + 4 * t); song.loop[t] = dword(tr, 68 + 4 * t); + if (!room(song.tracks, song.start[t], 8) || !room(song.tracks, song.loop[t], 8)) + throw std::runtime_error("Original track pointer outside table"); + } + const auto part = chunk(raw, container, "PART"); + const auto patterns = word(part, 2); + if (word(part, 0) != 0 || !patterns || patterns > 256 || !room(part, 4, patterns * 4)) + throw std::runtime_error("invalid Original PART table"); + song.parts = part.subspan(4 + patterns * 4); + for (unsigned p = 0; p < patterns; ++p) { + const auto start = dword(part, 4 + p * 4); + if (start >= song.parts.size()) throw std::runtime_error("Original pattern pointer outside table"); + song.patterns.push_back(start); + } + } + return true; + } + void fail() noexcept { stats.failed = true; stats.playing = false; dma = {}; } + void level(unsigned c, std::uint8_t value) noexcept { + if (c >= 9 || value > 63) { fail(); return; } + auto& ch = channels[c]; + if (ch.level == value) return; + ch.level = value; + // Uint8T5's 64x64 table, generated there at runtime. + const auto scale = [value](std::uint8_t tl) { + return std::uint8_t((tl & 0xc0) | (63 - (unsigned(value) * (64 - (tl & 63)) >> 6))); + }; + write(assets.tables.operators[c] + 0x20, scale(ch.modulator)); + write(assets.tables.operators[c] + 0x23, scale(ch.carrier)); + } + void instrument(unsigned c, std::uint8_t id) noexcept { + if (c >= 9) { fail(); return; } + const Bank& bank = id & 128 ? effects : songs[stats.song]; + if ((id & 127) >= bank.instruments.size()) { fail(); return; } + auto& ch = channels[c]; ch.instrument = id; + const auto& in = bank.instruments[id & 127]; + ch.modulator = in[2]; ch.carrier = in[3]; ch.level = 255; + const unsigned op = assets.tables.operators[c]; + write(op, in[0]); write(op + 3, in[1]); + write(op + 0x40, in[4]); write(op + 0x43, in[5]); + write(op + 0x60, in[6]); write(op + 0x63, in[7]); + write(op + 0xc0, in[8]); write(op + 0xc3, in[9]); + write(0xc0 + c, in[10]); + } + void note(unsigned c, unsigned pitch, std::uint8_t volume) noexcept { + if (c >= 9 || pitch >= assets.tables.frequencies.size()) { fail(); return; } + write(0xb0 + c, 0); + level(c, volume); + const auto frequency = assets.tables.frequencies[pitch]; + channels[c].high = std::uint8_t(frequency >> 8); + write(0xa0 + c, std::uint8_t(frequency)); write(0xb0 + c, std::uint8_t(frequency >> 8)); + } + void start_sample(std::uint8_t slot, bool is_effect, std::uint8_t priority = 0) noexcept { + const Bank* bank = nullptr; + unsigned index = slot; + if (slot >= 16) { bank = &effects; index -= 16; } + else if (stats.song < 3) bank = &songs[stats.song]; + if (!bank || index >= bank->samples.size()) { fail(); return; } + const auto& s = bank->samples[index]; + dma = s.loop.empty() ? s.data : s.loop; + dma_loop = !s.loop.empty(); dma_cursor = 0; dma_phase = 0; + dma_constant = s.time_constant; dma_effect = is_effect; dma_priority = priority; dma_slot = slot; + if (dma_loop && is_effect) ambient_slot = slot; + if (!dry) { ++stats.sample_starts; if (sample_observer) sample_observer(slot); } + } + void stop_effects() noexcept { + for (unsigned c = 0; c < 9; ++c) if (channels[c].reserved) { + level(c, 0); channels[c].reserved = 0; + } + dma = {}; dma_effect = false; ambient_slot = 255; stats.ambient = false; + } + void pause_music() noexcept { + for (unsigned c = 0; c < 9; ++c) level(c, 0); + stats.playing = false; + dma = {}; + } + void start_song(unsigned i, bool restart = false) noexcept { + if (i >= 3) return; + if (stats.song == i && !restart) { stats.playing = options.music; return; } + pause_music(); stop_effects(); + // Effect resets only OriginalRuntimeField(duration)=0, a5540(instrument)=FF, + // a5544(level)=FF and a5546(reserved)=0 at stride16. The cached high + // frequency byte, release/priority and instrument levels survive. + // Clearing high changes the first pending key-off after a song switch. + for (auto& c : channels) { + c.duration = 0; c.instrument = 255; c.level = 255; c.reserved = 0; + } + stats.song = i; stats.bar = 0; stats.step = 0; tempo_tick = 0; + for (unsigned t = 0; t < 16; ++t) { + tracks[t].active = false; tracks[t].next = songs[i].start[t]; tracks[t].loop = songs[i].loop[t]; + } + stats.playing = options.music; + } + bool effect(std::uint8_t id) noexcept { + if (id < 10 || id > 22 || !options.effects || (id <= 15 && !options.clicks)) return false; + const auto& f = sfx[id - 10]; + if (f[1] == 9) { + if (dma_effect && !dma.empty() && f[3] < dma_priority) return true; + start_sample(f[0], true, f[3]); + } else { + auto& c = channels[f[1]]; + if (c.reserved && f[3] < c.priority) return true; + c.reserved = f[5]; c.release = f[6]; c.priority = f[3]; + instrument(f[1], f[0]); note(f[1], f[2], f[4]); + } + return !stats.failed; + } + std::uint8_t song_level(std::uint8_t value) noexcept { + // Source OriginalRuntimeField2=0x3f80 selects master127 in the 128x128 table. + if (value > 127) { fail(); return 0; } + return std::uint8_t((127u * (unsigned(value) + 1) >> 7) >> 1); + } + void music_step() noexcept { + if (!stats.playing || stats.failed) return; + const auto& song = songs[stats.song]; + if (stats.step == 0) { + if (stats.bar == song.end) { + if (song.end == song.repeat) { stats.playing = false; return; } + for (auto& t : tracks) t.next = t.loop; + stats.bar = song.repeat; + } + for (auto& t : tracks) { + if (!room(song.tracks, t.next, 8)) { fail(); return; } + const auto row = song.tracks.subspan(t.next, 8); + const auto bar = unsigned(row[0]) | (unsigned(row[1]) << 8); + if (bar != stats.bar) continue; + t.active = true; t.tick = 0; + if (row[2] != 255) t.instrument = row[2]; + if (row[3] != 255) t.volume = row[3]; + t.transpose = row[4]; t.first = row[6]; t.channel = t.first; + t.end = std::uint8_t(t.first + row[7]); + if (row[5] >= song.patterns.size() || (unsigned(&t - tracks.data()) != 9 && + (t.first >= 9 || t.end > 9 || t.end <= t.first))) { fail(); return; } + t.cursor = song.patterns[row[5]]; t.next += 8; + } + } + for (unsigned index = 0; index < tracks.size(); ++index) { + auto& t = tracks[index]; + if (!t.active) continue; + if (!room(song.parts, t.cursor, 1)) { fail(); return; } + const auto time = song.parts[t.cursor]; + if (time == 255) { t.active = false; continue; } + if (time == t.tick) { + if (!room(song.parts, t.cursor, 2)) { fail(); return; } + auto cursor = t.cursor + 2; + const auto code = song.parts[t.cursor + 1]; + unsigned count = 1; + if (code >= 128) { + if (code & 0x40) { + if (!room(song.parts, cursor, 1)) { fail(); return; } + t.instrument = song.parts[cursor++]; + } + if (code & 0x20) { + if (!room(song.parts, cursor, 1)) { fail(); return; } + t.volume = song.parts[cursor++]; + const auto value = song_level(t.volume); + for (unsigned c = t.first; c < t.end; ++c) level(c, value); + } + count = code & 7; + } + for (unsigned n = 0; n < count; ++n) { + if (!room(song.parts, cursor, code < 128 ? 1 : 2)) { fail(); return; } + const auto pitch = code < 128 ? code : song.parts[cursor++]; + const auto duration = song.parts[cursor++]; + if (index == 9 && code < 128) { + if (!dma_effect) start_sample(pitch, false); + } else if (t.channel < 9) { + auto& c = channels[t.channel]; + if (!c.reserved) { + if (c.instrument != t.instrument) instrument(t.channel, t.instrument); + c.duration = duration; + note(t.channel, std::uint8_t(pitch + t.transpose), song_level(t.volume)); + } + if (++t.channel == t.end) t.channel = t.first; + } else { fail(); return; } + } + t.cursor = cursor; + } + ++t.tick; + } + if (++stats.step == 16) { stats.step = 0; ++stats.bar; } + } + void tick() noexcept { + ++stats.ticks; + if (stats.failed) return; + // IRQ0 calls Write2 before Write/Write3. + for (unsigned n = 0; n < 9; ++n) { + auto& c = channels[n]; + if (c.reserved) { + --c.reserved; + if (c.release != 255 && --c.release == 255) write(0xb0 + n, c.high & 31); + } + } + if (!stats.playing) return; + if (tempo_tick == 0) { + music_step(); + for (unsigned n = 0; n < 9; ++n) { + auto& c = channels[n]; + if (c.duration != 255 && --c.duration == 255) write(0xb0 + n, c.high & 31); + } + } + if (++tempo_tick == songs[stats.song].tempo) tempo_tick = 0; + } +}; + +OriginalSynth::OriginalSynth() = default; +OriginalSynth::~OriginalSynth() = default; +bool OriginalSynth::load(OriginalAssets assets, std::uint32_t rate, std::string& error) { + error.clear(); + if (rate < 8000 || rate > 192000) { error = "invalid Original output rate"; return false; } + std::array used{}; + for (auto op : assets.tables.operators) { + const bool valid = (op >= 0x20 && op <= 0x22) || (op >= 0x28 && op <= 0x2a) || + (op >= 0x30 && op <= 0x32); + if (!valid || used[op]) { error = "invalid Original OPL operator table"; return false; } + used[op] = true; + } + for (auto frequency : assets.tables.frequencies) + if (!(frequency & 0x2000) || (frequency & 0xc000) || !(frequency & 0x3ff)) { + error = "invalid Original OPL note table"; return false; + } + try { + auto candidate = std::make_unique(); + candidate->assets = std::move(assets); candidate->rate = rate; + if (!candidate->parse(error)) return false; + // Interpret two full passes before making foreign data visible to the + // real-time callback. All runtime table accesses remain checked as well. + candidate->dry = true; + for (unsigned i = 0; i < 3; ++i) { + candidate->start_song(i, true); + const auto steps = unsigned(candidate->songs[i].end) * 32 + 1; + for (unsigned n = 0; n < steps && candidate->stats.playing; ++n) candidate->music_step(); + if (candidate->stats.failed) throw std::runtime_error("invalid Original track/pattern event"); + } + candidate->dry = false; candidate->stop_effects(); candidate->stats = {}; + candidate->tracks = {}; candidate->channels = {}; candidate->tempo_tick = 0; + candidate->reset_chip(); + state_ = std::move(candidate); + return true; + } catch (const std::exception& e) { error = e.what(); return false; } +} +bool OriginalSynth::ready() const noexcept { return state_ && !state_->stats.failed; } +void OriginalSynth::set_options(OriginalAudioOptions options) noexcept { + if (!state_) return; + auto& s = *state_; + if (s.options.music && !options.music && s.stats.playing) s.pause_music(); + const bool resume = !s.options.music && options.music && s.stats.song < 3 && !s.stats.ambient; + if (s.options.effects && !options.effects) s.stop_effects(); + s.options = options; + if (resume) s.stats.playing = true; +} +bool OriginalSynth::command(std::uint8_t id) noexcept { + if (!ready()) return false; + auto& s = *state_; + if (id < 3) { + // PauseMusic -> PauseMusic2 pauses music/effects before either loading a + // different song or PauseMusic3's same-song resume. Track cursors and + // retained instrument/volume stay intact on the latter path. + s.pause_music(); s.stop_effects(); s.start_song(id); return true; + } + if (id == 3) { + if (s.stats.ambient) return true; + s.pause_music(); s.stop_effects(); s.stats.ambient = true; + if (s.options.effects) s.effect(22); + return true; + } + if (id == 8) { stop(); return true; } + if (id < 10 || id > 22) return false; + // Source suppresses effects over the title song. The standalone direct + // effect entry remains available for isolated decoding and verification. + if (s.stats.song == 0) return true; + return s.effect(id); +} +bool OriginalSynth::effect(std::uint8_t id) noexcept { return ready() && state_->effect(id); } +void OriginalSynth::stop() noexcept { + if (!state_) return; + state_->pause_music(); state_->stop_effects(); +} +void OriginalSynth::tick() noexcept { if (state_) state_->tick(); } +void OriginalSynth::render(std::span output, float volume) noexcept { + std::fill(output.begin(), output.end(), 0); + if (!state_ || state_->stats.failed) return; + auto& s = *state_; + const auto gain = std::isfinite(volume) ? std::clamp(volume, 0.0F, 1.0F) : 0.0F; + for (auto& value : output) { + if (s.stats.failed) break; + s.pit_phase += 1193180; + const std::uint64_t period = std::uint64_t(s.rate) * 6554; + if (s.pit_phase >= period) { s.pit_phase -= period; s.tick(); } + std::int16_t pair[2]{}; + OPL3_GenerateResampled(&s.chip, pair); + std::int32_t mixed = (std::int32_t(pair[0]) + pair[1]) / 2; + if (!s.dma.empty()) { + mixed += (int(s.dma[s.dma_cursor]) - 128) * 256; + s.dma_phase += 1000000; + const auto divisor = std::uint64_t(s.rate) * (256 - unsigned(s.dma_constant)); + while (s.dma_phase >= divisor && !s.dma.empty()) { + s.dma_phase -= divisor; + if (++s.dma_cursor == s.dma.size()) { + if (s.dma_loop) s.dma_cursor = 0; + else if (s.ambient_slot != 255) s.start_sample(s.ambient_slot, true, 64); + else { s.dma = {}; s.dma_effect = false; } + } + } + } + value = std::int16_t(std::clamp(std::lround(mixed * gain), -32768, 32767)); + ++s.stats.frames; + } +} +OriginalAudioStats OriginalSynth::stats() const noexcept { return state_ ? state_->stats : OriginalAudioStats{}; } +void OriginalSynth::set_register_observer(std::function f) { + if (state_) state_->register_observer = std::move(f); +} +void OriginalSynth::set_sample_observer(std::function f) { + if (state_) state_->sample_observer = std::move(f); +} + +} // namespace openbmh::audio diff --git a/src/audio/original.hpp b/src/audio/original.hpp new file mode 100644 index 0000000..dc8a8ef --- /dev/null +++ b/src/audio/original.hpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace openbmh::audio { + +// Read from the user's executable by the application. Audio does not know the +// game state, filesystem layout, simulation clock, or random generators. +struct OriginalTables { + std::array frequencies{}; // Audio_OriginalAudioAssets_RuntimeField2, including key-on bits + std::array operators{}; // Audio_OriginalAudioAssets_RuntimeField, stride16 +}; +struct OriginalAssets { + std::array, 4> containers; // S/2000..2003 + OriginalTables tables; +}; +struct OriginalAudioOptions { + bool music = true; + bool effects = true; + bool clicks = true; +}; +struct OriginalAudioStats { + std::uint64_t ticks{}, register_writes{}, sample_starts{}, frames{}; + std::uint32_t bar{}, step{}, song = 255; + bool playing{}, ambient{}, failed{}; +}; + +// The Original MIDILINK sequencer and one Sound Blaster PCM channel. IRQ0 uses +// PIT divisor0x199a. SONG/TRCK/PART, OPL instruments, SFX priorities/lifetimes, +// note durations, sample interruption and the looping crowd are Source-derived. +// Loading owns/validates its inputs. render() allocates nothing and never blocks. +class OriginalSynth { +public: + OriginalSynth(); + ~OriginalSynth(); + OriginalSynth(const OriginalSynth&) = delete; + OriginalSynth& operator=(const OriginalSynth&) = delete; + bool load(OriginalAssets assets, std::uint32_t output_rate, std::string& error); + bool ready() const noexcept; + void set_options(OriginalAudioOptions options) noexcept; + // Source dispatch IDs:0 title,1 desk,2 intro,3 crowd,8 stop,10..22 effects. + bool command(std::uint8_t id) noexcept; + // Direct SFX entry, also used by the standalone driver/oracle. + bool effect(std::uint8_t id) noexcept; + void stop() noexcept; + void render(std::span output, float volume = 1.0F) noexcept; + OriginalAudioStats stats() const noexcept; + + // Deterministic hardware-independent probe: one Original IRQ0, not one game + // tick. Optional observers are installed only by offline validation tools. + void tick() noexcept; + void set_register_observer(std::function observer); + void set_sample_observer(std::function observer); +private: + struct State; + std::unique_ptr state_; +}; + +} // namespace openbmh::audio diff --git a/src/audio/original_validation.cpp b/src/audio/original_validation.cpp new file mode 100644 index 0000000..30bdda6 --- /dev/null +++ b/src/audio/original_validation.cpp @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "original.hpp" +#include "playback.hpp" +#include "container.hpp" +#include "formats/le.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace openbmh::audio; +constexpr std::uint64_t kFnvOffset = 14695981039346656037ull; +void require(bool value, const std::string& reason) { + if (!value) throw std::runtime_error(reason); +} +OriginalAssets assets_from(const std::filesystem::path& data) { + OriginalAssets assets; + const auto exe = bmh::load_le(data / "BMH.exe"); + for (unsigned i = 0; i < 4; ++i) + assets.containers[i] = bmh::read_file(data / "S" / std::to_string(2000 + i)); + for (unsigned i = 0; i < assets.tables.frequencies.size(); ++i) + assets.tables.frequencies[i] = exe.u16(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField2 + 2 * i); + for (unsigned i = 0; i < assets.tables.operators.size(); ++i) + assets.tables.operators[i] = exe.u8(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField + 16 * i); + return assets; +} +void load(OriginalSynth& synth, const OriginalAssets& assets) { + std::string error; + require(synth.load(assets, 22050, error), "load external Original audio: " + error); +} +struct TraceHash { + std::uint64_t count{}, hash = kFnvOffset; + void word(std::uint32_t value) { + for (unsigned shift = 0; shift < 32; shift += 8) + hash = (hash ^ ((value >> shift) & 255u)) * 1099511628211ull; + } + void sample(std::uint32_t tick, std::uint8_t slot) { ++count; word(tick); word(slot); } + void reg(std::uint32_t tick, std::uint8_t index, std::uint8_t value) { + ++count; word(tick); word(index); word(value); + } +}; +struct Oracle { + std::uint8_t id; + unsigned ticks; + std::uint64_t writes, register_hash, samples, sample_hash; +}; +// Counts and FNV-1a hashes from the executed, unmodified Original x86 driver. +// Canonical hash input: each observed column as little-endian u32, in order. +// No Original audio bytes or register/sample sequences are embedded here. +constexpr std::array kOracle{{ + {0,60000,32348,0xcbca207bfd99aeb0ull,3266,0xadad438156972aa9ull}, + {1,70000,12223,0xa0fe3a8b449c366bull,3163,0x31cd0db01f7a3ed2ull}, + {2,2000,386,0x52ce4acd30052d42ull,21,0xed4a856bd0b5d9bbull}, + {10,100,15,0xa38ea2831340e69eull,0,kFnvOffset}, + {11,100,15,0x6842cc45dcb290c5ull,0,kFnvOffset}, + {12,100,15,0x2ad007b26f4116b8ull,0,kFnvOffset}, + {13,100,15,0xaa5fff83f44303f5ull,0,kFnvOffset}, + {14,100,15,0xea8efbf8811746beull,0,kFnvOffset}, + {15,100,15,0x89a307eb865aa83full,0,kFnvOffset}, + {16,100,15,0x23a80f34bb743d13ull,0,kFnvOffset}, + {17,100,0,kFnvOffset,1,0xa91d37acc4be70b5ull}, + {18,100,0,kFnvOffset,1,0x09228ba46e88b424ull}, + {19,100,0,kFnvOffset,1,0xe9128fbd7129e9d7ull}, + {20,100,0,kFnvOffset,1,0x4917e3b51af42d46ull}, + {21,100,0,kFnvOffset,1,0x2932878b6be77e71ull}, + {22,100,0,kFnvOffset,1,0x8937db8315b1c1e0ull}, +}}; + +void original_oracle(const OriginalAssets& assets) { + for (const auto& expected : kOracle) { + OriginalSynth synth; load(synth, assets); + const bool song = expected.id < 3; + if (song) require(synth.command(expected.id), "Original song command"); + TraceHash registers, samples; + unsigned tick = 0, wraps = 0; + auto previous_bar = synth.stats().bar; + synth.set_register_observer([&](auto reg, auto value) { registers.reg(tick, reg, value); }); + synth.set_sample_observer([&](auto slot) { samples.sample(tick, slot); }); + if (!song) require(synth.effect(expected.id), "Original effect command"); + for (; tick < expected.ticks; ++tick) { + synth.tick(); + const auto stats = synth.stats(); + if (stats.bar < previous_bar) ++wraps; + previous_bar = stats.bar; + } + require(!synth.stats().failed && registers.count == expected.writes && + registers.hash == expected.register_hash && samples.count == expected.samples && + samples.hash == expected.sample_hash, + "executed Original driver oracle mismatch for ID " + std::to_string(expected.id)); + if (expected.id < 2) require(wraps > 0, "looping Original song must traverse its repeat boundary"); + if (expected.id == 2) require(!synth.stats().playing, "finite intro must stop at its Original end"); + std::cout << (song ? "song " : "effect ") << unsigned(expected.id) + << " ticks=" << expected.ticks << " registers=" << registers.count + << " fnv=" << std::hex << registers.hash << std::dec + << " samples=" << samples.count << " fnv=" << std::hex << samples.hash << std::dec << '\n'; + } +} + +void transition_oracle(const OriginalAssets& assets) { + // Executed Original x86: warm up 1000 IRQs, start direct effect16, switch + // through legacy routine/legacy routine (different song), or legacy routine/721d9/72199 + // (same song); observe the following5000 IRQs. Only digests are retained. + constexpr std::array writes{2469,364,386,1922,446,386,1922,364,0}; + constexpr std::array hashes{ + 0xe0e4d6a8ce302b09ull,0xa7c86105f1e09e74ull,0x52ce4acd30052d42ull, + 0x2157ea8cf3b1f61eull,0x4d37e6aa0de33d57ull,0x52ce4acd30052d42ull, + 0x22ad1211c726b767ull,0x5ebdbbd8e9af9298ull,kFnvOffset}; + constexpr std::array starts{276,218,21,277,231,21,277,218,0}; + constexpr std::array sample_hashes{ + 0x781b9195a1b85333ull,0x24d2a97d1a8511f9ull,0xed4a856bd0b5d9bbull, + 0x23b9f58978f6f974ull,0x7d674e527408da4dull,0xed4a856bd0b5d9bbull, + 0x23b9f58978f6f974ull,0x24d2a97d1a8511f9ull,kFnvOffset}; + for (unsigned previous = 0; previous < 3; ++previous) for (unsigned target = 0; target < 3; ++target) { + OriginalSynth synth; load(synth, assets); + require(synth.command(std::uint8_t(previous)), "transition warmup song"); + for (unsigned n = 0; n < 1000; ++n) synth.tick(); + require(synth.effect(16) && synth.command(std::uint8_t(target)), "transition effect and target"); + TraceHash registers, samples; unsigned tick = 0; + synth.set_register_observer([&](auto reg, auto value) { registers.reg(tick, reg, value); }); + synth.set_sample_observer([&](auto slot) { samples.sample(tick, slot); }); + for (; tick < 5000; ++tick) synth.tick(); + const auto index = previous * 3 + target; + require(!synth.stats().failed && registers.count == writes[index] && registers.hash == hashes[index] && + samples.count == starts[index] && samples.hash == sample_hashes[index], + "Original song transition mismatch " + std::to_string(previous) + "->" + std::to_string(target)); + } + std::cout << "transitions: all9 cross/same-song executed Original digests, including finite intro resume\n"; +} + +std::size_t payload(const OriginalAssets& assets, unsigned bank, const char* name) { + Container container; std::string error; + require(parse_container(assets.containers[bank], container, error), "parse external chunk: " + error); + for (const auto& chunk : container.chunks) if (chunk.id == name) return chunk.payload_offset; + throw std::runtime_error("missing external chunk"); +} +void put16(std::vector& bytes, std::size_t at, unsigned value) { + bytes.at(at) = std::uint8_t(value); bytes.at(at + 1) = std::uint8_t(value >> 8); +} +void malformed_inputs(const OriginalAssets& assets) { + unsigned cases = 0; + const auto rejected = [&](const std::function& mutation) { + auto malformed = assets; mutation(malformed); + OriginalSynth synth; std::string error; + require(!synth.load(std::move(malformed), 22050, error) && !error.empty() && !synth.ready(), + "malformed Original asset must fail before callback exposure: case " + std::to_string(cases)); + ++cases; + }; + rejected([](auto& a) { a.containers[0].clear(); }); + rejected([](auto& a) { a.containers[1].pop_back(); }); + rejected([](auto& a) { a.tables.operators[0] = 255; }); + rejected([](auto& a) { a.tables.operators[1] = a.tables.operators[0]; }); + rejected([](auto& a) { a.tables.frequencies[0] = 0; }); + rejected([](auto& a) { a.tables.frequencies[1] &= ~0x2000u; }); + const auto song = payload(assets, 0, "SONG"), track = payload(assets, 0, "TRCK"); + const auto part = payload(assets, 0, "PART"), sample = payload(assets, 3, "SAMP"); + const auto effect = payload(assets, 3, "SEFX"); + rejected([&](auto& a) { put16(a.containers[0], song + 4, 0); }); + rejected([&](auto& a) { put16(a.containers[0], song + 8, 0xffff); }); + rejected([&](auto& a) { std::fill_n(a.containers[0].begin() + std::ptrdiff_t(track + 4), 4, 255); }); + rejected([&](auto& a) { std::fill_n(a.containers[0].begin() + std::ptrdiff_t(part + 4), 4, 255); }); + rejected([&](auto& a) { + a.containers[3].at(sample + 4 + 10) = 1; + put16(a.containers[3], sample + 4 + 4, 0xffff); + put16(a.containers[3], sample + 4 + 6, 0xffff); + }); + rejected([&](auto& a) { a.containers[3].at(effect + 4 + 2) = 255; }); + rejected([&](auto& a) { a.containers[3].at(effect + 4 + 1) = 10; }); + OriginalSynth synth; std::string error; + require(!synth.load(assets, 7999, error) && !synth.load(assets, 192001, error), "output rate bounds"); + load(synth, assets); + require(synth.command(1), "valid song after malformed cases"); + const auto before = synth.stats(); + auto malformed = assets; malformed.containers[0].clear(); + require(!synth.load(std::move(malformed), 22050, error) && synth.ready() && + synth.stats().register_writes == before.register_writes && synth.stats().song == before.song, + "failed reload must retain the previous validated synthesizer"); + std::cout << "malformed: " << cases << " asset/table/span/loop cases plus rate and failed-reload bounds\n"; +} + +bool nonzero(std::span samples) { + return std::any_of(samples.begin(), samples.end(), [](auto value) { return value != 0; }); +} +void render_and_options(const OriginalAssets& assets) { + for (unsigned id = 0; id <= 22; ++id) { + if (id > 2 && id < 10) continue; + OriginalSynth synth; load(synth, assets); + require(id < 3 ? synth.command(std::uint8_t(id)) : synth.effect(std::uint8_t(id)), "render command"); + std::array pcm{}; synth.render(pcm); + require(!synth.stats().failed && synth.stats().frames == pcm.size() && nonzero(pcm), + "all Original songs/effects must produce bounded audible PCM: " + std::to_string(id)); + } + OriginalSynth first, second, silent; + load(first, assets); load(second, assets); load(silent, assets); + require(first.command(1) && second.command(1) && silent.command(1), "streaming song setup"); + std::array a{}, b{}, zero{}; + first.render(a); + for (std::size_t at = 0; at < b.size(); at += 97) + second.render(std::span(b).subspan(at, std::min(97, b.size() - at))); + silent.render(zero, 0); + require(a == b && nonzero(a) && !nonzero(zero) && + silent.stats().ticks == first.stats().ticks && silent.stats().frames == a.size(), + "PCM continuation is callback-block independent; zero volume preserves sequencing"); + require(!first.command(255) && !first.effect(9) && !first.effect(23), "invalid command/effect bounds"); + require(first.command(0) && !first.command(255), "title suppression cannot accept invalid IDs"); + auto writes = first.stats().register_writes; + require(first.command(16) && first.stats().register_writes == writes, "Source title suppresses game effects"); + first.stop(); + first.set_options({false, true, false}); + require(first.command(1) && !first.stats().playing, "music disabled independently"); + writes = first.stats().register_writes; + require(!first.effect(10) && first.stats().register_writes == writes && first.effect(16), + "click switch disables click ID10 while retaining non-click ID16"); + first.set_options({false, false, false}); + require(!first.effect(17), "effect option independently disabled"); + first.set_options({false, true, true}); + require(first.command(3) && first.stats().ambient, "Original crowd command starts loop"); + const auto starts = first.stats().sample_starts; + first.set_options({true, true, true}); first.set_options({false, true, true}); + require(first.stats().ambient && first.stats().sample_starts == starts, + "music option toggles cannot erase the Original crowd"); + first.render(a); require(nonzero(a) && first.stats().ambient, "bounded crowd render continues"); + first.stop(); require(!first.stats().playing && !first.stats().ambient, "stop clears all playback owners"); + std::cout << "render: 3 songs/13 effects, chunk continuity, volume0, switches, title gate and crowd loop\n"; +} + +void pause_and_crowd_transitions(const OriginalAssets& assets) { + OriginalSynth reference, paused; load(reference, assets); load(paused, assets); + require(reference.command(1) && paused.command(1), "pause/resume desk setup"); + for (unsigned n = 0; n < 233; ++n) { reference.tick(); paused.tick(); } + const auto cursor = paused.stats(); + paused.set_options({false, true, true}); + require(!paused.stats().playing, "music option pauses current song"); + for (unsigned n = 0; n < 71; ++n) paused.tick(); + require(paused.stats().bar == cursor.bar && paused.stats().step == cursor.step, + "disabled music retains its bar/step cursor"); + paused.set_options({true, true, true}); + require(paused.stats().playing, "music option resumes current song"); + for (unsigned n = 0; n < 257; ++n) { reference.tick(); paused.tick(); } + require(paused.stats().bar == reference.stats().bar && paused.stats().step == reference.stats().step, + "music option resumes retained tempo phase and cursors"); + + OriginalSynth desk, crowd; load(desk, assets); load(crowd, assets); + require(desk.command(1) && crowd.command(1), "crowd/desk setup"); + for (unsigned n = 0; n < 233; ++n) { desk.tick(); crowd.tick(); } + require(crowd.command(3) && crowd.stats().ambient && !crowd.stats().playing, "crowd pauses desk"); + const auto before = crowd.stats(); + require(crowd.command(3) && crowd.stats().sample_starts == before.sample_starts, + "same crowd command retains existing owner without restarting sample"); + for (unsigned n = 0; n < 71; ++n) crowd.tick(); + require(crowd.stats().bar == before.bar && crowd.stats().step == before.step, + "crowd retains the paused song cursor"); + require(crowd.command(1) && !crowd.stats().ambient && crowd.stats().playing, + "return to same desk song stops crowd and resumes music"); + for (unsigned n = 0; n < 257; ++n) { desk.tick(); crowd.tick(); } + require(crowd.stats().bar == desk.stats().bar && crowd.stats().step == desk.stats().step && + crowd.stats().song == 1 && !crowd.stats().failed, + "crowd to desk retains song/tempo cursor rather than restarting"); + std::cout << "pause/crowd: music off/on and crowd-to-desk retain song and tempo cursors\n"; +} + +void effect_priorities(const OriginalAssets& assets) { + const auto at = payload(assets, 3, "SEFX") + 4; + const auto& bytes = assets.containers[3]; + unsigned pairs = 0; + for (unsigned high = 0; high < 13; ++high) for (unsigned low = 0; low < 13; ++low) { + const auto h = at + high * 16, l = at + low * 16; + if (bytes[h + 1] != bytes[l + 1] || bytes[h + 3] <= bytes[l + 3] || + (bytes[h + 1] != 9 && bytes[h + 5] == 0)) continue; + OriginalSynth synth; load(synth, assets); + require(synth.effect(std::uint8_t(high + 10)), "start higher-priority Original effect"); + const auto before = synth.stats(); + require(synth.effect(std::uint8_t(low + 10)) && + synth.stats().register_writes == before.register_writes && + synth.stats().sample_starts == before.sample_starts, + "lower-priority effect must not interrupt the active Original channel"); + OriginalSynth replacement; load(replacement, assets); + require(replacement.effect(std::uint8_t(low + 10)), "start lower-priority Original effect"); + const auto old = replacement.stats(); + require(replacement.effect(std::uint8_t(high + 10)) && + (replacement.stats().register_writes > old.register_writes || + replacement.stats().sample_starts > old.sample_starts), + "higher-priority effect must replace the active lower-priority channel"); + ++pairs; + } + require(pairs != 0, "external bank must exercise actual priority pairs"); + std::cout << "priority: " << pairs << " actual competing high/low pairs retained correctly\n"; +} + +void callback_and_lifecycle(const OriginalAssets& assets) { + std::string error; + { + Playback playback; + require(playback.initialize_original(assets, error), "SDL Original initialization: " + error); + require(playback.available() && playback.original_ready() && !playback.needs_pump(), "callback mode owns audio"); + playback.reset_session(42); + require(playback.play_original_id(1, error), "callback desk song"); + const auto initial = playback.original_stats(); + SDL_Delay(120); // Deliberately no pump, render, GUI step or simulation callback. + const auto advanced = playback.original_stats(); + require(advanced.frames > initial.frames + 512 && advanced.ticks > initial.ticks && + advanced.playing && !advanced.failed && playback.queued_bytes() == 0, + "SDL callback must continue throughout a blocked main thread"); + playback.set_volume(0); + const auto quiet = playback.original_stats().frames; SDL_Delay(40); + require(playback.original_stats().frames > quiet && playback.volume() == 0, "zero volume retains callback clock"); + playback.set_volume(1); + playback.set_original_options({false, false, false}); + require(!playback.original_stats().playing, "saved music option reaches callback"); + const auto stopped = playback.original_stats().sample_starts; + require(playback.play_original_id(17, error) && playback.original_stats().sample_starts == stopped, + "disabled effects are a normal consumed refusal"); + playback.set_original_options({true, true, true}); + playback.set_muted(true); + const auto muted = playback.original_stats().frames; SDL_Delay(40); + require(playback.original_stats().frames == muted && !playback.original_stats().playing, + "mute stops and freezes Original sequencing"); + require(playback.submit(CueRequest{42, 1, 17}, error) == CueStatus::muted, "muted event consumed"); + playback.set_muted(false); + require(playback.submit(CueRequest{42, 1, 17}, error) == CueStatus::duplicate, + "unmute cannot replay a consumed event"); + require(playback.submit(CueRequest{41, 2, 17}, error) == CueStatus::invalid, "stale session refused"); + require(playback.submit(CueRequest{42, 2, 17}, error) == CueStatus::queued, "real effect submitted"); + require(playback.submit(CueRequest{42, 3, 255}, error) == CueStatus::unsupported && + playback.submit(CueRequest{42, 3, 255}, error) == CueStatus::duplicate, + "invalid command is rejected and its envelope remains consumed"); + playback.stop(); playback.reset_session(43); + require(playback.submit(CueRequest{43, 1, 16}, error) == CueStatus::queued, "new session starts independent event sequence"); + playback.shutdown(); + require(!playback.available() && playback.submit(CueRequest{43, 2, 16}, error) == CueStatus::disabled, + "shutdown closes device and consumes no-device events safely"); + require(playback.initialize_original(assets, error), "reinitialize after shutdown: " + error); + require(playback.play_original_id(2, error), "reinitialized finite song"); + } + const char* old = SDL_getenv("SDL_AUDIODRIVER"); + const std::string previous = old ? old : "dummy"; + SDL_setenv("SDL_AUDIODRIVER", "openbmh_intentionally_missing_driver", 1); + Playback unavailable; + const bool initialized = unavailable.initialize_original(assets, error); + SDL_setenv("SDL_AUDIODRIVER", previous.c_str(), 1); + require(!initialized && !unavailable.available() && !error.empty(), "unavailable device fails without crashing"); + require(unavailable.initialize_original(assets, error), "retry after no-device failure: " + error); + unavailable.shutdown(); + std::cout << "callback: blocked-main continuity, volume0/mute/options, dedup, no-device, reinitialize/lifecycle\n"; +} +} + +int main(int argc, char** argv) try { + if (argc != 2) return 2; + if (!*argv[1]) { + std::cout << "SKIP: external game audio not configured\n"; + return 77; + } + if (!*argv[1]) { std::cout << "SKIP: Original BMH_DATA not configured\n"; return 77; } + const auto assets = assets_from(argv[1]); + original_oracle(assets); + transition_oracle(assets); + malformed_inputs(assets); + render_and_options(assets); + pause_and_crowd_transitions(assets); + effect_priorities(assets); + callback_and_lifecycle(assets); + return 0; +} catch (const std::exception& error) { + std::cerr << "Original audio validation: " << error.what() << '\n'; + return 1; +} diff --git a/src/audio/playback.cpp b/src/audio/playback.cpp new file mode 100644 index 0000000..98d6468 --- /dev/null +++ b/src/audio/playback.cpp @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "playback.hpp" + +#include +#include +#include +#include + +namespace openbmh::audio { +namespace { +struct AudioLock { + SDL_AudioDeviceID device; + explicit AudioLock(SDL_AudioDeviceID id) : device(id) { if (device) SDL_LockAudioDevice(device); } + ~AudioLock() { if (device) SDL_UnlockAudioDevice(device); } +}; +constexpr std::uint32_t kQueueLimitBytes = 2U * 1024U * 1024U; +constexpr std::uint32_t kOutputRate = 22050; +constexpr std::size_t kPumpFrames = kOutputRate / 50; // 20 ms. +constexpr std::uint32_t kPumpBlockBytes = static_cast(kPumpFrames * 2); +constexpr std::uint32_t kQueueHighWaterBytes = kPumpBlockBytes * 2; // 40 ms. +} + +Playback::~Playback() { shutdown(); } + +bool Playback::initialize(std::string& error) { + error.clear(); + if (device_) return true; + if (!initialized_audio_ && SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) { + error = SDL_GetError(); + return false; + } + initialized_audio_ = true; + SDL_AudioSpec wanted{}; + wanted.freq = static_cast(kOutputRate); + wanted.format = AUDIO_S16SYS; + wanted.channels = 1; + // 1024 frames at 22050 Hz exceed the entire 40 ms music queue. A small + // device block lets the bounded queue cover 17/33 ms app pump intervals. + wanted.samples = 256; + if (original_mode_) { + wanted.callback = original_callback; + wanted.userdata = this; + } + device_ = SDL_OpenAudioDevice(nullptr, 0, &wanted, &obtained_, 0); + if (!device_) { + error = SDL_GetError(); + SDL_QuitSubSystem(SDL_INIT_AUDIO); + initialized_audio_ = false; + return false; + } + if (obtained_.format != AUDIO_S16SYS || obtained_.channels != 1) { + error = "audio device did not provide mono S16 output"; + SDL_CloseAudioDevice(device_); + device_ = 0; + SDL_QuitSubSystem(SDL_INIT_AUDIO); + initialized_audio_ = false; + return false; + } + SDL_PauseAudioDevice(device_, 0); + return true; +} + +bool Playback::initialize_original(OriginalAssets assets, std::string& error) { + // Asset parsing/preflight never runs inside a live audio callback. + if (device_) { + SDL_CloseAudioDevice(device_); + device_ = 0; + } + mixer_.clear(); + if (!original_.load(std::move(assets), kOutputRate, error)) return false; + original_.set_options(original_options_); + original_mode_ = true; + return initialize(error); +} + +void Playback::original_callback(void* userdata, Uint8* stream, int length) { + auto& self = *static_cast(userdata); + SDL_memset(stream, 0, size_t(length)); + if (length <= 0 || self.muted_) return; + self.original_.render(std::span(reinterpret_cast(stream), + size_t(length) / sizeof(std::int16_t)), self.volume_); +} + +void Playback::set_original_options(OriginalAudioOptions options) noexcept { + if (!original_mode_) return; + AudioLock lock(device_); + original_options_ = options; + original_.set_options(options); +} + +bool Playback::original_ready() const noexcept { + if (!original_mode_) return false; + AudioLock lock(device_); + return original_.ready(); +} + +OriginalAudioStats Playback::original_stats() const noexcept { + AudioLock lock(original_mode_ ? device_ : 0); + return original_.stats(); +} + +void Playback::shutdown() { + stop(); + if (device_) { + SDL_CloseAudioDevice(device_); + device_ = 0; + } + if (initialized_audio_) { + SDL_QuitSubSystem(SDL_INIT_AUDIO); + initialized_audio_ = false; + } +} + +void Playback::set_volume(float volume) noexcept { + AudioLock lock(original_mode_ ? device_ : 0); + if (std::isfinite(volume)) volume_ = std::clamp(volume, 0.0F, 1.0F); +} + +void Playback::set_muted(bool muted) noexcept { + if (original_mode_) { + AudioLock lock(device_); + muted_ = muted; + if (muted) original_.stop(); + return; + } + muted_ = muted; + if (muted_) stop(); +} + +std::uint32_t Playback::queued_bytes() const noexcept { + if (original_mode_) return 0; + return device_ ? SDL_GetQueuedAudioSize(device_) : 0; +} + +void Playback::stop() { + if (original_mode_) { + AudioLock lock(device_); + original_.stop(); + return; + } + if (device_) SDL_ClearQueuedAudio(device_); + mixer_.clear(); +} + +bool Playback::start_music_loop(const PcmSample& loop, std::string& error) { + error.clear(); + if (original_mode_) { error = "Original driver owns music playback"; return false; } + if (!device_) { error = "audio device is unavailable"; return false; } + if (obtained_.freq != static_cast(kOutputRate) || obtained_.samples > 256) { + error = "audio device block does not support the bounded music pump cadence"; + return false; + } + if (SDL_GetQueuedAudioSize(device_) > kQueueHighWaterBytes) { + error = "cannot start music while the existing cue queue exceeds 40 ms"; + return false; + } + return mixer_.start_music_loop(loop, static_cast(obtained_.freq), error); +} + +void Playback::stop_music() noexcept { + if (original_mode_) { + AudioLock lock(device_); + original_options_.music = false; + original_.set_options(original_options_); + return; + } + mixer_.stop_music(); +} + +bool Playback::pump(std::string& error) { + error.clear(); + if (original_mode_) return available(); + if (!device_) { error = "audio device is unavailable"; return false; } + if (muted_ || !mixer_.active()) return false; + + std::array block{}; + auto enqueue_up_to_20ms = [&]() { + const auto queued = SDL_GetQueuedAudioSize(device_); + if (queued >= kQueueHighWaterBytes) return false; + const auto room_frames = (kQueueHighWaterBytes - queued) / sizeof(std::int16_t); + const auto frames = std::min(kPumpFrames, room_frames); + if (!frames || !mixer_.mix_block(std::span(block.data(), frames), volume_)) + return false; + const auto bytes = static_cast(frames * sizeof(std::int16_t)); + if (SDL_QueueAudio(device_, block.data(), bytes) != 0) { + error = SDL_GetError(); + mixer_.clear(); + return false; + } + return true; + }; + + // Fill toward the 40 ms high-water mark. Two fixed, bounded calls let a + // 30 Hz main loop catch up without busy waiting or allocating in pump(). + const bool first = enqueue_up_to_20ms(); + if (!first || !mixer_.active()) return first; + enqueue_up_to_20ms(); + return error.empty(); +} + +void Playback::reset_session(std::uint64_t session_id) noexcept { + if (session_id == session_id_) return; + stop(); + session_id_ = session_id; + last_event_id_ = 0; +} + +CueStatus Playback::consume_event(std::uint64_t session_id, std::uint64_t event_id, + std::string& detail) { + detail.clear(); + if (!session_id_ || session_id != session_id_ || event_id == 0) { + detail = "invalid or stale audio event envelope"; + return CueStatus::invalid; + } + if (event_id <= last_event_id_) return CueStatus::duplicate; + last_event_id_ = event_id; + if (muted_) return CueStatus::muted; + if (!device_) return CueStatus::disabled; + return CueStatus::queued; +} + +CueStatus Playback::submit(CueRequest request, std::string& detail) { + const auto gate = consume_event(request.session_id, request.event_id, detail); + if (gate != CueStatus::queued) return gate; + if (!play_original_id(request.original_id, detail)) return CueStatus::unsupported; + return CueStatus::queued; +} + +CueStatus Playback::submit(SemanticCueRequest request, std::string& detail) { + const auto gate = consume_event(request.session_id, request.event_id, detail); + if (gate != CueStatus::queued) return gate; + if (!play_semantic_cue(request.cue, detail)) return CueStatus::unsupported; + return CueStatus::queued; +} + +bool Playback::load_original_bank(std::span bytes, + std::string& error) { + std::array, 13> decoded{}; + for (std::uint8_t id = 17; id <= 22; ++id) { + OriginalCue cue; + if (!decode_original_cue(bytes, id, cue, error)) return false; + decoded[static_cast(id - 10)] = std::move(cue.pcm); + } + stop(); + original_cues_ = std::move(decoded); + error.clear(); + return true; +} + +bool Playback::play_pcm(const std::int16_t* samples, std::size_t count, + std::uint32_t sample_rate, std::string& error) { + error.clear(); + if (original_mode_) { error = "Original driver does not queue synthetic PCM"; return false; } + if (!device_) { error = "audio device is unavailable"; return false; } + if (muted_ || volume_ == 0.0F) return true; + if (!samples || !count || sample_rate < 4000 || sample_rate > 192000) { + error = "invalid PCM input"; return false; + } + if (mixer_.active()) { + return mixer_.add_voice(std::span(samples, count), sample_rate, + static_cast(obtained_.freq), error); + } + if (count > std::numeric_limits::max() / sizeof(std::int16_t)) { + error = "PCM input is too large"; return false; + } + const std::uint64_t output_count64 = + (static_cast(count) * obtained_.freq + sample_rate / 2) / sample_rate; + if (output_count64 == 0 || output_count64 > kQueueLimitBytes / sizeof(std::int16_t)) { + error = "PCM input exceeds the bounded playback buffer"; return false; + } + const auto output_count = static_cast(output_count64); + const auto queued = SDL_GetQueuedAudioSize(device_); + if (queued > kQueueLimitBytes - output_count * sizeof(std::int16_t)) { + error = "playback queue is full"; return false; + } + std::vector converted(output_count); + for (std::size_t i = 0; i < output_count; ++i) { + const std::uint64_t numerator = static_cast(i) * sample_rate; + const auto source_index = std::min(count - 1, + static_cast((numerator + obtained_.freq / 2) / obtained_.freq)); + const auto scaled = std::lround(static_cast(samples[source_index]) * volume_); + converted[i] = static_cast(std::clamp(scaled, -32768, 32767)); + } + const auto bytes = static_cast(converted.size() * sizeof(std::int16_t)); + if (SDL_QueueAudio(device_, converted.data(), bytes) != 0) { + error = SDL_GetError(); return false; + } + return true; +} + +bool Playback::play_original_id(std::uint8_t id, std::string& error) { + if (original_mode_) { + error.clear(); + if (!device_) { error = "audio device is unavailable"; return false; } + AudioLock lock(device_); + if (muted_) return true; + if (original_.command(id)) return true; + // Disabled Original options are normal refusals, not decoder errors. + if (id >= 10 && id <= 22 && original_.ready()) return true; + error = "invalid Original sound command or failed sound driver"; + return false; + } + error.clear(); + if (id < 10 || id > 22 || !original_cues_[static_cast(id - 10)]) { + error = "original Sound ID has no decoded PCM cue (IDs 10..16 use unsupported instruments)"; + return false; + } + const auto& pcm = *original_cues_[static_cast(id - 10)]; + return play_pcm(pcm.mono.data(), pcm.mono.size(), pcm.sample_rate, error); +} + +bool Playback::play_semantic_cue(SemanticCue cue, std::string& error) { + PcmSample pcm; + if (!synthesize_semantic_cue(cue, pcm, error)) return false; + return play_pcm(pcm.mono.data(), pcm.mono.size(), pcm.sample_rate, error); +} + +} // namespace openbmh::audio diff --git a/src/audio/playback.hpp b/src/audio/playback.hpp new file mode 100644 index 0000000..9c6fc17 --- /dev/null +++ b/src/audio/playback.hpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "container.hpp" +#include "mixer.hpp" +#include "semantic_cues.hpp" +#include "original.hpp" + +#include +#include +#include +#include +#include +#include + +namespace openbmh::audio { + +struct CueRequest { + std::uint64_t session_id{}; + std::uint64_t event_id{}; + std::uint8_t original_id{}; +}; + +struct SemanticCueRequest { + std::uint64_t session_id{}; + std::uint64_t event_id{}; + SemanticCue cue{}; +}; + +enum class CueStatus { queued, muted, disabled, duplicate, unsupported, invalid }; + +class Playback { +public: + Playback() = default; + ~Playback(); + Playback(const Playback&) = delete; + Playback& operator=(const Playback&) = delete; + + bool initialize(std::string& error); + // Full Original driver, streamed by SDL's audio callback so synchronous + // simulation and modal windows cannot starve music or the crowd loop. + bool initialize_original(OriginalAssets assets, std::string& error); + bool original_ready() const noexcept; + void set_original_options(OriginalAudioOptions options) noexcept; + OriginalAudioStats original_stats() const noexcept; + void shutdown(); + bool available() const noexcept { return device_ != 0; } + void set_muted(bool muted) noexcept; + bool muted() const noexcept { return muted_; } + std::uint32_t queued_bytes() const noexcept; + void set_volume(float volume) noexcept; + float volume() const noexcept { return volume_; } + void stop(); + + // Optional software music. It is off by default. pump() adds at most two + // bounded blocks of up to 20 ms; total queued audio stays at or below 40 ms. + // Music requires 22050 Hz and a device block no larger than 256 frames. + bool start_music_loop(const PcmSample& loop, std::string& error); + void stop_music() noexcept; + bool music_active() const noexcept { return mixer_.has_music(); } + bool needs_pump() const noexcept { return !original_mode_ && mixer_.active(); } + bool pump(std::string& error); + + // The controller supplies stable session/event identities. IDs are not + // generated by audio; requests are consumed once in increasing event order. + void reset_session(std::uint64_t session_id) noexcept; + CueStatus submit(CueRequest request, std::string& detail); + CueStatus submit(SemanticCueRequest request, std::string& detail); + + // Legacy PCM-only bank loader. initialize_original provides the complete + // sequencer and instrument path for songs and all effects 10..22. + bool load_original_bank(std::span bytes, std::string& error); + + // Plays caller-supplied mono S16 native-endian PCM. A 2 MiB queue ceiling + // prevents a caller from accumulating unbounded playback. This is a backend + // primitive, not an original Sound ID mapping. + bool play_pcm(const std::int16_t* samples, std::size_t count, + std::uint32_t sample_rate, std::string& error); + bool play_original_id(std::uint8_t id, std::string& error); + bool play_semantic_cue(SemanticCue cue, std::string& error); + +private: + static void original_callback(void* userdata, Uint8* stream, int length); + CueStatus consume_event(std::uint64_t session_id, std::uint64_t event_id, + std::string& detail); + SDL_AudioDeviceID device_{}; + SDL_AudioSpec obtained_{}; + bool initialized_audio_{}; + bool muted_{}; + float volume_{1.0F}; + std::uint64_t session_id_{}; + std::uint64_t last_event_id_{}; + std::array, 13> original_cues_{}; + Mixer mixer_; + OriginalSynth original_; + bool original_mode_{}; + OriginalAudioOptions original_options_; +}; + +} // namespace openbmh::audio diff --git a/src/audio/semantic_cues.cpp b/src/audio/semantic_cues.cpp new file mode 100644 index 0000000..6b07735 --- /dev/null +++ b/src/audio/semantic_cues.cpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "semantic_cues.hpp" + +#include +#include +#include + +namespace openbmh::audio { +namespace { +constexpr std::uint32_t kSampleRate = 22050; +constexpr double kPi = 3.14159265358979323846; + +std::int16_t clamp_pcm(double value) { + const auto rounded = static_cast(std::lround(value)); + return static_cast(std::clamp(rounded, -32768L, 32767L)); +} + +void append_whistle(std::vector& pcm, std::size_t frames, + double start_hz, double end_hz) { + double phase = 0.0; + const std::size_t attack = kSampleRate / 80; + const std::size_t release = kSampleRate / 14; + for (std::size_t i = 0; i < frames; ++i) { + const double t = static_cast(i) / static_cast(frames); + const double frequency = start_hz + (end_hz - start_hz) * t; + phase += 2.0 * kPi * frequency / kSampleRate; + const double in = std::min(1.0, static_cast(i) / attack); + const double out = std::min(1.0, static_cast(frames - 1 - i) / release); + const double envelope = std::min(in, out); + const double tone = std::sin(phase) + 0.16 * std::sin(phase * 2.01); + pcm.push_back(clamp_pcm(14500.0 * envelope * tone)); + } +} + +void append_fanfare_note(std::vector& pcm, std::size_t frames, + double frequency) { + double phase = 0.0; + const std::size_t attack = kSampleRate / 90; + const std::size_t release = kSampleRate / 9; + for (std::size_t i = 0; i < frames; ++i) { + phase += 2.0 * kPi * frequency / kSampleRate; + const double in = std::min(1.0, static_cast(i) / attack); + const double out = std::min(1.0, static_cast(frames - 1 - i) / release); + const double envelope = std::min(in, out); + const double brass = std::sin(phase) + 0.38 * std::sin(phase * 2.0) + + 0.14 * std::sin(phase * 3.0); + pcm.push_back(clamp_pcm(10500.0 * envelope * brass)); + } +} +} + +bool synthesize_semantic_cue(SemanticCue cue, PcmSample& out, std::string& error) { + out = {}; + error.clear(); + out.sample_rate = kSampleRate; + switch (cue) { + case SemanticCue::kickoff_whistle: + append_whistle(out.mono, kSampleRate * 42 / 100, 2050.0, 1880.0); + break; + case SemanticCue::goal: + append_fanfare_note(out.mono, kSampleRate * 15 / 100, 659.25); + append_fanfare_note(out.mono, kSampleRate * 15 / 100, 783.99); + append_fanfare_note(out.mono, kSampleRate * 34 / 100, 987.77); + break; + case SemanticCue::full_time_whistle: + append_whistle(out.mono, kSampleRate * 32 / 100, 1940.0, 1840.0); + out.mono.insert(out.mono.end(), kSampleRate * 9 / 100, 0); + append_whistle(out.mono, kSampleRate * 42 / 100, 2110.0, 1910.0); + break; + default: + out = {}; + error = "unknown semantic audio cue"; + return false; + } + return true; +} + +} // namespace openbmh::audio diff --git a/src/audio/semantic_cues.hpp b/src/audio/semantic_cues.hpp new file mode 100644 index 0000000..6a9cba6 --- /dev/null +++ b/src/audio/semantic_cues.hpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "container.hpp" + +#include +#include + +namespace openbmh::audio { + +// Presentation cues used when no verified original PCM effect is available. +// These are intentionally semantic labels, never fabricated original Sound IDs. +enum class SemanticCue : std::uint8_t { + kickoff_whistle = 1, + goal = 2, + full_time_whistle = 3, +}; + +// Generates deterministic mono PCM16 cues at 22050 Hz. The synthesizer has no +// game state, random source, or renderer dependency. +bool synthesize_semantic_cue(SemanticCue cue, PcmSample& out, std::string& error); + +} // namespace openbmh::audio diff --git a/src/audio/sound_driver.cpp b/src/audio/sound_driver.cpp new file mode 100644 index 0000000..eef3b7c --- /dev/null +++ b/src/audio/sound_driver.cpp @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "container.hpp" +#include "music_fallback.hpp" +#include "playback.hpp" +#include "formats/le.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +bool parse_semantic_cue(const std::string& name, openbmh::audio::SemanticCue& cue) { + using openbmh::audio::SemanticCue; + if (name == "kickoff_whistle") cue = SemanticCue::kickoff_whistle; + else if (name == "goal") cue = SemanticCue::goal; + else if (name == "full_time_whistle") cue = SemanticCue::full_time_whistle; + else return false; + return true; +} + +bool write_wav(const openbmh::audio::PcmSample& decoded, const char* path, + std::string& error) { + if (decoded.mono.size() > (std::numeric_limits::max() - 36u) / 2u || + decoded.sample_rate == 0 || decoded.sample_rate > 192000) { + error = "WAV output exceeds format bounds"; return false; + } + const std::uint32_t data_bytes = static_cast(decoded.mono.size() * 2); + std::ofstream wav(path, std::ios::binary); + if (!wav) { error = "cannot create WAV output"; return false; } + const auto put16 = [&wav](std::uint16_t v) { + const char b[] = {static_cast(v), static_cast(v >> 8)}; + wav.write(b, 2); + }; + const auto put32 = [&wav](std::uint32_t v) { + const char b[] = {static_cast(v), static_cast(v >> 8), + static_cast(v >> 16), static_cast(v >> 24)}; + wav.write(b, 4); + }; + wav.write("RIFF", 4); put32(36 + data_bytes); wav.write("WAVEfmt ", 8); + put32(16); put16(1); put16(1); put32(decoded.sample_rate); + put32(decoded.sample_rate * 2); put16(2); put16(16); wav.write("data", 4); + put32(data_bytes); + for (const auto value : decoded.mono) put16(static_cast(value)); + if (!wav) { error = "failed while writing WAV output"; return false; } + error.clear(); + return true; +} + +bool bounded_number(const char* value, unsigned minimum, unsigned maximum, unsigned& out) { + const std::string_view text(value); + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), out); + return error == std::errc{} && end == text.data() + text.size() && out >= minimum && out <= maximum; +} + +openbmh::audio::OriginalAssets load_original_assets(const std::filesystem::path& directory) { + openbmh::audio::OriginalAssets assets; + const auto exe = bmh::load_le(directory / "BMH.exe"); + for (unsigned i = 0; i < 4; ++i) + assets.containers[i] = bmh::read_file(directory / "S" / std::to_string(2000 + i)); + for (unsigned i = 0; i < assets.tables.frequencies.size(); ++i) + assets.tables.frequencies[i] = exe.u16(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField2 + 2 * i); + for (unsigned i = 0; i < assets.tables.operators.size(); ++i) + assets.tables.operators[i] = exe.u8(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField + 16 * i); + return assets; +} + +int original_driver(int argc, char** argv) { + using namespace openbmh::audio; + const auto usage = [] { + std::cerr << "usage: openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds 1..600] [--loops 1..16]\n" + " openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds 1..600]\n" + " openbmh_sound --original DATA_DIR --play-id ID [--seconds 1..600]\n" + " openbmh_sound --original DATA_DIR --play-all [--seconds 1..600]\n"; + return 2; + }; + if (argc < 4) return usage(); + const std::string action = argv[3]; + const bool song = action == "--export-song"; + const bool export_id = action == "--export-id"; + const bool play = action == "--play-id"; + const bool all = action == "--play-all"; + if (!song && !export_id && !play && !all) return usage(); + const int required = all ? 4 : play ? 5 : 6; + if (argc < required) return usage(); + unsigned id = 0, seconds = song || all ? 10 : 2, loops = 1; + if (!all && !bounded_number(argv[4], 0, 255, id)) return usage(); + if ((song && id > 2) || (export_id && (id < 10 || id > 22)) || + (play && !(id <= 3 || id == 8 || (id >= 10 && id <= 22)))) return usage(); + for (int at = required; at < argc; at += 2) { + if (at + 1 >= argc) return usage(); + const std::string option = argv[at]; + if (option == "--seconds") { + if (!bounded_number(argv[at + 1], 1, 600, seconds)) return usage(); + } else if (song && option == "--loops") { + if (!bounded_number(argv[at + 1], 1, 16, loops)) return usage(); + } else return usage(); + } + try { + auto assets = load_original_assets(argv[2]); + std::string error; + if (song || export_id) { + OriginalSynth synth; + if (!synth.load(std::move(assets), 22050, error)) { + std::cerr << "Original audio rejected: " << error << '\n'; return 1; + } + if (!(song ? synth.command(std::uint8_t(id)) : synth.effect(std::uint8_t(id)))) { + std::cerr << "Original command rejected\n"; return 1; + } + PcmSample pcm; pcm.sample_rate = 22050; + const std::size_t limit = std::size_t(seconds) * pcm.sample_rate; + pcm.mono.reserve(limit); + std::array block{}; + unsigned completed_loops = 0; + auto previous_bar = synth.stats().bar; + bool completed = false; + while (pcm.mono.size() < limit) { + const auto count = std::min(block.size(), limit - pcm.mono.size()); + synth.render(std::span(block).first(count)); + pcm.mono.insert(pcm.mono.end(), block.begin(), block.begin() + std::ptrdiff_t(count)); + const auto stats = synth.stats(); + if (stats.failed) { std::cerr << "Original decoder failed during export\n"; return 1; } + if (song) { + if (stats.bar < previous_bar) ++completed_loops; + previous_bar = stats.bar; + if (!stats.playing || completed_loops >= loops) { completed = true; break; } + } + } + if (!write_wav(pcm, argv[5], error)) { std::cerr << error << '\n'; return 1; } + const auto stats = synth.stats(); + std::cout << "exported Original " << (song ? "song=" : "effect=") << id + << " rate=22050 channels=1 bits=16 frames=" << pcm.mono.size() + << " ticks=" << stats.ticks << " loops=" << completed_loops + << " stop=" << (completed ? "song-or-loop-complete" : "duration-bound") << '\n'; + return 0; + } + Playback playback; + if (!playback.initialize_original(std::move(assets), error)) { + std::cerr << "Original playback unavailable: " << error << '\n'; return 1; + } + const auto audition = [&](unsigned command, unsigned duration) { + if (!playback.play_original_id(std::uint8_t(command), error)) return false; + // The actual callback must continue while the main thread is blocked. + SDL_Delay(duration * 1000); + const auto stats = playback.original_stats(); + std::cout << "played Original command=" << command << " frames=" << stats.frames + << " ticks=" << stats.ticks << " failed=" << stats.failed << '\n'; + playback.stop(); + return !stats.failed; + }; + if (all) { + for (unsigned command = 0; command < 3; ++command) + if (!audition(command, seconds)) { std::cerr << error << '\n'; return 1; } + for (unsigned command = 10; command <= 22; ++command) + if (!audition(command, seconds)) { std::cerr << error << '\n'; return 1; } + return 0; + } + if (!audition(id, seconds)) { std::cerr << error << '\n'; return 1; } + return 0; + } catch (const std::exception& error) { + std::cerr << "Original audio input: " << error.what() << '\n'; return 1; + } +} +} + +int main(int argc, char** argv) { + if (argc >= 2 && std::string(argv[1]) == "--original") return original_driver(argc, argv); + if (argc < 2) { + std::cerr << "usage: openbmh_sound [--play-test-tone | --play-sample INDEX | --export-sample INDEX OUTPUT.wav | --play-id ID | --export-id ID OUTPUT.wav]\n" + " openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds N] [--loops N]\n" + " openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds N]\n" + " openbmh_sound --original DATA_DIR --play-id ID | --play-all [--seconds N]\n" + " openbmh_sound --play-cue NAME | --export-cue NAME OUTPUT.wav\n" + " openbmh_sound --export-music-loop OUTPUT.wav\n"; + return 2; + } + if (argc == 4 && std::string(argv[1]) == "--export-cue") { + openbmh::audio::SemanticCue cue; + const std::string name = argv[2]; + if (!parse_semantic_cue(name, cue)) { + std::cerr << "unknown semantic cue\n"; return 2; + } + openbmh::audio::PcmSample pcm; + std::string error; + if (!openbmh::audio::synthesize_semantic_cue(cue, pcm, error) || + !write_wav(pcm, argv[3], error)) { + std::cerr << "semantic cue export failed: " << error << '\n'; return 1; + } + std::cout << "exported synthetic semantic cue=" << name << " rate=" << pcm.sample_rate + << " Hz channels=1 bits=16 frames=" << pcm.mono.size() + << " (not an original Sound ID)\n"; + return 0; + } + if (argc == 3 && std::string(argv[1]) == "--export-music-loop") { + openbmh::audio::PcmSample pcm; + std::string error; + if (!openbmh::audio::synthesize_matchday_music_loop(pcm, error) || + !write_wav(pcm, argv[2], error)) { + std::cerr << "synthetic music export failed: " << error << '\n'; return 1; + } + std::cout << "exported synthetic 8-bar matchday loop rate=" << pcm.sample_rate + << " Hz channels=1 bits=16 frames=" << pcm.mono.size() + << " (not original music or a Sound ID)\n"; + return 0; + } + if (argc == 3 && std::string(argv[1]) == "--play-cue") { + openbmh::audio::SemanticCue cue; + std::uint32_t wait_ms; + const std::string name = argv[2]; + if (!parse_semantic_cue(name, cue)) { std::cerr << "unknown semantic cue\n"; return 2; } + if (cue == openbmh::audio::SemanticCue::kickoff_whistle) wait_ms = 500; + else if (cue == openbmh::audio::SemanticCue::goal) wait_ms = 750; + else wait_ms = 1000; + openbmh::audio::Playback playback; + std::string cue_error; + if (!playback.initialize(cue_error)) { + std::cerr << "audio unavailable: " << cue_error << '\n'; return 0; + } + if (!playback.play_semantic_cue(cue, cue_error)) { + std::cerr << "semantic cue playback failed: " << cue_error << '\n'; return 1; + } + SDL_Delay(wait_ms); + playback.stop(); + std::cout << "played synthetic semantic cue=" << name << " (not an original Sound ID)\n"; + return 0; + } + std::vector bytes; + FILE* f = std::fopen(argv[1], "rb"); + if (!f) { std::cerr << "cannot open input\n"; return 2; } + if (std::fseek(f, 0, SEEK_END) != 0) { std::fclose(f); return 2; } + const long n = std::ftell(f); + if (n < 0 || n > 64L * 1024 * 1024 || std::fseek(f, 0, SEEK_SET) != 0) { + std::fclose(f); std::cerr << "input size rejected\n"; return 2; + } + bytes.resize(static_cast(n)); + const auto got = std::fread(bytes.data(), 1, bytes.size(), f); + std::fclose(f); + if (got != bytes.size()) { std::cerr << "short read\n"; return 2; } + + openbmh::audio::Container container; + std::string error; + if (!openbmh::audio::parse_container(bytes, container, error)) { + std::cerr << "container rejected: " << error << '\n'; return 1; + } + for (const auto& c : container.chunks) + std::cout << c.id << " offset=" << c.payload_offset << " length=" << c.payload_size << '\n'; + + if ((argc >= 4 && std::string(argv[2]) == "--play-id") || + (argc >= 5 && std::string(argv[2]) == "--export-id")) { + const bool do_play = std::string(argv[2]) == "--play-id"; + char* end = nullptr; + const unsigned long id = std::strtoul(argv[3], &end, 10); + if (!end || *end != '\0' || id > 255) { + std::cerr << "invalid original Sound ID\n"; return 2; + } + openbmh::audio::OriginalCue cue; + if (!openbmh::audio::decode_original_cue(bytes, static_cast(id), cue, error)) { + std::cerr << "original cue rejected: " << error << '\n'; return 1; + } + if (do_play) { + openbmh::audio::Playback playback; + if (!playback.initialize(error)) { + std::cerr << "audio unavailable: " << error << '\n'; return 0; + } + if (!playback.load_original_bank(bytes, error) || + !playback.play_original_id(cue.original_id, error)) { + std::cerr << "original cue playback rejected: " << error << '\n'; return 1; + } + const auto milliseconds = static_cast( + cue.pcm.mono.size() * 1000 / cue.pcm.sample_rate); + SDL_Delay(milliseconds + 25); + playback.stop(); + std::cout << "played original_id=" << static_cast(cue.original_id) + << " sefx_index=" << static_cast(cue.sefx_index) + << " samp_index=" << static_cast(cue.sample_index) + << " frames=" << cue.pcm.mono.size() << " rate=" + << cue.pcm.sample_rate << " Hz\n"; + } else { + if (!write_wav(cue.pcm, argv[4], error)) { + std::cerr << error << '\n'; return 2; + } + std::cout << "original_id=" << static_cast(cue.original_id) + << " sefx_index=" << static_cast(cue.sefx_index) + << " samp_index=" << static_cast(cue.sample_index) + << " rate=" << cue.pcm.sample_rate << " Hz channels=1 bits=16 frames=" + << cue.pcm.mono.size() << '\n'; + } + } + + if ((argc >= 4 && std::string(argv[2]) == "--play-sample") || + (argc >= 5 && std::string(argv[2]) == "--export-sample")) { + const bool do_play = std::string(argv[2]) == "--play-sample"; + char* end = nullptr; + const unsigned long index = std::strtoul(argv[3], &end, 10); + if (!end || *end != '\0' || index > 255) { + std::cerr << "invalid sample index\n"; return 2; + } + const auto samp = std::find_if(container.chunks.begin(), container.chunks.end(), + [](const auto& c) { return c.id == "SAMP"; }); + if (samp == container.chunks.end()) { std::cerr << "no SAMP chunk\n"; return 1; } + openbmh::audio::PcmSample decoded; + if (!openbmh::audio::decode_sample( + std::span(bytes).subspan(samp->payload_offset, samp->payload_size), + index, decoded, error)) { + std::cerr << "sample rejected: " << error << '\n'; return 1; + } + if (do_play) { + openbmh::audio::Playback playback; + if (!playback.initialize(error)) { + std::cerr << "audio unavailable: " << error << '\n'; return 0; + } + if (!playback.play_pcm(decoded.mono.data(), decoded.mono.size(), decoded.sample_rate, error)) { + std::cerr << "sample playback rejected: " << error << '\n'; return 1; + } + const auto milliseconds = static_cast( + decoded.mono.size() * 1000 / decoded.sample_rate); + SDL_Delay(milliseconds + 25); + playback.stop(); + std::cout << "played SAMP sample=" << index << " frames=" << decoded.mono.size() + << " rate=" << decoded.sample_rate << " Hz\n"; + } else { + const std::uint32_t data_bytes = static_cast(decoded.mono.size() * 2); + std::ofstream wav(argv[4], std::ios::binary); + if (!wav) { std::cerr << "cannot create WAV output\n"; return 2; } + const auto put16 = [&wav](std::uint16_t v) { + const char b[] = {static_cast(v), static_cast(v >> 8)}; + wav.write(b, 2); + }; + const auto put32 = [&wav](std::uint32_t v) { + const char b[] = {static_cast(v), static_cast(v >> 8), + static_cast(v >> 16), static_cast(v >> 24)}; + wav.write(b, 4); + }; + wav.write("RIFF", 4); put32(36 + data_bytes); wav.write("WAVEfmt ", 8); + put32(16); put16(1); put16(1); put32(decoded.sample_rate); + put32(decoded.sample_rate * 2); put16(2); put16(16); wav.write("data", 4); + put32(data_bytes); + for (const auto value : decoded.mono) put16(static_cast(value)); + if (!wav) { std::cerr << "failed while writing WAV\n"; return 2; } + std::cout << "sample=" << index << " rate=" << decoded.sample_rate + << " Hz channels=1 bits=16 frames=" << decoded.mono.size() << '\n'; + } + } + + if (argc >= 3 && std::string(argv[2]) == "--play-test-tone") { + openbmh::audio::Playback playback; + if (!playback.initialize(error)) { + std::cerr << "audio unavailable: " << error << '\n'; return 0; + } + constexpr std::uint32_t rate = 22050; + std::vector tone(rate / 5); + for (std::size_t i = 0; i < tone.size(); ++i) + tone[i] = static_cast(6000.0 * std::sin(2.0 * 3.141592653589793 * 440.0 * i / rate)); + if (!playback.play_pcm(tone.data(), tone.size(), rate, error)) { + std::cerr << "test tone rejected: " << error << '\n'; return 1; + } + SDL_Delay(250); + playback.stop(); + } + return 0; +} diff --git a/src/audio/third_party/nuked-opl3/LICENSE b/src/audio/third_party/nuked-opl3/LICENSE new file mode 100644 index 0000000..8000a6f --- /dev/null +++ b/src/audio/third_party/nuked-opl3/LICENSE @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random + Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/audio/third_party/nuked-opl3/README.md b/src/audio/third_party/nuked-opl3/README.md new file mode 100644 index 0000000..4f00613 --- /dev/null +++ b/src/audio/third_party/nuked-opl3/README.md @@ -0,0 +1,8 @@ +Nuked OPL3 by Nuke.YKT, unmodified upstream source. + +Upstream: https://github.com/nukeykt/Nuked-OPL3 +Commit: 765ec962e473aeb767e4cba74ffdc8f588ffbfe8 +License: LGPL-2.1-or-later (see LICENSE and source notices). + +Used in OPL2 compatibility mode for the Original MIDILINK register stream. +No Original music, instruments, samples or executable bytes are distributed. diff --git a/src/audio/third_party/nuked-opl3/opl3.c b/src/audio/third_party/nuked-opl3/opl3.c new file mode 100644 index 0000000..4847022 --- /dev/null +++ b/src/audio/third_party/nuked-opl3/opl3.c @@ -0,0 +1,1517 @@ +/* Nuked OPL3 + * Copyright (C) 2013-2020 Nuke.YKT + * + * This file is part of Nuked OPL3. + * + * Nuked OPL3 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 + * of the License, or (at your option) any later version. + * + * Nuked OPL3 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Nuked OPL3. If not, see . + + * Nuked OPL3 emulator. + * Thanks: + * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): + * Feedback and Rhythm part calculation information. + * forums.submarine.org.uk(carbon14, opl3): + * Tremolo and phase generator calculation information. + * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): + * OPL2 ROMs. + * siliconpr0n.org(John McMaster, digshadow): + * YMF262 and VRC VII decaps and die shots. + * + * version: 1.8 + */ + +#include +#include +#include +#include "opl3.h" + +#if OPL_ENABLE_STEREOEXT && !defined OPL_SIN +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES 1 +#endif +#include +/* input: [0, 256), output: [0, 65536] */ +#define OPL_SIN(x) ((int32_t)(sin((x) * M_PI / 512.0) * 65536.0)) +#endif + +/* Quirk: Some FM channels are output one sample later on the left side than the right. */ +#ifndef OPL_QUIRK_CHANNELSAMPLEDELAY +#define OPL_QUIRK_CHANNELSAMPLEDELAY (!OPL_ENABLE_STEREOEXT) +#endif + +#define RSM_FRAC 10 + +/* Channel types */ + +enum { + ch_2op = 0, + ch_4op = 1, + ch_4op2 = 2, + ch_drum = 3 +}; + +/* Envelope key types */ + +enum { + egk_norm = 0x01, + egk_drum = 0x02 +}; + + +/* + logsin table +*/ + +static const uint16_t logsinrom[256] = { + 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, + 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365, + 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, + 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, + 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, + 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, + 0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, + 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, + 0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, + 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118, + 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, + 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, + 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, + 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, + 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, + 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, + 0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, + 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060, + 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, + 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045, + 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, + 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, + 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, + 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, + 0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, + 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, + 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, + 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007, + 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, + 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, + 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, + 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000 +}; + +/* + exp table +*/ + +static const uint16_t exprom[256] = { + 0x7fa, 0x7f5, 0x7ef, 0x7ea, 0x7e4, 0x7df, 0x7da, 0x7d4, + 0x7cf, 0x7c9, 0x7c4, 0x7bf, 0x7b9, 0x7b4, 0x7ae, 0x7a9, + 0x7a4, 0x79f, 0x799, 0x794, 0x78f, 0x78a, 0x784, 0x77f, + 0x77a, 0x775, 0x770, 0x76a, 0x765, 0x760, 0x75b, 0x756, + 0x751, 0x74c, 0x747, 0x742, 0x73d, 0x738, 0x733, 0x72e, + 0x729, 0x724, 0x71f, 0x71a, 0x715, 0x710, 0x70b, 0x706, + 0x702, 0x6fd, 0x6f8, 0x6f3, 0x6ee, 0x6e9, 0x6e5, 0x6e0, + 0x6db, 0x6d6, 0x6d2, 0x6cd, 0x6c8, 0x6c4, 0x6bf, 0x6ba, + 0x6b5, 0x6b1, 0x6ac, 0x6a8, 0x6a3, 0x69e, 0x69a, 0x695, + 0x691, 0x68c, 0x688, 0x683, 0x67f, 0x67a, 0x676, 0x671, + 0x66d, 0x668, 0x664, 0x65f, 0x65b, 0x657, 0x652, 0x64e, + 0x649, 0x645, 0x641, 0x63c, 0x638, 0x634, 0x630, 0x62b, + 0x627, 0x623, 0x61e, 0x61a, 0x616, 0x612, 0x60e, 0x609, + 0x605, 0x601, 0x5fd, 0x5f9, 0x5f5, 0x5f0, 0x5ec, 0x5e8, + 0x5e4, 0x5e0, 0x5dc, 0x5d8, 0x5d4, 0x5d0, 0x5cc, 0x5c8, + 0x5c4, 0x5c0, 0x5bc, 0x5b8, 0x5b4, 0x5b0, 0x5ac, 0x5a8, + 0x5a4, 0x5a0, 0x59c, 0x599, 0x595, 0x591, 0x58d, 0x589, + 0x585, 0x581, 0x57e, 0x57a, 0x576, 0x572, 0x56f, 0x56b, + 0x567, 0x563, 0x560, 0x55c, 0x558, 0x554, 0x551, 0x54d, + 0x549, 0x546, 0x542, 0x53e, 0x53b, 0x537, 0x534, 0x530, + 0x52c, 0x529, 0x525, 0x522, 0x51e, 0x51b, 0x517, 0x514, + 0x510, 0x50c, 0x509, 0x506, 0x502, 0x4ff, 0x4fb, 0x4f8, + 0x4f4, 0x4f1, 0x4ed, 0x4ea, 0x4e7, 0x4e3, 0x4e0, 0x4dc, + 0x4d9, 0x4d6, 0x4d2, 0x4cf, 0x4cc, 0x4c8, 0x4c5, 0x4c2, + 0x4be, 0x4bb, 0x4b8, 0x4b5, 0x4b1, 0x4ae, 0x4ab, 0x4a8, + 0x4a4, 0x4a1, 0x49e, 0x49b, 0x498, 0x494, 0x491, 0x48e, + 0x48b, 0x488, 0x485, 0x482, 0x47e, 0x47b, 0x478, 0x475, + 0x472, 0x46f, 0x46c, 0x469, 0x466, 0x463, 0x460, 0x45d, + 0x45a, 0x457, 0x454, 0x451, 0x44e, 0x44b, 0x448, 0x445, + 0x442, 0x43f, 0x43c, 0x439, 0x436, 0x433, 0x430, 0x42d, + 0x42a, 0x428, 0x425, 0x422, 0x41f, 0x41c, 0x419, 0x416, + 0x414, 0x411, 0x40e, 0x40b, 0x408, 0x406, 0x403, 0x400 +}; + +/* + freq mult table multiplied by 2 + + 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15 +*/ + +static const uint8_t mt[16] = { + 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30 +}; + +/* + ksl table +*/ + +static const uint8_t kslrom[16] = { + 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64 +}; + +static const uint8_t kslshift[4] = { + 8, 1, 2, 0 +}; + +/* + envelope generator constants +*/ + +static const uint8_t eg_incstep[4][4] = { + { 0, 0, 0, 0 }, + { 1, 0, 0, 0 }, + { 1, 0, 1, 0 }, + { 1, 1, 1, 0 } +}; + +/* + address decoding +*/ + +static const int8_t ad_slot[0x20] = { + 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, + 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 +}; + +static const uint8_t ch_slot[18] = { + 0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32 +}; + +#if OPL_ENABLE_STEREOEXT +/* + stereo extension panning table +*/ + +static int32_t panpot_lut[256]; +static uint8_t panpot_lut_build = 0; +#endif + +/* + Envelope generator +*/ + +typedef int16_t(*envelope_sinfunc)(uint16_t phase, uint16_t envelope); +typedef void(*envelope_genfunc)(opl3_slot *slott); + +static int16_t OPL3_EnvelopeCalcExp(uint32_t level) +{ + if (level > 0x1fff) + { + level = 0x1fff; + } + return (exprom[level & 0xffu] << 1) >> (level >> 8); +} + +static int16_t OPL3_EnvelopeCalcSin0(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + uint16_t neg = 0; + phase &= 0x3ff; + if (phase & 0x200) + { + neg = 0xffff; + } + if (phase & 0x100) + { + out = logsinrom[(phase & 0xffu) ^ 0xffu]; + } + else + { + out = logsinrom[phase & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; +} + +static int16_t OPL3_EnvelopeCalcSin1(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + phase &= 0x3ff; + if (phase & 0x200) + { + out = 0x1000; + } + else if (phase & 0x100) + { + out = logsinrom[(phase & 0xffu) ^ 0xffu]; + } + else + { + out = logsinrom[phase & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)); +} + +static int16_t OPL3_EnvelopeCalcSin2(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + phase &= 0x3ff; + if (phase & 0x100) + { + out = logsinrom[(phase & 0xffu) ^ 0xffu]; + } + else + { + out = logsinrom[phase & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)); +} + +static int16_t OPL3_EnvelopeCalcSin3(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + phase &= 0x3ff; + if (phase & 0x100) + { + out = 0x1000; + } + else + { + out = logsinrom[phase & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)); +} + +static int16_t OPL3_EnvelopeCalcSin4(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + uint16_t neg = 0; + phase &= 0x3ff; + if ((phase & 0x300) == 0x100) + { + neg = 0xffff; + } + if (phase & 0x200) + { + out = 0x1000; + } + else if (phase & 0x80) + { + out = logsinrom[((phase ^ 0xffu) << 1u) & 0xffu]; + } + else + { + out = logsinrom[(phase << 1u) & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; +} + +static int16_t OPL3_EnvelopeCalcSin5(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + phase &= 0x3ff; + if (phase & 0x200) + { + out = 0x1000; + } + else if (phase & 0x80) + { + out = logsinrom[((phase ^ 0xffu) << 1u) & 0xffu]; + } + else + { + out = logsinrom[(phase << 1u) & 0xffu]; + } + return OPL3_EnvelopeCalcExp(out + (envelope << 3)); +} + +static int16_t OPL3_EnvelopeCalcSin6(uint16_t phase, uint16_t envelope) +{ + uint16_t neg = 0; + phase &= 0x3ff; + if (phase & 0x200) + { + neg = 0xffff; + } + return OPL3_EnvelopeCalcExp(envelope << 3) ^ neg; +} + +static int16_t OPL3_EnvelopeCalcSin7(uint16_t phase, uint16_t envelope) +{ + uint16_t out = 0; + uint16_t neg = 0; + phase &= 0x3ff; + if (phase & 0x200) + { + neg = 0xffff; + phase = (phase & 0x1ff) ^ 0x1ff; + } + out = phase << 3; + return OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg; +} + +static const envelope_sinfunc envelope_sin[8] = { + OPL3_EnvelopeCalcSin0, + OPL3_EnvelopeCalcSin1, + OPL3_EnvelopeCalcSin2, + OPL3_EnvelopeCalcSin3, + OPL3_EnvelopeCalcSin4, + OPL3_EnvelopeCalcSin5, + OPL3_EnvelopeCalcSin6, + OPL3_EnvelopeCalcSin7 +}; + +enum envelope_gen_num +{ + envelope_gen_num_attack = 0, + envelope_gen_num_decay = 1, + envelope_gen_num_sustain = 2, + envelope_gen_num_release = 3 +}; + +static void OPL3_EnvelopeUpdateKSL(opl3_slot *slot) +{ + int16_t ksl = (kslrom[slot->channel->f_num >> 6u] << 2) + - ((0x08 - slot->channel->block) << 5); + if (ksl < 0) + { + ksl = 0; + } + slot->eg_ksl = (uint8_t)ksl; +} + +static void OPL3_EnvelopeCalc(opl3_slot *slot) +{ + uint8_t nonzero; + uint8_t rate; + uint8_t rate_hi; + uint8_t rate_lo; + uint8_t reg_rate = 0; + uint8_t ks; + uint8_t eg_shift, shift; + uint16_t eg_rout; + int16_t eg_inc; + uint8_t eg_off; + uint8_t reset = 0; + slot->eg_out = slot->eg_rout + (slot->reg_tl << 2) + + (slot->eg_ksl >> kslshift[slot->reg_ksl]) + *slot->trem; + if (slot->key && slot->eg_gen == envelope_gen_num_release) + { + reset = 1; + reg_rate = slot->reg_ar; + } + else + { + switch (slot->eg_gen) + { + case envelope_gen_num_attack: + reg_rate = slot->reg_ar; + break; + case envelope_gen_num_decay: + reg_rate = slot->reg_dr; + break; + case envelope_gen_num_sustain: + if (!slot->reg_type) + { + reg_rate = slot->reg_rr; + } + break; + case envelope_gen_num_release: + reg_rate = slot->reg_rr; + break; + } + } + slot->pg_reset = reset; + ks = slot->channel->ksv >> ((slot->reg_ksr ^ 1) << 1); + nonzero = (reg_rate != 0); + rate = ks + (reg_rate << 2); + rate_hi = rate >> 2; + rate_lo = rate & 0x03; + if (rate_hi & 0x10) + { + rate_hi = 0x0f; + } + eg_shift = rate_hi + slot->chip->eg_add; + shift = 0; + if (nonzero) + { + if (rate_hi < 12) + { + if (slot->chip->eg_state) + { + switch (eg_shift) + { + case 12: + shift = 1; + break; + case 13: + shift = (rate_lo >> 1) & 0x01; + break; + case 14: + shift = rate_lo & 0x01; + break; + default: + break; + } + } + } + else + { + shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->eg_timer_lo]; + if (shift & 0x04) + { + shift = 0x03; + } + if (!shift) + { + shift = slot->chip->eg_state; + } + } + } + eg_rout = slot->eg_rout; + eg_inc = 0; + eg_off = 0; + /* Instant attack */ + if (reset && rate_hi == 0x0f) + { + eg_rout = 0x00; + } + /* Envelope off */ + if ((slot->eg_rout & 0x1f8) == 0x1f8) + { + eg_off = 1; + } + if (slot->eg_gen != envelope_gen_num_attack && !reset && eg_off) + { + eg_rout = 0x1ff; + } + switch (slot->eg_gen) + { + case envelope_gen_num_attack: + if (!slot->eg_rout) + { + slot->eg_gen = envelope_gen_num_decay; + } + else if (slot->key && shift > 0 && rate_hi != 0x0f) + { + eg_inc = ~slot->eg_rout >> (4 - shift); + } + break; + case envelope_gen_num_decay: + if ((slot->eg_rout >> 4) == slot->reg_sl) + { + slot->eg_gen = envelope_gen_num_sustain; + } + else if (!eg_off && !reset && shift > 0) + { + eg_inc = 1 << (shift - 1); + } + break; + case envelope_gen_num_sustain: + case envelope_gen_num_release: + if (!eg_off && !reset && shift > 0) + { + eg_inc = 1 << (shift - 1); + } + break; + } + slot->eg_rout = (eg_rout + eg_inc) & 0x1ff; + /* Key off */ + if (reset) + { + slot->eg_gen = envelope_gen_num_attack; + } + if (!slot->key) + { + slot->eg_gen = envelope_gen_num_release; + } +} + +static void OPL3_EnvelopeKeyOn(opl3_slot *slot, uint8_t type) +{ + slot->key |= type; +} + +static void OPL3_EnvelopeKeyOff(opl3_slot *slot, uint8_t type) +{ + slot->key &= ~type; +} + +/* + Phase Generator +*/ + +static void OPL3_PhaseGenerate(opl3_slot *slot) +{ + opl3_chip *chip; + uint16_t f_num; + uint32_t basefreq; + uint8_t rm_xor, n_bit; + uint32_t noise; + uint16_t phase; + + chip = slot->chip; + f_num = slot->channel->f_num; + if (slot->reg_vib) + { + int8_t range; + uint8_t vibpos; + + range = (f_num >> 7) & 7; + vibpos = slot->chip->vibpos; + + if (!(vibpos & 3)) + { + range = 0; + } + else if (vibpos & 1) + { + range >>= 1; + } + range >>= slot->chip->vibshift; + + if (vibpos & 4) + { + range = -range; + } + f_num += range; + } + basefreq = (f_num << slot->channel->block) >> 1; + phase = (uint16_t)(slot->pg_phase >> 9); + if (slot->pg_reset) + { + slot->pg_phase = 0; + } + slot->pg_phase += (basefreq * mt[slot->reg_mult]) >> 1; + /* Rhythm mode */ + noise = chip->noise; + slot->pg_phase_out = phase; + if (slot->slot_num == 13) /* hh */ + { + chip->rm_hh_bit2 = (phase >> 2) & 1; + chip->rm_hh_bit3 = (phase >> 3) & 1; + chip->rm_hh_bit7 = (phase >> 7) & 1; + chip->rm_hh_bit8 = (phase >> 8) & 1; + } + if (slot->slot_num == 17 && (chip->rhy & 0x20)) /* tc */ + { + chip->rm_tc_bit3 = (phase >> 3) & 1; + chip->rm_tc_bit5 = (phase >> 5) & 1; + } + if (chip->rhy & 0x20) + { + rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7) + | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5) + | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5); + switch (slot->slot_num) + { + case 13: /* hh */ + slot->pg_phase_out = rm_xor << 9; + if (rm_xor ^ (noise & 1)) + { + slot->pg_phase_out |= 0xd0; + } + else + { + slot->pg_phase_out |= 0x34; + } + break; + case 16: /* sd */ + slot->pg_phase_out = (chip->rm_hh_bit8 << 9) + | ((chip->rm_hh_bit8 ^ (noise & 1)) << 8); + break; + case 17: /* tc */ + slot->pg_phase_out = (rm_xor << 9) | 0x80; + break; + default: + break; + } + } + n_bit = ((noise >> 14) ^ noise) & 0x01; + chip->noise = (noise >> 1) | (n_bit << 22); +} + +/* + Slot +*/ + +static void OPL3_SlotWrite20(opl3_slot *slot, uint8_t data) +{ + if ((data >> 7) & 0x01) + { + slot->trem = &slot->chip->tremolo; + } + else + { + slot->trem = (uint8_t*)&slot->chip->zeromod; + } + slot->reg_vib = (data >> 6) & 0x01; + slot->reg_type = (data >> 5) & 0x01; + slot->reg_ksr = (data >> 4) & 0x01; + slot->reg_mult = data & 0x0f; +} + +static void OPL3_SlotWrite40(opl3_slot *slot, uint8_t data) +{ + slot->reg_ksl = (data >> 6) & 0x03; + slot->reg_tl = data & 0x3f; + OPL3_EnvelopeUpdateKSL(slot); +} + +static void OPL3_SlotWrite60(opl3_slot *slot, uint8_t data) +{ + slot->reg_ar = (data >> 4) & 0x0f; + slot->reg_dr = data & 0x0f; +} + +static void OPL3_SlotWrite80(opl3_slot *slot, uint8_t data) +{ + slot->reg_sl = (data >> 4) & 0x0f; + if (slot->reg_sl == 0x0f) + { + slot->reg_sl = 0x1f; + } + slot->reg_rr = data & 0x0f; +} + +static void OPL3_SlotWriteE0(opl3_slot *slot, uint8_t data) +{ + slot->reg_wf = data & 0x07; + if (slot->chip->newm == 0x00) + { + slot->reg_wf &= 0x03; + } +} + +static void OPL3_SlotGenerate(opl3_slot *slot) +{ + slot->out = envelope_sin[slot->reg_wf](slot->pg_phase_out + *slot->mod, slot->eg_out); +} + +static void OPL3_SlotCalcFB(opl3_slot *slot) +{ + if (slot->channel->fb != 0x00) + { + slot->fbmod = (slot->prout + slot->out) >> (0x09 - slot->channel->fb); + } + else + { + slot->fbmod = 0; + } + slot->prout = slot->out; +} + +/* + Channel +*/ + +static void OPL3_ChannelSetupAlg(opl3_channel *channel); + +static void OPL3_ChannelUpdateRhythm(opl3_chip *chip, uint8_t data) +{ + opl3_channel *channel6; + opl3_channel *channel7; + opl3_channel *channel8; + uint8_t chnum; + + chip->rhy = data & 0x3f; + if (chip->rhy & 0x20) + { + channel6 = &chip->channel[6]; + channel7 = &chip->channel[7]; + channel8 = &chip->channel[8]; + channel6->out[0] = &channel6->slotz[1]->out; + channel6->out[1] = &channel6->slotz[1]->out; + channel6->out[2] = &chip->zeromod; + channel6->out[3] = &chip->zeromod; + channel7->out[0] = &channel7->slotz[0]->out; + channel7->out[1] = &channel7->slotz[0]->out; + channel7->out[2] = &channel7->slotz[1]->out; + channel7->out[3] = &channel7->slotz[1]->out; + channel8->out[0] = &channel8->slotz[0]->out; + channel8->out[1] = &channel8->slotz[0]->out; + channel8->out[2] = &channel8->slotz[1]->out; + channel8->out[3] = &channel8->slotz[1]->out; + for (chnum = 6; chnum < 9; chnum++) + { + chip->channel[chnum].chtype = ch_drum; + } + OPL3_ChannelSetupAlg(channel6); + OPL3_ChannelSetupAlg(channel7); + OPL3_ChannelSetupAlg(channel8); + /* hh */ + if (chip->rhy & 0x01) + { + OPL3_EnvelopeKeyOn(channel7->slotz[0], egk_drum); + } + else + { + OPL3_EnvelopeKeyOff(channel7->slotz[0], egk_drum); + } + /* tc */ + if (chip->rhy & 0x02) + { + OPL3_EnvelopeKeyOn(channel8->slotz[1], egk_drum); + } + else + { + OPL3_EnvelopeKeyOff(channel8->slotz[1], egk_drum); + } + /* tom */ + if (chip->rhy & 0x04) + { + OPL3_EnvelopeKeyOn(channel8->slotz[0], egk_drum); + } + else + { + OPL3_EnvelopeKeyOff(channel8->slotz[0], egk_drum); + } + /* sd */ + if (chip->rhy & 0x08) + { + OPL3_EnvelopeKeyOn(channel7->slotz[1], egk_drum); + } + else + { + OPL3_EnvelopeKeyOff(channel7->slotz[1], egk_drum); + } + /* bd */ + if (chip->rhy & 0x10) + { + OPL3_EnvelopeKeyOn(channel6->slotz[0], egk_drum); + OPL3_EnvelopeKeyOn(channel6->slotz[1], egk_drum); + } + else + { + OPL3_EnvelopeKeyOff(channel6->slotz[0], egk_drum); + OPL3_EnvelopeKeyOff(channel6->slotz[1], egk_drum); + } + } + else + { + for (chnum = 6; chnum < 9; chnum++) + { + chip->channel[chnum].chtype = ch_2op; + OPL3_ChannelSetupAlg(&chip->channel[chnum]); + OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[0], egk_drum); + OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[1], egk_drum); + } + } +} + +static void OPL3_ChannelUpdateFrequency(opl3_channel *channel) +{ + channel->ksv = (channel->block << 1) + | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); + OPL3_EnvelopeUpdateKSL(channel->slotz[0]); + OPL3_EnvelopeUpdateKSL(channel->slotz[1]); +} + +static void OPL3_ChannelRestoreFrequency(opl3_channel *channel) +{ + channel->f_num = channel->f_num_reg; + channel->block = channel->block_reg; + OPL3_ChannelUpdateFrequency(channel); +} + +static void OPL3_ChannelSync4Op(opl3_channel *channel) +{ + channel->pair->f_num = channel->f_num; + channel->pair->block = channel->block; + OPL3_ChannelUpdateFrequency(channel->pair); +} + +static void OPL3_ChannelWriteA0(opl3_channel *channel, uint8_t data) +{ + channel->f_num_reg = (channel->f_num_reg & 0x300) | data; + if (channel->chtype == ch_4op2) + { + return; + } + OPL3_ChannelRestoreFrequency(channel); + if (channel->chtype == ch_4op) + { + OPL3_ChannelSync4Op(channel); + } +} + +static void OPL3_ChannelWriteB0(opl3_channel *channel, uint8_t data) +{ + channel->f_num_reg = (channel->f_num_reg & 0xff) | ((data & 0x03) << 8); + channel->block_reg = (data >> 2) & 0x07; + if (channel->chtype == ch_4op2) + { + return; + } + OPL3_ChannelRestoreFrequency(channel); + if (channel->chtype == ch_4op) + { + OPL3_ChannelSync4Op(channel); + } +} + +static void OPL3_ChannelSetupAlg(opl3_channel *channel) +{ + if (channel->chtype == ch_drum) + { + if (channel->ch_num == 7 || channel->ch_num == 8) + { + channel->slotz[0]->mod = &channel->chip->zeromod; + channel->slotz[1]->mod = &channel->chip->zeromod; + return; + } + switch (channel->alg & 0x01) + { + case 0x00: + channel->slotz[0]->mod = &channel->slotz[0]->fbmod; + channel->slotz[1]->mod = &channel->slotz[0]->out; + break; + case 0x01: + channel->slotz[0]->mod = &channel->slotz[0]->fbmod; + channel->slotz[1]->mod = &channel->chip->zeromod; + break; + } + return; + } + if (channel->alg & 0x08) + { + return; + } + if (channel->alg & 0x04) + { + channel->pair->out[0] = &channel->chip->zeromod; + channel->pair->out[1] = &channel->chip->zeromod; + channel->pair->out[2] = &channel->chip->zeromod; + channel->pair->out[3] = &channel->chip->zeromod; + switch (channel->alg & 0x03) + { + case 0x00: + channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; + channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out; + channel->slotz[0]->mod = &channel->pair->slotz[1]->out; + channel->slotz[1]->mod = &channel->slotz[0]->out; + channel->out[0] = &channel->slotz[1]->out; + channel->out[1] = &channel->chip->zeromod; + channel->out[2] = &channel->chip->zeromod; + channel->out[3] = &channel->chip->zeromod; + break; + case 0x01: + channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; + channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out; + channel->slotz[0]->mod = &channel->chip->zeromod; + channel->slotz[1]->mod = &channel->slotz[0]->out; + channel->out[0] = &channel->pair->slotz[1]->out; + channel->out[1] = &channel->slotz[1]->out; + channel->out[2] = &channel->chip->zeromod; + channel->out[3] = &channel->chip->zeromod; + break; + case 0x02: + channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; + channel->pair->slotz[1]->mod = &channel->chip->zeromod; + channel->slotz[0]->mod = &channel->pair->slotz[1]->out; + channel->slotz[1]->mod = &channel->slotz[0]->out; + channel->out[0] = &channel->pair->slotz[0]->out; + channel->out[1] = &channel->slotz[1]->out; + channel->out[2] = &channel->chip->zeromod; + channel->out[3] = &channel->chip->zeromod; + break; + case 0x03: + channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; + channel->pair->slotz[1]->mod = &channel->chip->zeromod; + channel->slotz[0]->mod = &channel->pair->slotz[1]->out; + channel->slotz[1]->mod = &channel->chip->zeromod; + channel->out[0] = &channel->pair->slotz[0]->out; + channel->out[1] = &channel->slotz[0]->out; + channel->out[2] = &channel->slotz[1]->out; + channel->out[3] = &channel->chip->zeromod; + break; + } + } + else + { + switch (channel->alg & 0x01) + { + case 0x00: + channel->slotz[0]->mod = &channel->slotz[0]->fbmod; + channel->slotz[1]->mod = &channel->slotz[0]->out; + channel->out[0] = &channel->slotz[1]->out; + channel->out[1] = &channel->chip->zeromod; + channel->out[2] = &channel->chip->zeromod; + channel->out[3] = &channel->chip->zeromod; + break; + case 0x01: + channel->slotz[0]->mod = &channel->slotz[0]->fbmod; + channel->slotz[1]->mod = &channel->chip->zeromod; + channel->out[0] = &channel->slotz[0]->out; + channel->out[1] = &channel->slotz[1]->out; + channel->out[2] = &channel->chip->zeromod; + channel->out[3] = &channel->chip->zeromod; + break; + } + } +} + +static void OPL3_ChannelUpdateAlg(opl3_channel *channel) +{ + channel->alg = channel->con; + if (channel->chtype == ch_4op) + { + channel->pair->alg = 0x04 | (channel->con << 1) | (channel->pair->con); + channel->alg = 0x08; + OPL3_ChannelSetupAlg(channel->pair); + } + else if (channel->chtype == ch_4op2) + { + channel->alg = 0x04 | (channel->pair->con << 1) | (channel->con); + channel->pair->alg = 0x08; + OPL3_ChannelSetupAlg(channel); + } + else + { + OPL3_ChannelSetupAlg(channel); + } +} + +static void OPL3_ChannelWriteC0(opl3_channel *channel, uint8_t data) +{ + channel->fb = (data & 0x0e) >> 1; + channel->con = data & 0x01; + OPL3_ChannelUpdateAlg(channel); + if (channel->chip->newm) + { + channel->cha = ((data >> 4) & 0x01) ? ~0 : 0; + channel->chb = ((data >> 5) & 0x01) ? ~0 : 0; + channel->chc = ((data >> 6) & 0x01) ? ~0 : 0; + channel->chd = ((data >> 7) & 0x01) ? ~0 : 0; + } + else + { + channel->cha = channel->chb = (uint16_t)~0; + channel->chc = channel->chd = 0; + } +#if OPL_ENABLE_STEREOEXT + if (!channel->chip->stereoext) + { + channel->leftpan = channel->cha << 16; + channel->rightpan = channel->chb << 16; + } +#endif +} + +#if OPL_ENABLE_STEREOEXT +static void OPL3_ChannelWriteD0(opl3_channel* channel, uint8_t data) +{ + if (channel->chip->stereoext) + { + channel->leftpan = panpot_lut[data ^ 0xffu]; + channel->rightpan = panpot_lut[data]; + } +} +#endif + +static void OPL3_ChannelKeyOn(opl3_channel *channel) +{ + if (channel->chtype == ch_4op) + { + OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm); + OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm); + OPL3_EnvelopeKeyOn(channel->pair->slotz[0], egk_norm); + OPL3_EnvelopeKeyOn(channel->pair->slotz[1], egk_norm); + } + else if (channel->chtype == ch_2op || channel->chtype == ch_drum) + { + OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm); + OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm); + } +} + +static void OPL3_ChannelKeyOff(opl3_channel *channel) +{ + if (channel->chtype == ch_4op) + { + OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm); + OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm); + OPL3_EnvelopeKeyOff(channel->pair->slotz[0], egk_norm); + OPL3_EnvelopeKeyOff(channel->pair->slotz[1], egk_norm); + } + else if (channel->chtype == ch_2op || channel->chtype == ch_drum) + { + OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm); + OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm); + } +} + +static void OPL3_ChannelSet4Op(opl3_chip *chip, uint8_t data) +{ + uint8_t bit; + uint8_t chnum; + for (bit = 0; bit < 6; bit++) + { + chnum = bit; + if (bit >= 3) + { + chnum += 9 - 3; + } + if ((data >> bit) & 0x01) + { + chip->channel[chnum].chtype = ch_4op; + chip->channel[chnum + 3u].chtype = ch_4op2; + OPL3_ChannelSync4Op(&chip->channel[chnum]); + OPL3_ChannelUpdateAlg(&chip->channel[chnum]); + } + else + { + chip->channel[chnum].chtype = ch_2op; + chip->channel[chnum + 3u].chtype = ch_2op; + OPL3_ChannelRestoreFrequency(&chip->channel[chnum + 3u]); + OPL3_ChannelUpdateAlg(&chip->channel[chnum]); + OPL3_ChannelUpdateAlg(&chip->channel[chnum + 3u]); + } + } +} + +static int16_t OPL3_ClipSample(int32_t sample) +{ + if (sample > 32767) + { + sample = 32767; + } + else if (sample < -32768) + { + sample = -32768; + } + return (int16_t)sample; +} + +static void OPL3_ProcessSlot(opl3_slot *slot) +{ + OPL3_SlotCalcFB(slot); + OPL3_EnvelopeCalc(slot); + OPL3_PhaseGenerate(slot); + OPL3_SlotGenerate(slot); +} + +inline void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4) +{ + opl3_channel *channel; + opl3_writebuf *writebuf; + int16_t **out; + int32_t mix[2]; + uint8_t ii; + int16_t accm; + uint8_t shift = 0; + + buf4[1] = OPL3_ClipSample(chip->mixbuff[1]); + buf4[3] = OPL3_ClipSample(chip->mixbuff[3]); + +#if OPL_QUIRK_CHANNELSAMPLEDELAY + for (ii = 0; ii < 15; ii++) +#else + for (ii = 0; ii < 36; ii++) +#endif + { + OPL3_ProcessSlot(&chip->slot[ii]); + } + + mix[0] = mix[1] = 0; + for (ii = 0; ii < 18; ii++) + { + channel = &chip->channel[ii]; + out = channel->out; + accm = *out[0] + *out[1] + *out[2] + *out[3]; +#if OPL_ENABLE_STEREOEXT + mix[0] += (int16_t)((accm * channel->leftpan) >> 16); +#else + mix[0] += (int16_t)(accm & channel->cha); +#endif + mix[1] += (int16_t)(accm & channel->chc); + } + chip->mixbuff[0] = mix[0]; + chip->mixbuff[2] = mix[1]; + +#if OPL_QUIRK_CHANNELSAMPLEDELAY + for (ii = 15; ii < 18; ii++) + { + OPL3_ProcessSlot(&chip->slot[ii]); + } +#endif + + buf4[0] = OPL3_ClipSample(chip->mixbuff[0]); + buf4[2] = OPL3_ClipSample(chip->mixbuff[2]); + +#if OPL_QUIRK_CHANNELSAMPLEDELAY + for (ii = 18; ii < 33; ii++) + { + OPL3_ProcessSlot(&chip->slot[ii]); + } +#endif + + mix[0] = mix[1] = 0; + for (ii = 0; ii < 18; ii++) + { + channel = &chip->channel[ii]; + out = channel->out; + accm = *out[0] + *out[1] + *out[2] + *out[3]; +#if OPL_ENABLE_STEREOEXT + mix[0] += (int16_t)((accm * channel->rightpan) >> 16); +#else + mix[0] += (int16_t)(accm & channel->chb); + #endif + mix[1] += (int16_t)(accm & channel->chd); + } + chip->mixbuff[1] = mix[0]; + chip->mixbuff[3] = mix[1]; + +#if OPL_QUIRK_CHANNELSAMPLEDELAY + for (ii = 33; ii < 36; ii++) + { + OPL3_ProcessSlot(&chip->slot[ii]); + } +#endif + + if ((chip->timer & 0x3f) == 0x3f) + { + chip->tremolopos = (chip->tremolopos + 1) % 210; + } + if (chip->tremolopos < 105) + { + chip->tremolo = chip->tremolopos >> chip->tremoloshift; + } + else + { + chip->tremolo = (210 - chip->tremolopos) >> chip->tremoloshift; + } + + if ((chip->timer & 0x3ff) == 0x3ff) + { + chip->vibpos = (chip->vibpos + 1) & 7; + } + + chip->timer++; + + if (chip->eg_state) + { + while (shift < 13 && ((chip->eg_timer >> shift) & 1) == 0) + { + shift++; + } + if (shift > 12) + { + chip->eg_add = 0; + } + else + { + chip->eg_add = shift + 1; + } + chip->eg_timer_lo = (uint8_t)(chip->eg_timer & 0x3u); + } + + if (chip->eg_timerrem || chip->eg_state) + { + if (chip->eg_timer == UINT64_C(0xfffffffff)) + { + chip->eg_timer = 0; + chip->eg_timerrem = 1; + } + else + { + chip->eg_timer++; + chip->eg_timerrem = 0; + } + } + + chip->eg_state ^= 1; + + while ((writebuf = &chip->writebuf[chip->writebuf_cur]), writebuf->time <= chip->writebuf_samplecnt) + { + if (!(writebuf->reg & 0x200)) + { + break; + } + writebuf->reg &= 0x1ff; + OPL3_WriteReg(chip, writebuf->reg, writebuf->data); + chip->writebuf_cur = (chip->writebuf_cur + 1) % OPL_WRITEBUF_SIZE; + } + chip->writebuf_samplecnt++; +} + +void OPL3_Generate(opl3_chip *chip, int16_t *buf) +{ + int16_t samples[4]; + OPL3_Generate4Ch(chip, samples); + buf[0] = samples[0]; + buf[1] = samples[1]; +} + +void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4) +{ + while (chip->samplecnt >= chip->rateratio) + { + chip->oldsamples[0] = chip->samples[0]; + chip->oldsamples[1] = chip->samples[1]; + chip->oldsamples[2] = chip->samples[2]; + chip->oldsamples[3] = chip->samples[3]; + OPL3_Generate4Ch(chip, chip->samples); + chip->samplecnt -= chip->rateratio; + } + buf4[0] = (int16_t)((chip->oldsamples[0] * (chip->rateratio - chip->samplecnt) + + chip->samples[0] * chip->samplecnt) / chip->rateratio); + buf4[1] = (int16_t)((chip->oldsamples[1] * (chip->rateratio - chip->samplecnt) + + chip->samples[1] * chip->samplecnt) / chip->rateratio); + buf4[2] = (int16_t)((chip->oldsamples[2] * (chip->rateratio - chip->samplecnt) + + chip->samples[2] * chip->samplecnt) / chip->rateratio); + buf4[3] = (int16_t)((chip->oldsamples[3] * (chip->rateratio - chip->samplecnt) + + chip->samples[3] * chip->samplecnt) / chip->rateratio); + chip->samplecnt += 1 << RSM_FRAC; +} + +void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf) +{ + int16_t samples[4]; + OPL3_Generate4ChResampled(chip, samples); + buf[0] = samples[0]; + buf[1] = samples[1]; +} + +void OPL3_Reset(opl3_chip *chip, uint32_t samplerate) +{ + opl3_slot *slot; + opl3_channel *channel; + uint8_t slotnum; + uint8_t channum; + uint8_t local_ch_slot; + + memset(chip, 0, sizeof(opl3_chip)); + for (slotnum = 0; slotnum < 36; slotnum++) + { + slot = &chip->slot[slotnum]; + slot->chip = chip; + slot->mod = &chip->zeromod; + slot->eg_rout = 0x1ff; + slot->eg_out = 0x1ff; + slot->eg_gen = envelope_gen_num_release; + slot->trem = (uint8_t*)&chip->zeromod; + slot->slot_num = slotnum; + } + for (channum = 0; channum < 18; channum++) + { + channel = &chip->channel[channum]; + local_ch_slot = ch_slot[channum]; + channel->slotz[0] = &chip->slot[local_ch_slot]; + channel->slotz[1] = &chip->slot[local_ch_slot + 3u]; + chip->slot[local_ch_slot].channel = channel; + chip->slot[local_ch_slot + 3u].channel = channel; + if ((channum % 9) < 3) + { + channel->pair = &chip->channel[channum + 3u]; + } + else if ((channum % 9) < 6) + { + channel->pair = &chip->channel[channum - 3u]; + } + channel->chip = chip; + channel->out[0] = &chip->zeromod; + channel->out[1] = &chip->zeromod; + channel->out[2] = &chip->zeromod; + channel->out[3] = &chip->zeromod; + channel->chtype = ch_2op; + channel->cha = 0xffff; + channel->chb = 0xffff; +#if OPL_ENABLE_STEREOEXT + channel->leftpan = 0x10000; + channel->rightpan = 0x10000; +#endif + channel->ch_num = channum; + OPL3_ChannelSetupAlg(channel); + } + chip->noise = 1; + chip->rateratio = (samplerate << RSM_FRAC) / 49716; + chip->tremoloshift = 4; + chip->vibshift = 1; + +#if OPL_ENABLE_STEREOEXT + if (!panpot_lut_build) + { + int32_t i; + for (i = 0; i < 256; i++) + { + panpot_lut[i] = OPL_SIN(i); + } + panpot_lut_build = 1; + } +#endif +} + +void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v) +{ + uint8_t high = (reg >> 8) & 0x01; + uint8_t regm = reg & 0xff; + switch (regm & 0xf0) + { + case 0x00: + if (high) + { + switch (regm & 0x0f) + { + case 0x04: + OPL3_ChannelSet4Op(chip, v); + break; + case 0x05: + chip->newm = v & 0x01; +#if OPL_ENABLE_STEREOEXT + chip->stereoext = (v >> 1) & 0x01; +#endif + break; + } + } + else + { + switch (regm & 0x0f) + { + case 0x08: + chip->nts = (v >> 6) & 0x01; + break; + } + } + break; + case 0x20: + case 0x30: + if (ad_slot[regm & 0x1fu] >= 0) + { + OPL3_SlotWrite20(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v); + } + break; + case 0x40: + case 0x50: + if (ad_slot[regm & 0x1fu] >= 0) + { + OPL3_SlotWrite40(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v); + } + break; + case 0x60: + case 0x70: + if (ad_slot[regm & 0x1fu] >= 0) + { + OPL3_SlotWrite60(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v); + } + break; + case 0x80: + case 0x90: + if (ad_slot[regm & 0x1fu] >= 0) + { + OPL3_SlotWrite80(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v); + } + break; + case 0xe0: + case 0xf0: + if (ad_slot[regm & 0x1fu] >= 0) + { + OPL3_SlotWriteE0(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v); + } + break; + case 0xa0: + if ((regm & 0x0f) < 9) + { + OPL3_ChannelWriteA0(&chip->channel[9u * high + (regm & 0x0fu)], v); + } + break; + case 0xb0: + if (regm == 0xbd && !high) + { + chip->tremoloshift = (((v >> 7) ^ 1) << 1) + 2; + chip->vibshift = ((v >> 6) & 0x01) ^ 1; + OPL3_ChannelUpdateRhythm(chip, v); + } + else if ((regm & 0x0f) < 9) + { + OPL3_ChannelWriteB0(&chip->channel[9u * high + (regm & 0x0fu)], v); + if (v & 0x20) + { + OPL3_ChannelKeyOn(&chip->channel[9u * high + (regm & 0x0fu)]); + } + else + { + OPL3_ChannelKeyOff(&chip->channel[9u * high + (regm & 0x0fu)]); + } + } + break; + case 0xc0: + if ((regm & 0x0f) < 9) + { + OPL3_ChannelWriteC0(&chip->channel[9u * high + (regm & 0x0fu)], v); + } + break; +#if OPL_ENABLE_STEREOEXT + case 0xd0: + if ((regm & 0x0f) < 9) + { + OPL3_ChannelWriteD0(&chip->channel[9u * high + (regm & 0x0fu)], v); + } + break; +#endif + } +} + +void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v) +{ + uint64_t time1, time2; + opl3_writebuf *writebuf; + uint32_t writebuf_last; + + writebuf_last = chip->writebuf_last; + writebuf = &chip->writebuf[writebuf_last]; + + if (writebuf->reg & 0x200) + { + OPL3_WriteReg(chip, writebuf->reg & 0x1ff, writebuf->data); + + chip->writebuf_cur = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; + chip->writebuf_samplecnt = writebuf->time; + } + + writebuf->reg = reg | 0x200; + writebuf->data = v; + time1 = chip->writebuf_lasttime + OPL_WRITEBUF_DELAY; + time2 = chip->writebuf_samplecnt; + + if (time1 < time2) + { + time1 = time2; + } + + writebuf->time = time1; + chip->writebuf_lasttime = time1; + chip->writebuf_last = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; +} + +void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples) +{ + uint_fast32_t i; + int16_t samples[4]; + + for(i = 0; i < numsamples; i++) + { + OPL3_Generate4ChResampled(chip, samples); + sndptr1[0] = samples[0]; + sndptr1[1] = samples[1]; + sndptr2[0] = samples[2]; + sndptr2[1] = samples[3]; + sndptr1 += 2; + sndptr2 += 2; + } +} + +void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples) +{ + uint_fast32_t i; + + for(i = 0; i < numsamples; i++) + { + OPL3_GenerateResampled(chip, sndptr); + sndptr += 2; + } +} diff --git a/src/audio/third_party/nuked-opl3/opl3.h b/src/audio/third_party/nuked-opl3/opl3.h new file mode 100644 index 0000000..4abc29f --- /dev/null +++ b/src/audio/third_party/nuked-opl3/opl3.h @@ -0,0 +1,175 @@ +/* Nuked OPL3 + * Copyright (C) 2013-2020 Nuke.YKT + * + * This file is part of Nuked OPL3. + * + * Nuked OPL3 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 + * of the License, or (at your option) any later version. + * + * Nuked OPL3 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Nuked OPL3. If not, see . + + * Nuked OPL3 emulator. + * Thanks: + * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): + * Feedback and Rhythm part calculation information. + * forums.submarine.org.uk(carbon14, opl3): + * Tremolo and phase generator calculation information. + * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): + * OPL2 ROMs. + * siliconpr0n.org(John McMaster, digshadow): + * YMF262 and VRC VII decaps and die shots. + * + * version: 1.8 + */ + +#ifndef OPL_OPL3_H +#define OPL_OPL3_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifndef OPL_ENABLE_STEREOEXT +#define OPL_ENABLE_STEREOEXT 0 +#endif + +#define OPL_WRITEBUF_SIZE 1024 +#define OPL_WRITEBUF_DELAY 2 + +typedef struct _opl3_slot opl3_slot; +typedef struct _opl3_channel opl3_channel; +typedef struct _opl3_chip opl3_chip; + +struct _opl3_slot { + opl3_channel *channel; + opl3_chip *chip; + int16_t out; + int16_t fbmod; + int16_t *mod; + int16_t prout; + uint16_t eg_rout; + uint16_t eg_out; + uint8_t eg_inc; + uint8_t eg_gen; + uint8_t eg_rate; + uint8_t eg_ksl; + uint8_t *trem; + uint8_t reg_vib; + uint8_t reg_type; + uint8_t reg_ksr; + uint8_t reg_mult; + uint8_t reg_ksl; + uint8_t reg_tl; + uint8_t reg_ar; + uint8_t reg_dr; + uint8_t reg_sl; + uint8_t reg_rr; + uint8_t reg_wf; + uint8_t key; + uint32_t pg_reset; + uint32_t pg_phase; + uint16_t pg_phase_out; + uint8_t slot_num; +}; + +struct _opl3_channel { + opl3_slot *slotz[2];/*Don't use "slots" keyword to avoid conflict with Qt applications*/ + opl3_channel *pair; + opl3_chip *chip; + int16_t *out[4]; + +#if OPL_ENABLE_STEREOEXT + int32_t leftpan; + int32_t rightpan; +#endif + + uint8_t chtype; + uint16_t f_num; + uint16_t f_num_reg; + uint8_t block; + uint8_t block_reg; + uint8_t fb; + uint8_t con; + uint8_t alg; + uint8_t ksv; + uint16_t cha, chb; + uint16_t chc, chd; + uint8_t ch_num; +}; + +typedef struct _opl3_writebuf { + uint64_t time; + uint16_t reg; + uint8_t data; +} opl3_writebuf; + +struct _opl3_chip { + opl3_channel channel[18]; + opl3_slot slot[36]; + uint16_t timer; + uint64_t eg_timer; + uint8_t eg_timerrem; + uint8_t eg_state; + uint8_t eg_add; + uint8_t eg_timer_lo; + uint8_t newm; + uint8_t nts; + uint8_t rhy; + uint8_t vibpos; + uint8_t vibshift; + uint8_t tremolo; + uint8_t tremolopos; + uint8_t tremoloshift; + uint32_t noise; + int16_t zeromod; + int32_t mixbuff[4]; + uint8_t rm_hh_bit2; + uint8_t rm_hh_bit3; + uint8_t rm_hh_bit7; + uint8_t rm_hh_bit8; + uint8_t rm_tc_bit3; + uint8_t rm_tc_bit5; + +#if OPL_ENABLE_STEREOEXT + uint8_t stereoext; +#endif + + /* OPL3L */ + int32_t rateratio; + int32_t samplecnt; + int16_t oldsamples[4]; + int16_t samples[4]; + + uint64_t writebuf_samplecnt; + uint32_t writebuf_cur; + uint32_t writebuf_last; + uint64_t writebuf_lasttime; + opl3_writebuf writebuf[OPL_WRITEBUF_SIZE]; +}; + +void OPL3_Generate(opl3_chip *chip, int16_t *buf); +void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf); +void OPL3_Reset(opl3_chip *chip, uint32_t samplerate); +void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v); +void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v); +void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples); + +void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4); +void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4); +void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/audio/validation.cpp b/src/audio/validation.cpp new file mode 100644 index 0000000..150ddcb --- /dev/null +++ b/src/audio/validation.cpp @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "container.hpp" +#include "music_fallback.hpp" +#include "playback.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +#define CHECK(expr) do { if (!(expr)) { \ + std::cerr << "check failed at line " << __LINE__ << ": " << #expr << '\n'; \ + return 1; \ +} } while (false) +std::vector fixture() { + // Authored format header and payload, not bytes copied from a game asset. + return {'F','O','R','M', 17,0,0,0, 'A','L','P','T','R','A','U','M', + 'H','E','D','R', 1,0,0,0, 42}; +} + +std::vector sfx_fixture() { + std::vector bytes(65380, 0); + std::copy_n("FORM", 4, bytes.begin()); + const auto put32 = [&bytes](std::size_t at, std::uint32_t value) { + for (unsigned i = 0; i < 4; ++i) bytes[at + i] = static_cast(value >> (i * 8)); + }; + const auto put16 = [&bytes](std::size_t at, std::uint16_t value) { + bytes[at] = static_cast(value); + bytes[at + 1] = static_cast(value >> 8); + }; + put32(4, static_cast(bytes.size())); + std::copy_n("ALPTRAUM", 8, bytes.begin() + 8); + const auto chunk = [&bytes, &put32](std::size_t at, const char* id, std::uint32_t size) { + std::copy_n(id, 4, bytes.begin() + static_cast(at)); + put32(at + 4, size); + }; + chunk(16, "HEDR", 8); + chunk(32, "SEFX", 212); + bytes[42] = 7; + for (std::size_t i = 7; i < 13; ++i) { + const std::size_t row = 44 + i * 16; + bytes[row] = static_cast(16 + i - 7); + bytes[row + 1] = 9; + } + chunk(252, "INST", 228); + chunk(488, "SAMP", 64884); + const std::size_t samp = 496; + put16(samp + 2, 6); + const std::size_t data_at = samp + 4 + 6 * 16; + for (std::size_t i = 0; i < 6; ++i) { + const std::size_t row = samp + 4 + i * 16; + put16(row, static_cast(i * 2048)); + put16(row + 2, 2048); + put16(row + 8, 11025); + std::fill(bytes.begin() + static_cast(data_at + i * 2048), + bytes.begin() + static_cast(data_at + (i + 1) * 2048), + static_cast(128 + i)); + } + return bytes; +} +} + +int main(int, char**) { // (the SDL_main signature: SDL.h renames main on Windows) + using namespace openbmh::audio; + std::string error; + Container c; + auto good = fixture(); + CHECK(parse_container(good, c, error)); + CHECK(c.chunks.size() == 1 && c.chunks[0].id == "HEDR"); + CHECK(c.chunks[0].payload_size == 1 && good[c.chunks[0].payload_offset] == 42); + + auto broken = good; + broken[20] = 0xff; + broken[21] = 0xff; + broken[22] = 0xff; + broken[23] = 0x7f; + CHECK(!parse_container(broken, c, error)); + CHECK(c.chunks.empty()); + CHECK(!parse_container(std::span(good.data(), 15), c, error)); + + std::vector sefx(65380, 0); + const char form[] = "FORM"; + std::copy(form, form + 4, sefx.begin()); + sefx[4] = static_cast(sefx.size()); + sefx[5] = static_cast(sefx.size() >> 8); + const char type[] = "ALPTRAUM"; + std::copy(type, type + 8, sefx.begin() + 8); + std::size_t at = 16; + const auto put_chunk = [&](const char* id, std::uint32_t size, std::size_t& cursor) { + std::copy(id, id + 4, sefx.begin() + static_cast(cursor)); + sefx[cursor + 4] = static_cast(size); + sefx[cursor + 5] = static_cast(size >> 8); + cursor += 8 + size; + }; + put_chunk("HEDR", 8, at); + put_chunk("SEFX", 212, at); + sefx[42] = 7; // observed 2003 SEFX record-count field + put_chunk("INST", 228, at); + put_chunk("SAMP", 64884, at); + CHECK(at == sefx.size()); + CHECK(parse_container(sefx, c, error)); + CHECK(c.chunks.size() == 4 && c.chunks[1].id == "SEFX"); + auto wrong_exception = sefx; + wrong_exception[32] = 'S'; wrong_exception[33] = 'O'; + wrong_exception[34] = 'N'; wrong_exception[35] = 'G'; + CHECK(!parse_container(wrong_exception, c, error)); + auto wrong_type = good; + wrong_type[8] = 'X'; + CHECK(!parse_container(wrong_type, c, error)); + + std::vector samp(24, 0); + samp[2] = 1; + samp[6] = 4; + samp[12] = 0x22; samp[13] = 0x56; // 22050 Hz + samp[20] = 0; samp[21] = 128; samp[22] = 255; samp[23] = 128; + PcmSample pcm; + CHECK(decode_sample(samp, 0, pcm, error)); + CHECK(pcm.sample_rate == 22050 && pcm.mono.size() == 4); + CHECK(pcm.mono[0] == -32768 && pcm.mono[1] == 0 && pcm.mono[2] == 32512); + samp[6] = 0xff; samp[7] = 0xff; + CHECK(!decode_sample(samp, 0, pcm, error)); + CHECK(!decode_sample(samp, 1, pcm, error)); + + auto bank = sfx_fixture(); + OriginalCue original; + CHECK(decode_original_cue(bank, 17, original, error)); + CHECK(original.original_id == 17 && original.sefx_index == 7 && original.sample_index == 0); + CHECK(original.pcm.sample_rate == 11025 && original.pcm.mono.size() == 2048); + CHECK(original.pcm.mono.front() == 0); + CHECK(decode_original_cue(bank, 22, original, error)); + CHECK(original.sefx_index == 12 && original.sample_index == 5); + CHECK(!decode_original_cue(bank, 16, original, error)); + + CHECK(SDL_InitSubSystem(SDL_INIT_VIDEO) == 0); + Playback playback; + CHECK(playback.initialize(error)); + CHECK(playback.available()); + CHECK(!playback.music_active() && !playback.needs_pump()); + CHECK(!playback.pump(error)); // The optional music path is inactive by default. + playback.set_volume(2.0F); + CHECK(playback.volume() == 1.0F); + playback.set_volume(-1.0F); + CHECK(playback.volume() == 0.0F); + playback.set_volume(1.0F); + playback.set_volume(std::numeric_limits::quiet_NaN()); + CHECK(playback.volume() == 1.0F); + playback.set_volume(std::numeric_limits::infinity()); + CHECK(playback.volume() == 1.0F); + playback.set_muted(true); + CHECK(playback.muted()); + CHECK(playback.play_pcm(nullptr, 0, 22050, error)); // mute drops without queueing + playback.set_muted(false); + const std::int16_t sample[] = {0, 1000, -1000, 0}; + CHECK(playback.play_pcm(sample, 4, 22050, error)); + std::vector long_sample(22050, 1000); + CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error)); + CHECK(playback.queued_bytes() > 0); + playback.set_muted(true); + CHECK(playback.queued_bytes() == 0); + playback.set_muted(false); + CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error)); + CHECK(playback.queued_bytes() > 0); + + playback.reset_session(7); + CHECK(playback.queued_bytes() == 0); + playback.reset_session(7); // same session preserves the event watermark + CHECK(playback.load_original_bank(bank, error)); + + const CueRequest cue_a{7, 1, 17}; + CHECK(playback.submit(cue_a, error) == CueStatus::queued); + CHECK(playback.queued_bytes() > 0); + CHECK(playback.submit(cue_a, error) == CueStatus::duplicate); + CHECK(playback.submit(CueRequest{7, 2, 17}, error) == CueStatus::queued); + playback.set_muted(true); + const CueRequest muted{7, 3, 17}; + CHECK(playback.submit(muted, error) == CueStatus::muted); + playback.set_muted(false); + CHECK(playback.submit(muted, error) == CueStatus::duplicate); + playback.stop(); + CHECK(playback.submit(cue_a, error) == CueStatus::duplicate); + playback.reset_session(8); + CHECK(playback.submit(CueRequest{8, 1, 17}, error) == CueStatus::queued); + CHECK(playback.submit(CueRequest{7, 4, 17}, error) == CueStatus::invalid); + CHECK(playback.submit(CueRequest{8, 1, 17}, error) == CueStatus::duplicate); + + PcmSample kickoff_pcm, goal_pcm, final_pcm; + CHECK(synthesize_semantic_cue(SemanticCue::kickoff_whistle, kickoff_pcm, error)); + CHECK(synthesize_semantic_cue(SemanticCue::goal, goal_pcm, error)); + CHECK(synthesize_semantic_cue(SemanticCue::full_time_whistle, final_pcm, error)); + CHECK(kickoff_pcm.sample_rate == 22050 && goal_pcm.sample_rate == 22050 && + final_pcm.sample_rate == 22050); + CHECK(!kickoff_pcm.mono.empty() && !goal_pcm.mono.empty() && !final_pcm.mono.empty()); + CHECK(kickoff_pcm.mono != goal_pcm.mono && goal_pcm.mono != final_pcm.mono && + kickoff_pcm.mono != final_pcm.mono); + PcmSample matchday_loop, repeated_loop; + CHECK(synthesize_matchday_music_loop(matchday_loop, error)); + CHECK(synthesize_matchday_music_loop(repeated_loop, error)); + CHECK(matchday_loop.sample_rate == 22050); + CHECK(matchday_loop.mono.size() == 392000); // 8 bars, 4 beats, 108 BPM. + CHECK(matchday_loop.mono == repeated_loop.mono); // deterministic, no RNG. + CHECK(matchday_loop.mono.front() == 0 && matchday_loop.mono.back() == 0); + CHECK(std::any_of(matchday_loop.mono.begin(), matchday_loop.mono.end(), + [](std::int16_t value) { return value != 0; })); + + Mixer mixer; + PcmSample constant_music{22050, std::vector(8, 1000)}; + const std::int16_t voice_samples[] = {2000, 2000, 2000, 2000}; + CHECK(mixer.start_music_loop(constant_music, 22050, error)); + CHECK(mixer.add_voice(voice_samples, 22050, 22050, error)); + CHECK(mixer.active_voices() == 1); + std::int16_t mixed_block[2]{}; + CHECK(mixer.mix_block(mixed_block, 1.0F)); + CHECK(mixed_block[0] == 3000 && mixed_block[1] == 3000); // Cue overlays the loop. + mixer.stop_music(); + CHECK(!mixer.has_music() && mixer.active_voices() == 1); + std::int16_t voice_tail[4]{}; + CHECK(mixer.mix_block(voice_tail, 1.0F)); // stop_music leaves the cue voice alive. + CHECK(voice_tail[0] == 2000 && voice_tail[1] == 2000 && + voice_tail[2] == 0 && voice_tail[3] == 0); + CHECK(!mixer.active()); + mixer.clear(); + CHECK(mixer.start_music_loop(constant_music, 22050, error)); + for (int i = 0; i < 8; ++i) CHECK(mixer.add_voice(voice_samples, 22050, 22050, error)); + CHECK(mixer.active_voices() == 8); + CHECK(!mixer.add_voice(voice_samples, 22050, 22050, error)); + mixer.clear(); + static_assert(static_cast(SemanticCue::kickoff_whistle) == 1); + static_assert(static_cast(SemanticCue::goal) == 2); + static_assert(static_cast(SemanticCue::full_time_whistle) == 3); + playback.reset_session(9); + const SemanticCueRequest kickoff{9, 1, SemanticCue::kickoff_whistle}; + CHECK(playback.submit(kickoff, error) == CueStatus::queued); + CHECK(playback.queued_bytes() > 0); + CHECK(playback.submit(kickoff, error) == CueStatus::duplicate); + CHECK(playback.submit(SemanticCueRequest{9, 2, SemanticCue::kickoff_whistle}, error) == CueStatus::queued); + playback.set_muted(true); + const SemanticCueRequest muted_goal{9, 3, SemanticCue::goal}; + CHECK(playback.submit(muted_goal, error) == CueStatus::muted); + playback.set_muted(false); + CHECK(playback.submit(muted_goal, error) == CueStatus::duplicate); + CHECK(playback.submit(SemanticCueRequest{9, 4, SemanticCue::goal}, error) == CueStatus::queued); + playback.reset_session(10); + CHECK(playback.queued_bytes() == 0); + CHECK(playback.submit(SemanticCueRequest{10, 1, SemanticCue::full_time_whistle}, error) == CueStatus::queued); + CHECK(playback.queued_bytes() > 0); + + playback.reset_session(11); + CHECK(playback.submit(CueRequest{11, 1, 17}, error) == CueStatus::queued); + CHECK(playback.submit(SemanticCueRequest{11, 1, SemanticCue::goal}, error) == CueStatus::duplicate); + CHECK(playback.submit(SemanticCueRequest{11, 2, SemanticCue::goal}, error) == CueStatus::queued); + CHECK(playback.submit(CueRequest{11, 2, 17}, error) == CueStatus::duplicate); + CHECK(playback.submit(SemanticCueRequest{10, 3, SemanticCue::goal}, error) == CueStatus::invalid); + CHECK(playback.submit(CueRequest{11, 0, 17}, error) == CueStatus::invalid); + CHECK(playback.submit(SemanticCueRequest{11, 3, SemanticCue::full_time_whistle}, error) == CueStatus::queued); + + // Optional music is explicit. Cues submitted while it is active enter the + // mixer immediately; pump emits short mixed blocks, never a whole loop. + playback.reset_session(12); + CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error)); + CHECK(playback.queued_bytes() > 0); + CHECK(!playback.start_music_loop(matchday_loop, error)); // Reject >40ms legacy cue backlog. + CHECK(!playback.music_active()); + CHECK(playback.queued_bytes() > 0); // Existing queued cue was not discarded. + playback.stop(); + CHECK(!playback.needs_pump()); + CHECK(playback.start_music_loop(matchday_loop, error)); + CHECK(playback.pump(error)); + CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U); + // Refill after typical 60/30 Hz app ticks. This checks the bounded refill, + // not continuous audible output: the dummy backend is not a listening test. + for (const unsigned delay : {17U, 33U}) { + for (unsigned tick = 0; tick < 12; ++tick) { + SDL_Delay(delay); + CHECK(playback.pump(error)); + CHECK(error.empty()); + CHECK(playback.queued_bytes() > 0); + CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U); + } + } + CHECK(playback.submit(CueRequest{12, 1, 17}, error) == CueStatus::queued); + bool cue_pumped = false; + for (unsigned attempt = 0; attempt < 5 && !cue_pumped; ++attempt) { + cue_pumped = playback.pump(error); + if (cue_pumped) + CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U); + if (!cue_pumped) SDL_Delay(25); + } + CHECK(cue_pumped); + const SemanticCueRequest music_muted_event{12, 2, SemanticCue::goal}; + playback.set_muted(true); // Clears music and both queued and active voices. + CHECK(!playback.music_active()); + CHECK(!playback.pump(error)); + CHECK(playback.submit(music_muted_event, error) == CueStatus::muted); + playback.set_muted(false); + CHECK(playback.submit(music_muted_event, error) == CueStatus::duplicate); + CHECK(!playback.pump(error)); + + // A zero master volume still advances an already active voice silently. + playback.reset_session(13); + CHECK(playback.start_music_loop(matchday_loop, error)); + const std::int16_t short_voice[] = {1000, 1000, 1000, 1000}; + CHECK(playback.play_pcm(short_voice, 4, 22050, error)); + playback.set_volume(0.0F); + playback.stop_music(); + CHECK(playback.needs_pump()); + CHECK(playback.pump(error)); + CHECK(!playback.needs_pump()); + playback.set_volume(1.0F); + CHECK(!playback.pump(error)); // No delayed replay after restoring volume. + + playback.reset_session(13); + CHECK(!playback.music_active() && !playback.pump(error)); + CHECK(playback.start_music_loop(matchday_loop, error)); + CHECK(playback.needs_pump()); + playback.reset_session(14); // A real session change clears music and queue. + CHECK(!playback.music_active() && !playback.needs_pump() && playback.queued_bytes() == 0); + CHECK(playback.start_music_loop(matchday_loop, error)); + CHECK(playback.submit(CueRequest{14, 1, 17}, error) == CueStatus::queued); + playback.stop_music(); + CHECK(!playback.music_active()); + CHECK(playback.needs_pump()); + CHECK(playback.pump(error)); // Stopping music alone preserves an active cue. + playback.stop(); + CHECK(!playback.needs_pump()); + CHECK(!playback.pump(error)); + + Playback unavailable; + unavailable.reset_session(20); + const CueRequest unavailable_event{20, 1, 17}; + CHECK(!unavailable.available()); + CHECK(!unavailable.start_music_loop(matchday_loop, error)); + CHECK(unavailable.submit(unavailable_event, error) == CueStatus::disabled); + playback.shutdown(); + CHECK(unavailable.initialize(error)); + CHECK(unavailable.submit(unavailable_event, error) == CueStatus::duplicate); + CHECK(unavailable.queued_bytes() == 0); // A disabled event is not replayed after device recovery. + unavailable.shutdown(); + CHECK(playback.initialize(error)); + playback.reset_session(15); + CHECK(playback.start_music_loop(matchday_loop, error)); + CHECK(playback.submit(CueRequest{15, 1, 17}, error) == CueStatus::queued); + playback.shutdown(); // Device shutdown clears the optional track and active cue. + CHECK(!playback.available() && !playback.music_active()); + playback.shutdown(); + CHECK(!playback.available()); + CHECK((SDL_WasInit(SDL_INIT_VIDEO) & SDL_INIT_VIDEO) != 0); + SDL_QuitSubSystem(SDL_INIT_VIDEO); + std::cout << "checks passed: original/semantic shared event ledger; stale and zero IDs; unavailable device and no replay; deterministic eight-bar loop; PCM overlay and stop-music cue tail; fixed voice cap; mute/reset/shutdown clear music; SDL dummy lifecycle; no listening test\n"; + return 0; // (explicit: main is SDL_main here, no implicit return 0) +} diff --git a/src/cli/console/console.cpp b/src/cli/console/console.cpp new file mode 100644 index 0000000..30360c2 --- /dev/null +++ b/src/cli/console/console.cpp @@ -0,0 +1,737 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The console's core: registry, input blocks, argument binding, output and the global +// commands (docs/CLI_CONCEPT/01-grundlagen.md). The windows live in windows_*.cpp. + +#include "cli/console/console.hpp" + +#include +#include + +#include "cli/console/detail.hpp" +#include "ui/manager.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +// --------------------------------------------------------------------------------------- +// detail helpers + +namespace detail { + +Param integer(std::string name, long long min, long long max, bool optional) { + Param p; + p.name = std::move(name); + p.type = Param::Type::integer; + p.min = min, p.max = max, p.optional = optional; + return p; +} +Param boolean(std::string name, bool optional) { + Param p; + p.name = std::move(name); + p.type = Param::Type::boolean; + p.optional = optional; + return p; +} +Param text(std::string name, long long max_length, bool optional) { + Param p; + p.name = std::move(name); + p.type = Param::Type::text; + p.max = max_length, p.optional = optional; + return p; +} +Param choice(std::string name, std::vector choices, bool optional) { + Param p; + p.name = std::move(name); + p.type = Param::Type::choice; + p.choices = std::move(choices); + p.optional = optional; + return p; +} + +std::string on_off(bool v) { return v ? "on" : "off"; } + +std::string lower(std::string s) { + for (char& c : s) c = char(std::tolower(static_cast(c))); + return s; +} + +std::string utf8(std::string_view text) { + for (char c : text) + if (static_cast(c) >= 0x80) return std::string(text); + return ui::original_to_utf8(text); +} + +std::string fold(std::string s) { + s = lower(std::move(s)); + // UTF-8 Ä Ö Ü (C3 84, C3 96, C3 9C) -> ä ö ü (C3 A4, C3 B6, C3 BC) + for (size_t i = 0; i + 1 < s.size(); ++i) + if (static_cast(s[i]) == 0xC3) { + unsigned char& c = reinterpret_cast(s[i + 1]); + if (c == 0x84 || c == 0x96 || c == 0x9C) c = static_cast(c + 0x20); + } + return s; +} + +// Dates as the concept's `date` type: YYYY-MM-DD (01-grundlagen 1.2). +std::string date_text(int day, int month, int year) { + char buffer[16]; + std::snprintf(buffer, sizeof buffer, "%04d-%02d-%02d", year, month, day); + return buffer; +} + +std::string money(long long value) { return std::to_string(value); } + +size_t resolve_player(const std::string& reference, const std::vector& players) { + const std::string key = lower(reference); + auto number = [&](size_t prefix) { + Arg a; + a.text = reference.substr(prefix); + const auto n = to_int(a); + if (!n) fail("E_BAD_ARGUMENT", "\"" + reference + "\" is no player reference (id:, row: or a name)"); + return int(*n); + }; + if (key.rfind("id:", 0) == 0 || key.rfind("row:", 0) == 0) { + const bool by_id = key[0] == 'i'; + const int n = number(by_id ? 3 : 4); + for (size_t i = 0; i < players.size(); ++i) + if ((by_id ? players[i].id : players[i].row) == n) return i; + fail("E_BAD_ARGUMENT", "no player " + reference + " in this list"); + } + const std::string wanted = fold(reference); + std::vector exact, partial; + for (size_t i = 0; i < players.size(); ++i) { + const std::string name = fold(players[i].name); + if (name == wanted) exact.push_back(i); + else if (name.find(wanted) != std::string::npos) partial.push_back(i); + } + const auto& found = exact.empty() ? partial : exact; + if (found.size() == 1) return found.front(); + if (found.empty()) fail("E_BAD_ARGUMENT", "no player named \"" + reference + "\" in this list"); + std::string candidates; + for (size_t i = 0; i < found.size() && i < 8; ++i) + candidates += (i ? ", " : "") + players[found[i]].name + " = id:" + std::to_string(players[found[i]].id); + fail("E_AMBIGUOUS", "\"" + reference + "\" fits several players: " + candidates); +} + +} // namespace detail + +namespace { + +const char* class_name(char cls) { + switch (cls) { + case '#': return "status"; + case '>': return "option"; + case '|': return "table"; + case '+': return "ok"; + case '!': return "error"; + case '?': return "question"; + case 'i': return "info"; + case '~': return "event"; + case 'c': return "chat"; + default: return "other"; + } +} + +// The type part of a parameter: "1..5", "bool", "string", "enum(a,b)". +std::string param_type(const Param& p) { + switch (p.type) { + case Param::Type::integer: return std::to_string(p.min) + ".." + std::to_string(p.max); + case Param::Type::boolean: return "bool"; + case Param::Type::text: return p.max > 0 ? "string(max " + std::to_string(p.max) + ")" : "string"; + case Param::Type::choice: { + std::string s = "enum("; + for (size_t i = 0; i < p.choices.size(); ++i) s += (i ? "," : "") + p.choices[i]; + return s + ")"; + } + } + return {}; +} + +// A parameter in a signature: "name:type", optional ones in [brackets]. +std::string param_text(const Param& p) { + if (!p.display.empty()) return p.display; + const std::string s = p.name + ":" + (p.type == Param::Type::text ? "string" : param_type(p)); + return p.optional ? "[" + s + "]" : s; +} + +// The index of an enum argument: a name of the list (canonical comparison) or its number. +int choice_index(const Param& p, const Arg& a) { + for (size_t i = 0; i < p.choices.size(); ++i) + if (canonical(p.choices[i]) == canonical(a.text)) return int(i); + if (const auto n = to_int(a); n && *n >= 0 && size_t(*n) < p.choices.size()) return int(*n); + return -1; +} + +size_t edit_distance(const std::string& a, const std::string& b) { + std::vector row(b.size() + 1); + for (size_t j = 0; j <= b.size(); ++j) row[j] = j; + for (size_t i = 1; i <= a.size(); ++i) { + size_t diagonal = row[0]; + row[0] = i; + for (size_t j = 1; j <= b.size(); ++j) { + const size_t up = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diagonal = up; + } + } + return row[b.size()]; +} + +} // namespace + +long long Console::Values::integer(const std::string& name, long long fallback) const { + const auto it = args.find(canonical(name)); + return it == args.end() ? fallback : *to_int(it->second); +} +bool Console::Values::boolean(const std::string& name, bool fallback) const { + const auto it = args.find(canonical(name)); + return it == args.end() ? fallback : *to_bool(it->second); +} +std::string Console::Values::text(const std::string& name, std::string fallback) const { + const auto it = args.find(canonical(name)); + return it == args.end() ? fallback : it->second.text; +} +int Console::Values::choice(const std::string& name) const { + const auto it = args.find(canonical(name)); + if (it == args.end() || !spec) return -1; + for (const Param& p : spec->params) + if (canonical(p.name) == canonical(name)) return choice_index(p, it->second); + return -1; +} + +// --------------------------------------------------------------------------------------- + +Console::Console(Options options, std::function write) + : options_(std::move(options)), write_(std::move(write)) { + texts_ = load_textd(ui::asset_path(options_.data, "TEXTD.BLK")); + exe_ = load_le(ui::asset_path(options_.data, "BMH.exe")); + // The program start up to the options dialog (InitializeCareer) - as the SDL app does it. + session_ = std::make_unique(options_.data, options_.seed); + install_hooks(); + register_global_commands(); + register_start_commands(); + register_file_commands(); + register_desk_commands(); + register_table_commands(); + register_club_commands(); + register_money_commands(); + register_office_commands(); + register_squad_commands(); + register_transfer_commands(); + register_info_commands(); + register_match_commands(); + register_friendly_commands(); + register_reschedule_commands(); + register_balance_commands(); + register_environment_commands(); + register_state_commands(); + register_advice_commands(); +} + +// ~Console is in windows_match.cpp, where the engine thread (EngineRun) is complete. + +std::string Console::text(int index) const { + if (index < 0 || size_t(index) >= texts_.strings.size()) return {}; + std::string s = utf8(texts_.strings[size_t(index)]); + // dialog markers at the start steer the original's dialog mode (09-texte 1.6) + while (!s.empty() && (s.rfind("\xC2\xA7", 0) == 0 || s.rfind("\xC2\xBA", 0) == 0)) s.erase(0, 2); + // padding for the screen layout is no content + while (!s.empty() && s.back() == ' ') s.pop_back(); + while (!s.empty() && s.front() == ' ') s.erase(0, 1); + return s; +} + +// --------------------------------------------------------------------------------------- +// registry + +void Console::add(Spec spec, Handler handler) { + handlers_[spec.window + "/" + canonical(spec.name)] = std::move(handler); + specs_.push_back(std::move(spec)); +} + +const Spec* Console::find(std::string_view window, std::string_view key) const { + for (const Spec& s : specs_) + if (s.window == window && canonical(s.name) == key) return &s; + return nullptr; +} + +void Console::register_global_commands() { + // --- global commands, valid in every window (01-grundlagen 9) ---------------------- + Param list_param = detail::text("command", 0, true); + list_param.display = "[command:string|all]"; + add({"*", "ListOptions", {list_param}, "commands possible here; ListOptions(all) also shows locked ones", false}, + [this](const Values& v) { + const std::string which = v.text("command"); + if (!which.empty() && canonical(which) != "all") { + const Spec* spec = find(window_, canonical(which)); + if (!spec) spec = find("*", canonical(which)); + if (!spec) fail("E_UNKNOWN_COMMAND", which + " is not a command of " + window_); + emit('>', option_line(*spec)); + std::vector> rows; + for (const Param& p : spec->params) rows.push_back({p.name, param_type(p), p.optional ? "optional" : "required"}); + if (!rows.empty()) emit_table({"Parameter", "Type", "Use"}, rows); + return; + } + const bool all = !which.empty(); + for (const Spec* spec : window_specs(all)) { + std::string line = option_line(*spec); + if (canonical(spec->name) == "answer" && !question_) line += " [locked: no open question]"; + emit('>', line); + // the desk's icons: one line per window Open() reaches (02-fenster 4 and 6) + if (window_ == "Desktop" && canonical(spec->name) == "open" && career_) { + ui::DeskState d = desk(); + std::sort(d.items.begin(), d.items.end(), [](const auto& a, const auto& b) { return a.kind < b.kind; }); + for (const auto& item : d.items) { + if (item.kind >= 30 || item.kind == 12) continue; // widgets; 12 = Kickoff + if (item.disabled && !all) continue; + std::string target = " Open(" + menu_window(item.kind) + ")"; + if (target.size() < 48) target.resize(48, ' '); + target += " - menu " + std::to_string(item.kind); + if (item.disabled) target += " [locked: mode]"; + emit('>', target); + } + } + } + }); + add({"*", "GoBack", {}, "right mouse button: one level back, otherwise nothing", false}, + [this](const Values& v) { + if (question_) { + // a question's right mouse button: its default answer (01-grundlagen 2.4) - only + // from the player it belongs to, and said aloud (it may decline a sale) + if (v.player && v.player != question_->player) + fail("E_NOT_YOUR_TURN", "the question belongs to player " + std::to_string(question_->player)); + Question q = std::move(*question_); + question_.reset(); + emit('+', "Q" + std::to_string(q.id) + " answered: " + q.default_option + " (GoBack = default answer)"); + q.on_answer(q.default_option); + return; + } + if (window_ == "NewGame") new_game_continue(); // exception: right mouse = next (H1 S. 13) + else if (const auto it = closers_.find(window_); it != closers_.end()) it->second(); + else if (!close_window()) emit('+', "nothing to go back to"); + }); + Param chat_to = integer("to", 0, 4, true); + add({"*", "Chat", {chat_to, detail::text("text", 200)}, "message to all, or to one player (0 = only the log)", false}, + [this](const Values& v) { + const std::string message = v.text("text"); + if (message.empty()) fail("E_BAD_ARGUMENT", "text must not be empty"); + const int from = v.player ? v.player : (player_ ? player_ : 1); + const int to = v.has("to") ? int(v.integer("to")) : -1; + chat_.push_back({from, to, message}); + const std::string target = to < 0 ? "All" : to == 0 ? "Log" : "P" + std::to_string(to); + emit('c', "[P" + std::to_string(from) + " -> " + target + "] " + message); + }); + add({"*", "ChatLog", {integer("count", 1, 1000, true)}, "the last chat messages", false}, [this](const Values& v) { + const size_t count = size_t(v.integer("count", 20)); + std::vector> rows; + const size_t first = chat_.size() > count ? chat_.size() - count : 0; + for (size_t i = first; i < chat_.size(); ++i) { + const ChatEntry& e = chat_[i]; + rows.push_back({std::to_string(i + 1), "P" + std::to_string(e.from), + e.to < 0 ? "All" : e.to == 0 ? "Log" : "P" + std::to_string(e.to), e.text}); + } + emit_table({"#", "From", "To", "Text"}, rows); + }); + Param answer_option = detail::text("option"); + answer_option.display = "option:enum"; + Param answer_id = detail::text("id"); + answer_id.display = "id:int"; // 2 or Q2, as the question line shows it + add({"*", "Answer", {answer_id, answer_option}, "answer the open question", false}, + [this](const Values& v) { + if (!question_) fail("E_BAD_ARGUMENT", "there is no open question"); + std::string id_text = v.text("id"); + if (!id_text.empty() && (id_text[0] == 'Q' || id_text[0] == 'q')) id_text.erase(0, 1); + Arg id_arg; + id_arg.text = id_text; + const auto id = to_int(id_arg); + if (!id) fail("E_BAD_ARGUMENT", "id must be the question number, e.g. 2 or Q2"); + if (*id != question_->id) fail("E_BAD_ARGUMENT", "the open question is Q" + std::to_string(question_->id)); + if (v.player && v.player != question_->player) + fail("E_NOT_YOUR_TURN", "the question belongs to player " + std::to_string(question_->player)); + Arg arg; + arg.text = v.text("option"); + std::string chosen; + for (const std::string& o : question_->options) + if (canonical(o) == canonical(arg.text)) chosen = o; + if (chosen.empty() && question_->options == std::vector{"Yes", "No"}) + if (const auto b = to_bool(arg)) chosen = *b ? "Yes" : "No"; + if (chosen.empty()) + if (const auto n = to_int(arg); n && *n >= 1 && size_t(*n) <= question_->options.size()) + chosen = question_->options[size_t(*n - 1)]; + if (chosen.empty()) fail("E_BAD_ARGUMENT", "option must be one of the question's options"); + Question q = std::move(*question_); + question_.reset(); + emit('+', "Q" + std::to_string(q.id) + " answered: " + chosen); // (some answers print nothing else) + q.on_answer(chosen); + }); + add({"*", "Status", {}, "window, player and a short overview", false}, [this](const Values& v) { + // a seat not on turn sees the desk of the manager on turn: say so, so it is not read + // as its own club + if (v.player && player_ && v.player != player_) + emit('+', "you are player " + std::to_string(v.player) + "; player " + std::to_string(player_) + + " is on turn - the overview below is his"); + if (run_) { + emit('+', match_status()); + return; + } + if (!career_) { + emit('+', "options: " + options_text()); + } else { + const ui::DeskState d = desk(); + emit('+', utf8(d.manager_name) + " | " + utf8(d.club_name) + " | " + + date_text(d.date.day, d.date.month, d.date.year) + " | balance " + money(d.balance)); + } + if (question_) emit('+', "open question: Q" + std::to_string(question_->id)); + }); + add({"*", "Help", {detail::text("command", 0, true)}, "command reference (all windows)", false}, [this](const Values& v) { + const std::string which = v.text("command"); + for (const Spec& spec : specs_) { + if (!which.empty() && canonical(spec.name) != canonical(which)) continue; + emit('>', "[" + spec.window + "] " + option_line(spec)); + } + if (!which.empty() && std::none_of(specs_.begin(), specs_.end(), + [&](const Spec& s) { return canonical(s.name) == canonical(which); })) + fail("E_UNKNOWN_COMMAND", which + " is no command"); + }); + add({"*", "Quit", {boolean("force", true)}, "end the session (asks first during a game)", false}, + [this](const Values& v) { + auto end = [this] { + if (run_) stop_matchday(); + ended_ = true; + emit('+', "session ended"); + }; + if (question_ && !v.boolean("force")) + fail("E_PENDING_QUESTION", "answer Q" + std::to_string(question_->id) + " first (or Quit(force=true))"); + if (!career_ || v.boolean("force")) { + end(); + return; + } + // the plug on the desk asks first (H2 S. 24); the question is the console's own + // text: the original asks with a picture, not with a TEXTD text + ask("Quit the game? Unsaved progress is lost.", {"Yes", "No"}, "No", [this, end](const std::string& answer) { + if (answer == "Yes") end(); + else emit('+', "quit cancelled"); + }); + }); +} + +// --------------------------------------------------------------------------------------- +// input + +void Console::start() { + last_block_.clear(); + last_output_.clear(); + flush_status(); +} + +bool Console::feed(std::string_view line) { + if (ended_) return false; + switch (classify_line(line)) { + case LineKind::skip: break; + case LineKind::clear: pending_.clear(); break; + case LineKind::command: pending_.emplace_back(line); break; + case LineKind::go: execute_block(); break; + } + return !ended_; +} + +void Console::execute_block() { + last_block_ = std::move(pending_); + pending_.clear(); + last_output_.clear(); + if (last_block_.empty()) { + emit('+', "nothing to do"); + return; + } + for (size_t i = 0; i < last_block_.size() && !ended_; ++i) { + try { + Command cmd; + try { + cmd = parse_command(last_block_[i]); + } catch (const ParseError& e) { + fail("E_BAD_ARGUMENT", std::string("syntax: ") + e.what()); + } + try { + execute(cmd); + } catch (const CliError&) { + throw; + } catch (const std::exception& e) { + // an engine exception is a defect of the program, never of the input + fail("E_INTERNAL", e.what()); + } + } catch (const CliError& e) { + emit('!', e.code + ": " + e.message + (e.text_key.empty() ? "" : " [textKey: " + e.text_key + "]")); + const size_t skipped = last_block_.size() - i - 1; + if (skipped) emit('!', "E_BLOCK_ABORTED: " + std::to_string(skipped) + " command" + (skipped == 1 ? "" : "s") + " skipped"); + break; + } + } + flush_status(); +} + +void Console::execute(const Command& cmd) { + const Spec* spec = find(window_, cmd.key); + if (!spec) spec = find("*", cmd.key); + if (!spec) { + // Run/Step outside a match: with several managers the match day starts only after the + // last one's Kickoff (each Kickoff passes the turn) - agents sent Run here again and + // again in the learning session, so the error says what to do instead + if ((cmd.key == "run" || cmd.key == "step") && window_ != "Match") + fail("E_NOT_IN_WINDOW", "no match is running - the match day starts after every manager's Kickoff; " + "WaitTurn (or Status) shows when the window is Match"); + for (const Spec& s : specs_) + if (canonical(s.name) == cmd.key) fail("E_NOT_IN_WINDOW", s.name + " is only available in " + s.window); + std::string best; + size_t best_distance = 1000; + for (const Spec& s : specs_) { + const size_t d = edit_distance(cmd.key, canonical(s.name)); + if (d < best_distance) best_distance = d, best = s.name; + } + fail("E_UNKNOWN_COMMAND", cmd.name + " is unknown" + + (best_distance <= std::max(2, cmd.key.size() / 3) ? " (did you mean " + best + "?)" : "")); + } + // An engine question owns the paused kickoff. Some navigation commands are + // changes=false yet prepare Native state on entry (notably Open(Lineup)). + // Only explicit observers and the current question's answer may run here. + const bool engine_question_observer = + spec->window == "*" && + (cmd.key == "answer" || cmd.key == "goback" || cmd.key == "status" || + cmd.key == "help" || cmd.key == "listoptions" || cmd.key == "chat" || cmd.key == "chatlog" || + (cmd.key == "quit" && loan_return_modal_active())); + const bool engine_question_desk_observer = + spec->window == "Desktop" && (cmd.key == "showdate" || cmd.key == "showopponent"); + if (question_ && (spec->changes || + (run_ && !engine_question_observer && !engine_question_desk_observer))) + fail("E_PENDING_QUESTION", "answer Q" + std::to_string(question_->id) + " first"); + if (loan_return_offer_active() && !engine_question_observer && spec->window != "Transfer.Negotiate") + fail("E_MODE_LOCKED", "finish the loan-return negotiation first"); + if (spec->changes && cmd.player && player_ && cmd.player != player_) + fail("E_NOT_YOUR_TURN", "current player is " + std::to_string(player_)); + if (loan_return_modal_active() && cmd.player && cmd.player != player_ && + (cmd.key == "goback" || cmd.key == "quit")) + fail("E_NOT_YOUR_TURN", "the loan-return modal belongs to player " + std::to_string(player_)); + // A player who is not on turn shares the screen with the active one: he may use the + // commands of every window (Status, Help, Chat, Answer ...) but not those of the open + // window, which would page or open things under the active player's hands. + if (cmd.player && player_ && cmd.player != player_ && spec->window != "*") + fail("E_NOT_YOUR_TURN", "current player is " + std::to_string(player_) + " (WaitTurn waits for your turn)"); + Values values = bind(*spec, cmd); + handlers_.at(spec->window + "/" + canonical(spec->name))(values); + succeeded_.insert(spec->window + "/" + spec->name); +} + +Console::Values Console::bind(const Spec& spec, const Command& cmd) const { + Values values; + values.spec = &spec; + values.player = cmd.player; + std::vector positional; + for (const Arg& a : cmd.args) + if (a.name.empty()) positional.push_back(&a); + const size_t required = size_t(std::count_if(spec.params.begin(), spec.params.end(), [](const Param& p) { return !p.optional; })); + if (positional.size() > spec.params.size()) + fail("E_BAD_ARGUMENT", spec.name + " takes at most " + std::to_string(spec.params.size()) + " arguments"); + // positional arguments fill the required parameters; the surplus fills optional ones + // from the left (Chat("x") = text, Chat(2, "x") = to + text) + // "fee:1500000" looks like the name:type of ListOptions but is a positional text; say how + // named arguments are written (references like id:7, club:3 go to text parameters) + for (const Arg* a : positional) { + const size_t colon = a->text.find(':'); + if (colon == std::string::npos || colon == 0) continue; + const std::string head = canonical(a->text.substr(0, colon)); + if (head == canonical("id") || head == canonical("row")) continue; + for (const Param& p : spec.params) + if (canonical(p.name) == head && p.type != Param::Type::text) // texts take references like club:3 + fail("E_BAD_ARGUMENT", "named arguments are written name=value, e.g. " + p.name + "=" + a->text.substr(colon + 1)); + } + size_t optional_slots = positional.size() > required ? positional.size() - required : 0; + size_t next = 0; + for (const Param& p : spec.params) { + if (next >= positional.size()) break; + if (p.optional) { + if (optional_slots == 0) continue; + --optional_slots; + } + values.args[canonical(p.name)] = *positional[next++]; + } + for (const Arg& a : cmd.args) { + if (a.name.empty()) continue; + const auto it = std::find_if(spec.params.begin(), spec.params.end(), [&](const Param& p) { return canonical(p.name) == a.name; }); + if (it == spec.params.end()) fail("E_BAD_ARGUMENT", spec.name + " has no parameter " + a.name); + if (values.args.count(a.name)) fail("E_BAD_ARGUMENT", "parameter " + it->name + " given twice"); + values.args[a.name] = a; + } + for (const Param& p : spec.params) { + const auto it = values.args.find(canonical(p.name)); + if (it == values.args.end()) { + if (!p.optional) fail("E_BAD_ARGUMENT", spec.name + " needs " + param_text(p)); + continue; + } + const Arg& a = it->second; + switch (p.type) { + case Param::Type::integer: { + const auto n = to_int(a); + if (!n || *n < p.min || *n > p.max) + fail("E_BAD_ARGUMENT", p.name + " must be " + std::to_string(p.min) + ".." + std::to_string(p.max)); + break; + } + case Param::Type::boolean: + if (!to_bool(a)) fail("E_BAD_ARGUMENT", p.name + " must be true or false"); + break; + case Param::Type::text: + if (p.max > 0 && a.text.size() > size_t(p.max)) + fail("E_BAD_ARGUMENT", p.name + " is longer than " + std::to_string(p.max) + " characters"); + break; + case Param::Type::choice: + if (choice_index(p, a) < 0) fail("E_BAD_ARGUMENT", p.name + " must be one of " + param_type(p)); + break; + } + } + return values; +} + +// --------------------------------------------------------------------------------------- +// output + +void Console::emit(char cls, const std::string& text, Json data) { + if (cls != '#') flush_status(); + std::string line; + if (options_.json) { + Json::Object o; + o["class"] = class_name(cls); + o["window"] = window_; + o["player"] = player_ ? Json(player_) : Json("All"); + o["text"] = text; + if (!std::holds_alternative(data.value)) o["data"] = std::move(data); + line = dump_json(Json(std::move(o))); + } else { + line = std::string(1, cls) + " " + text; + } + last_output_.push_back(line); + if (observer_) observer_({cls, player_, text, line}); + write_(line); +} + +void Console::emit_table(const std::vector& header, const std::vector>& rows) { + auto row_text = [](const std::vector& cells) { + std::string s = "|"; + for (const std::string& c : cells) s += " " + c + " |"; + return s.substr(2); // emit adds "| " + }; + auto cells_json = [](const std::vector& cells, bool head) { + Json::Array a; + for (const std::string& c : cells) a.emplace_back(c); + return Json(Json::Object{{"header", head}, {"cells", Json(std::move(a))}}); + }; + // With --json each row also carries a record keyed by the column names, the cells typed: + // whole numbers and the references id:/row:/club: as numbers, "-" and "" as null, the + // rest as text - what a graphical client needs without parsing the table (stage 2.5). + auto typed = [](const std::string& cell) -> Json { + if (cell.empty() || cell == "-") return Json(nullptr); + std::string digits = cell; + for (const char* prefix : {"id:", "row:", "club:"}) + if (digits.rfind(prefix, 0) == 0) digits = digits.substr(std::string(prefix).size()); + const bool negative = !digits.empty() && digits[0] == '-'; + const size_t from = negative ? 1 : 0; + if (digits.size() > from && digits.size() - from <= 18 && + digits.find_first_not_of("0123456789", from) == std::string::npos) + return Json(std::int64_t(std::stoll(digits))); + return Json(cell); + }; + emit('|', row_text(header), cells_json(header, true)); + for (const auto& r : rows) { + Json data = cells_json(r, false); + if (options_.json) { + Json::Object record; + for (size_t i = 0; i < r.size(); ++i) + record[i < header.size() && !header[i].empty() ? header[i] : "c" + std::to_string(i + 1)] = typed(r[i]); + data.object()->insert_or_assign("record", Json(std::move(record))); + } + emit('|', row_text(r), std::move(data)); + } +} + +void Console::flush_status() { + if (window_ == printed_window_ && player_ == printed_player_) return; + printed_window_ = window_; + printed_player_ = player_; + emit('#', "Window: " + window_); + emit('#', "Player: " + (player_ ? std::to_string(player_) : std::string("All"))); +} + +std::string Console::option_line(const Spec& spec) const { + std::string sig = spec.name + "("; + for (size_t i = 0; i < spec.params.size(); ++i) sig += (i ? ", " : "") + param_text(spec.params[i]); + sig += ")"; + if (spec.description.empty()) return sig; + if (sig.size() < 48) sig.resize(48, ' '); + return sig + " - " + spec.description; +} + +std::vector Console::window_specs(bool include_locked) const { + std::vector result; + for (const Spec& s : specs_) + if (s.window == window_) result.push_back(&s); + for (const Spec& s : specs_) { + if (s.window != "*") continue; + if (canonical(s.name) == "answer" && !question_ && !include_locked) continue; + result.push_back(&s); + } + return result; +} + +// --------------------------------------------------------------------------------------- +// windows and questions + +void Console::set_window(std::string window, int player) { + window_ = std::move(window); + player_ = player; + back_.clear(); +} + +void Console::open_window(std::string window) { + back_.push_back(window_); + window_ = std::move(window); +} + +bool Console::close_window() { + if (back_.empty()) { + // the start windows have a fixed way back (02-fenster 3) + if (window_ == "NewGame.LoadGame" || (window_ == "NewGame.Select" && confirmed_.empty())) { + set_window("NewGame", 1); + return true; + } + return false; + } + window_ = back_.back(); + back_.pop_back(); + return true; +} + +void Console::ask(std::string text, std::vector options, std::string default_option, + std::function on_answer, std::string text_key) { + Question q; + q.id = next_question_++; + q.player = player_ ? player_ : 1; + q.text = std::move(text); + q.options = std::move(options); + q.default_option = std::move(default_option); + q.on_answer = std::move(on_answer); + std::string opts; + for (size_t i = 0; i < q.options.size(); ++i) opts += (i ? " | " : "") + q.options[i]; + // --json: the question as data (id, the player it belongs to, the options and the answer + // GoBack gives), so a client can show a dialog without parsing the line + Json data = nullptr; + if (options_.json) { + Json::Array options; + for (const auto& o : q.options) options.emplace_back(o); + data = Json(Json::Object{{"id", q.id}, {"player", q.player}, {"text", q.text}, {"options", Json(std::move(options))}, + {"default", q.default_option}, {"text_key", text_key}}); + } + emit('?', "Q" + std::to_string(q.id) + " \"" + q.text + "\" options: " + opts + + (text_key.empty() ? "" : " [textKey: " + text_key + "]"), + std::move(data)); + question_ = std::move(q); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/console.hpp b/src/cli/console/console.hpp new file mode 100644 index 0000000..573ab40 --- /dev/null +++ b/src/cli/console/console.hpp @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The console language of openbmh_cli (docs/CLI_CONCEPT): +// - input in blocks of command lines, executed by a line "go." (01-grundlagen 1.1) +// - output lines with a class character (# status, > option, | table, + ok, ! error, +// ? question, i info, ~ event, c chat), the status lines "# Window:" / "# Player:" printed +// whenever window or player changed (2.2); --json gives one JSON object per line +// - global commands ListOptions, GoBack, Chat, ChatLog, Answer, Status, Help, Quit (9) +// +// Stage 0 (console.cpp, windows_start.cpp): options screen NewGame, load browser. +// Stage 1: manager selection NewGame.Select (+ Confirm), the info sequence after the last +// manager, Desktop with its displays, Open/Key, Kickoff (time "instant"), the file windows +// LoadGame/SaveGame, Mailbox, LeagueTable and Fixtures (windows_desk.cpp, windows_tables.cpp). +// +// The console owns no game logic: everything that changes the game goes through +// app::CareerSession (including its staged Source modal callbacks), like the SDL app. It never +// draws random numbers itself; where the original draws numbers when a window opens (the +// fixtures window), the console opens it through the same engine call. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/career_session.hpp" +#include "game/balance_plan.hpp" +#include "game/bank_credit.hpp" +#include "game/desk_actions.hpp" +#include "cli/console/parser.hpp" +#include "cli/json.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "ui/league_pairings.hpp" +#include "ui/club_info.hpp" +#include "ui/mailbox_state.hpp" +#include "ui/outgoing_transfer.hpp" +#include "ui/preparation.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +namespace bmh::cli::console { + +// How a matchday runs (01-grundlagen 7, 07-spieltag 3.2): stepped = the clock moves only on +// Match.Step / Match.Run and the managers can intervene; instant = the day runs through and +// only the results are printed. +enum class TimeMode { stepped, instant }; + +struct Options { + std::filesystem::path data; // the BMH directory (data files) + std::filesystem::path save_directory; // where LoadGame/Save look; empty = data + std::uint32_t seed = 1; // Watcom seed of the session (determinism) + bool json = false; // one JSON object per output line + TimeMode time = TimeMode::stepped; +}; + +// A command's parameter as ListOptions/Help show it and the argument check uses it. +struct Param { + enum class Type { integer, boolean, text, choice }; + std::string name; + Type type = Type::integer; + long long min = 0, max = 0; // integer range; text: max length (0 = none) + bool optional = false; + std::vector choices; // choice: allowed names (index = number) + std::string display; // overrides the generated "name:type" text +}; + +struct Spec { + std::string window; // "*" = every window + std::string name; // canonical display name, e.g. "ListOptions" + std::vector params; + std::string description; + bool changes = false; // changes the game: only the active player +}; + +class Console { +public: + // `write` receives every finished output line (without the newline). + Console(Options options, std::function write); + ~Console(); + + // Prints the first status lines. Call once before feeding input. + void start(); + // One line of input. Command lines are collected until "go.". Returns false once the + // session has ended (Quit); later input is ignored. + bool feed(std::string_view line); + bool ended() const { return ended_; } + // Whose turn it is (1-4, 0 = All during a live match), the open window and the player an + // open question belongs to (0 = none): what the multi-seat mailbox (--seats) waits on. + int active_player() const { return player_; } + const std::string& window() const { return window_; } + int question_player() const { return question_ ? question_->player : 0; } + // Every finished output line with its meaning, independent of text or JSON format: the + // class character (#, |, +, !, ?, i, ~, c, >), the player it belongs to (0 = All), the + // plain text and the formatted line as written. The seat hub (several clients in one game) + // routes lines by these instead of parsing them. + struct LineInfo { + char cls = 0; + int player = 0; + std::string text; + std::string line; + }; + void set_line_observer(std::function observer) { observer_ = std::move(observer); } + + // The input lines of the last executed block and its output, for --log / --replay. + // After start(): no input, the start output. + const std::vector& last_block() const { return last_block_; } + const std::vector& last_output() const { return last_output_; } + + // All registered commands (for tests against docs/CLI_CONCEPT/commands.csv). + const std::vector& specs() const { return specs_; } + // "window/Name" of every command that ran without an error (coverage, 10-agenten 3). + const std::set& succeeded() const { return succeeded_; } + + // The engine session (tests compare it with season_sim / save files). + const app::CareerSession& session() const { return *session_; } + + struct Values; // bound arguments of one call (detail.hpp) + +private: + struct Question { + int id = 0; + int player = 1; + std::string text; + std::vector options; + std::string default_option; // the answer GoBack (right mouse button) gives + std::function on_answer; + }; + struct ChatEntry { + int from = 0, to = 0; + std::string text; + }; + using Handler = std::function; + + // registry (one function per command file) + void add(Spec spec, Handler handler); + void register_global_commands(); + void register_start_commands(); // windows_start.cpp + void register_file_commands(); // windows_start.cpp: NewGame.LoadGame, LoadGame, SaveGame + void register_desk_commands(); // windows_desk.cpp: Desktop, Mailbox + void register_table_commands(); // windows_tables.cpp: LeagueTable, Fixtures + void register_club_commands(); // windows_club.cpp: Tactics, Training, TrainingCamp + void register_money_commands(); // windows_money.cpp: Bank, Stadium, Toto + void register_office_commands(); // windows_office.cpp: Advertising, Contracts, Settings + void register_squad_commands(); // windows_squad.cpp: Lineup, Lineup.Pitch, PlayerCard + void register_transfer_commands(); // windows_transfer.cpp: Transfer, Transfer.Negotiate + void register_info_commands(); // windows_info.cpp: TeamInfo, HighScore + void register_match_commands(); // windows_match.cpp: Match (stage 4) + void register_friendly_commands(); // windows_friendly.cpp: Friendlies (stage 5) + void register_reschedule_commands(); // windows_reschedule.cpp: Reschedule (stage 5) + void register_balance_commands(); // windows_balance.cpp: Balance (stage 5) + void register_environment_commands(); // windows_environment.cpp: Environment (stage 5) + void register_state_commands(); // windows_state.cpp: State(view), structured data (stage 2.5) + void register_advice_commands(); // windows_state.cpp: Advice, Scoreboard (learning agents) + const Spec* find(std::string_view window, std::string_view key) const; + + // execution + void execute_block(); + void execute(const Command& cmd); + Values bind(const Spec& spec, const Command& cmd) const; + + // output + void emit(char cls, const std::string& text, Json data = nullptr); + void emit_table(const std::vector& header, const std::vector>& rows); + void flush_status(); + std::string option_line(const Spec& spec) const; + std::vector window_specs(bool include_locked) const; + // A TEXTD text by its index (docs/formats/textd_inventory.csv), as UTF-8. + std::string text(int index) const; + + // windows and questions + void set_window(std::string window, int player); + // Opens a sub window; GoBack returns to the window it was opened from. + void open_window(std::string window); + // Leaves the current sub window (GoBack). False if there is nothing to go back to. + bool close_window(); + void ask(std::string text, std::vector options, std::string default_option, + std::function on_answer, std::string text_key = {}); + + // start (windows_start.cpp) + std::string options_text() const; + void new_game_continue(); + void begin_selection(int slot); + void confirm_selection(); + void finish_career(); + void load_game(const std::filesystem::path& path); + void save_game(const std::filesystem::path& path, bool overwrite); + std::filesystem::path save_directory() const; + std::string shown_directory() const; + std::filesystem::path browser_file(const std::string& name) const; + int resolve_club(const std::string& text) const; // master club index + + // desk (windows_desk.cpp) + int active_slot() const; + // The desk views (Advice, State) show the manager on turn; a seat that is not on turn + // would read another club as its own (learning session, October 2026), so it is refused. + void own_view_only(int player, const std::string& command) const; + ui::DeskState desk() const; + // The views of the action windows (training, bank, ...) of the active manager. + ui::PreparationState prep() const; + // Runs one engine action of an action window; `ok` is the dispatch result. + void require_engine(bool ok, const std::string& what, const std::string& error); + void enter_desktop(); + void open_menu(int menu); + void kickoff(); + void finish_kickoff(const ui::DeskState& before, const TurnAdvanceResult& advanced, const std::string& error); + // stage 4 (windows_match.cpp): the kickoff on the engine thread and its pauses + void start_matchday(const ui::DeskRequest& request, const ui::DeskState& before); + void resume_matchday(); // let the engine run until its next pause or the end + void engine_returned(); // the engine waits (minute, question) or has finished + void show_match_pause(); + void stop_matchday(); // abort and join a started day (Quit, destructor) + bool loan_return_offer_active() const; + bool loan_return_modal_active() const; + std::optional dispatch_loan_return_offer( + const ui::OutgoingTransferRequest&, const HumanBuyerSaleHooks&, std::string&, + const app::TransferOfferTeamInfoPresenter&, const app::TransferOfferPlayerInfoPresenter&); + void finish_loan_return_offer(); + std::string match_status() const; + struct EngineRun; + std::shared_ptr run_; // shared_ptr: EngineRun is complete only in windows_match.cpp + void report_new_mail(); + void flush_info(); + // Engine hooks of a new session (cup draws -> Info.CupDraw). + void install_hooks(); + + // tables (windows_tables.cpp) + void show_league_table(); + void open_fixtures(); + void show_fixtures(); + void fixtures_action(LeaguePairingsAction kind, int value = -1); + bool quiet_fixtures_ = false; // SetMatchday pages through without printing each page + bool squad_view_b_ = false; // Lineup: DATEN-B (age, skills, career numbers) instead of DATEN-A + + Options options_; + std::function write_; + std::function observer_; + std::vector specs_; + std::map handlers_; // window + "/" + key + // what Open(menu) does for the windows of the command files (menu_kind -> opener) + std::map> openers_; + // what GoBack does in windows whose closing is an engine step (Fixtures, Stadium) + std::map> closers_; + TextDb texts_; + LeImage exe_; + + std::unique_ptr session_; + uint64_t revision_ = 0; // CareerSession request revision + bool career_ = false; // a career is running (after finish or load) + ui::SetupOptions setup_; + std::string window_ = "NewGame"; + int player_ = 1; // 1-4, 0 = All + std::vector back_; // windows GoBack returns to + std::string printed_window_; + int printed_player_ = -1; + std::optional question_; + int next_question_ = 1; + std::vector chat_; + bool ended_ = false; + + // manager selection: the original picker model for the player choosing (tab ranges, + // defaults), the confirmed choices and the draft of the current player + std::unique_ptr picker_; + std::vector confirmed_; + ui::ManagerChoice draft_; + + // file windows + std::filesystem::path browse_directory_; + std::string selected_file_; + + // info windows produced inside engine calls (cup draws), printed after the call + std::vector> pending_info_; + + // mailbox: the messages of the last ListMessages (msg numbers refer to it) and the + // messages every player has already been told about + std::vector listed_mail_; + std::map> seen_mail_; + + // request ids of the engine calls that need increasing ids (advertising, contracts) + uint64_t next_request_id_ = 1; + // the open contract negotiation (Contracts.Negotiate) + struct Negotiation { + int row = -1, player_id = -1; + std::string name; + uint64_t quote_id = 0; + std::array demands{}; + int years = -1; // offered term, -1 = no salary offer yet + uint32_t salary = 0; // offered monthly salary + std::array bonuses{}; + }; + std::optional negotiation_; + + // squad windows (windows_squad.cpp) + void show_player_card(); + void show_player_statistics(int chart, bool absolute); + void show_pitch(); + void show_pairs(); + // the open offer editor of Transfer.Negotiate + std::optional offer_editor_; + bool offer_submitted_ = false; // a bid of this editor stands (closing does not withdraw it) + // the bank's credit editor draft (Bank.Credit) + std::optional credit_draft_; + int credit_counterparty_ = 0; // Bank.Credit: 0 the bank, else the lending manager + 1 + // the friendly offer of the Friendlies window + std::optional friendly_quote_; + std::optional balance_draft_; // the Balance window (BalanceFromGame2 locals) + // the open club information (TeamInfo) + std::optional team_info_; + int card_row_ = -1; // the squad row of the open player card + int chart_ = 0; // PlayerCard.Statistics: Value, Form, Strength, Total + bool chart_absolute_ = true; + + // tables + int table_league_ = -1; + std::optional pairings_; + + std::set succeeded_; + std::vector pending_; // command lines before "go." + std::vector last_block_, last_output_; +}; + +} // namespace bmh::cli::console diff --git a/src/cli/console/detail.hpp b/src/cli/console/detail.hpp new file mode 100644 index 0000000..50f7331 --- /dev/null +++ b/src/cli/console/detail.hpp @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Helpers shared by the console's command files (console.cpp and windows_*.cpp). Not part of +// the console's public interface. + +#include +#include +#include + +#include "cli/console/console.hpp" + +namespace bmh::cli::console::detail { + +// A rejected command: "! : [textKey: ]" (01-grundlagen 6). A failed +// command changes neither the game nor the random sequence: handlers check everything they +// can before they call the engine, and engine calls that fail leave the session unchanged. +struct CliError { + std::string code, message, text_key; +}; + +// The eight tactic settings (manager record +0xd2..+0xd9) by their place on the original +// board KB/11.VGA (hitboxes Tactics_Click_RuntimeField..Tactics_Click_RuntimeField6, src/ui/TACTICS.md) and the manual H2 p. 71. +// Item 0 is the attitude the match engine uses for a human side (match_engine.cpp +// update_attitude): fixed for the whole match unless the assistant controls it +// (SetAutomation(Tactics)); computer sides play 2 at home and 1 away and go up when behind. +// Items 1-3 and 5-6: the exact meaning of each diagram is not proven, the names say where. +inline constexpr const char* kTacticNames[8] = { + "attitude 0 defensive .. 3 offensive", + "pass/shot diagram, lower field (lower middle)", + "pass/shot diagram, lower field (upper middle)", + "pass/shot diagram, lower field (left)", + "flat or high balls (stick figures)", + "top right diagram, left (wingers hang back / build-up from behind)", + "top right diagram, right (wingers hang back / build-up from behind)", + "emphasis (EINSATZ!!!) 0..11", +}; + +[[noreturn]] inline void fail(std::string code, std::string message, std::string text_key = {}) { + throw CliError{std::move(code), std::move(message), std::move(text_key)}; +} + +// Parameter constructors for the registry. +Param integer(std::string name, long long min, long long max, bool optional = false); +Param boolean(std::string name, bool optional = false); +Param text(std::string name, long long max_length = 0, bool optional = false); +// enum: the names (case/'.'/'_' ignored) or their index +Param choice(std::string name, std::vector choices, bool optional = false); + +std::string on_off(bool v); +std::string lower(std::string s); +// For name comparisons: lower case, also the German capitals Ä Ö Ü in UTF-8. +std::string fold(std::string s); +// Text from the engine as UTF-8. Most projections keep the original ISO 646-DE bytes +// ("M]NCHEN"), some already convert (cup draw names, results). The original encoding has no +// bytes above 0x7f, so a string with such bytes is taken as UTF-8 already. +std::string utf8(std::string_view text); +// "2027-07-01" (the concept's date type) +std::string date_text(int day, int month, int year); +// Money as whole euros without separators (01-grundlagen 2.1) +std::string money(long long value); + +// A player of a list a command can refer to (01-grundlagen 1.3). +struct PlayerRef { + int row = -1; // row in the window's list (squad slot) + int id = -1; // player id of the game state (stable) + std::string name; // UTF-8 +}; +// Resolves id:, row: or a (unique part of a) name against `players`; returns the +// index into `players`. E_BAD_ARGUMENT if nothing fits, E_AMBIGUOUS with candidates. +size_t resolve_player(const std::string& reference, const std::vector& players); + +// The window a desk menu (menu_kind 0-29) opens, named as in 02-fenster 6; 63 = Mailbox. +// Empty for other numbers. +std::string menu_window(int menu); +// The menu number of a window name (canonical comparison), -1 if none. +int menu_of_window(std::string_view name); + +} // namespace bmh::cli::console::detail + +namespace bmh::cli::console { + +// The arguments of one call, bound to the parameter names and already type-checked. +struct Console::Values { + std::map args; // canonical parameter name -> argument + const Spec* spec = nullptr; + int player = 0; // the @n of the call (0 = none) + + bool has(const std::string& name) const { return args.count(canonical(name)) != 0; } + long long integer(const std::string& name, long long fallback = 0) const; + bool boolean(const std::string& name, bool fallback = false) const; + std::string text(const std::string& name, std::string fallback = {}) const; + // the index of an enum argument in its parameter's choices (-1 = absent) + int choice(const std::string& name) const; +}; + +} // namespace bmh::cli::console diff --git a/src/cli/console/parser.cpp b/src/cli/console/parser.cpp new file mode 100644 index 0000000..7e6ea7f --- /dev/null +++ b/src/cli/console/parser.cpp @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "cli/console/parser.hpp" + +#include +#include + +namespace bmh::cli::console { + +namespace { + +std::string_view trim(std::string_view s) { + while (!s.empty() && std::isspace(static_cast(s.front()))) s.remove_prefix(1); + while (!s.empty() && std::isspace(static_cast(s.back()))) s.remove_suffix(1); + return s; +} + +bool name_char(char c) { return std::isalnum(static_cast(c)) || c == '.' || c == '_'; } + +// Splits the text between the parentheses at top-level commas: commas inside "quotes" or +// [brackets] do not split. +std::vector split_args(std::string_view inner) { + std::vector parts; + std::string current; + bool quoted = false; + int depth = 0; + for (size_t i = 0; i < inner.size(); ++i) { + const char c = inner[i]; + if (quoted) { + current += c; + if (c == '\\' && i + 1 < inner.size()) current += inner[++i]; + else if (c == '"') quoted = false; + continue; + } + if (c == '"') quoted = true; + else if (c == '[') ++depth; + else if (c == ']') { + if (--depth < 0) throw ParseError("unbalanced ']'"); + } else if (c == ',' && depth == 0) { + parts.push_back(current); + current.clear(); + continue; + } + current += c; + } + if (quoted) throw ParseError("unterminated string"); + if (depth != 0) throw ParseError("unbalanced '['"); + parts.push_back(current); + return parts; +} + +Arg parse_arg(std::string_view text) { + Arg arg; + text = trim(text); + if (text.empty()) throw ParseError("empty argument"); + // name=value: a plain name before '=' (no quotes or brackets in front of it) + if (text.front() != '"' && text.front() != '[') { + const size_t eq = text.find('='); + if (eq != std::string_view::npos) { + const std::string_view name = trim(text.substr(0, eq)); + bool plain = !name.empty(); + for (char c : name) plain = plain && name_char(c); + if (plain) { + arg.name = canonical(name); + text = trim(text.substr(eq + 1)); + if (text.empty()) throw ParseError("missing value for " + std::string(name)); + } + } + } + if (text.front() == '"') { + if (text.size() < 2 || text.back() != '"') throw ParseError("unterminated string"); + arg.quoted = true; + const std::string_view body = text.substr(1, text.size() - 2); + for (size_t i = 0; i < body.size(); ++i) { + if (body[i] == '\\' && i + 1 < body.size()) { + arg.text += body[++i]; + } else if (body[i] == '"') { + throw ParseError("unescaped quote in string"); + } else { + arg.text += body[i]; + } + } + } else { + arg.text = std::string(text); + } + return arg; +} + +} // namespace + +std::string canonical(std::string_view name) { + std::string key; + for (char c : name) + if (c != '.' && c != '_') key += char(std::tolower(static_cast(c))); + return key; +} + +LineKind classify_line(std::string_view line) { + line = trim(line); + if (line.empty() || line.substr(0, 2) == "//") return LineKind::skip; + const std::string key = [&] { + std::string k; + for (char c : line) k += char(std::tolower(static_cast(c))); + return k; + }(); + if (key == "go.") return LineKind::go; + if (key == "clear.") return LineKind::clear; + return LineKind::command; +} + +Command parse_command(std::string_view line) { + Command cmd; + line = trim(line); + if (!line.empty() && line.front() == '@') { + size_t i = 1; + while (i < line.size() && std::isdigit(static_cast(line[i]))) ++i; + if (i == 1) throw ParseError("'@' needs a player number"); + int player = 0; + std::from_chars(line.data() + 1, line.data() + i, player); + if (player < 1 || player > 4) throw ParseError("player must be 1-4"); + cmd.player = player; + line = trim(line.substr(i)); + } + size_t n = 0; + while (n < line.size() && name_char(line[n])) ++n; + if (n == 0) throw ParseError("expected a command name"); + cmd.name = std::string(line.substr(0, n)); + cmd.key = canonical(cmd.name); + if (cmd.key.empty()) throw ParseError("expected a command name"); + std::string_view rest = trim(line.substr(n)); + if (rest.empty()) return cmd; + if (rest.front() != '(' || rest.back() != ')') throw ParseError("arguments must be written as Name(a, b)"); + const std::string_view inner = trim(rest.substr(1, rest.size() - 2)); + if (inner.empty()) return cmd; + bool named_seen = false; + for (const std::string& part : split_args(inner)) { + Arg arg = parse_arg(part); + if (arg.name.empty() && named_seen) throw ParseError("positional argument after a named one"); + named_seen = named_seen || !arg.name.empty(); + cmd.args.push_back(std::move(arg)); + } + return cmd; +} + +std::optional to_int(const Arg& arg) { + if (arg.quoted) return std::nullopt; + std::string digits; + for (char c : arg.text) + if (c != '_') digits += c; + if (digits.empty()) return std::nullopt; + long long value = 0; + const char* begin = digits.data(); + if (*begin == '+') ++begin; + const auto [ptr, ec] = std::from_chars(begin, digits.data() + digits.size(), value); + if (ec != std::errc{} || ptr != digits.data() + digits.size()) return std::nullopt; + return value; +} + +std::optional to_bool(const Arg& arg) { + if (arg.quoted) return std::nullopt; + const std::string v = canonical(arg.text); + if (v == "true" || v == "yes" || v == "on" || v == "1") return true; + if (v == "false" || v == "no" || v == "off" || v == "0") return false; + return std::nullopt; +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/parser.hpp b/src/cli/console/parser.hpp new file mode 100644 index 0000000..804a8c0 --- /dev/null +++ b/src/cli/console/parser.hpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The command line syntax of the console language (docs/CLI_CONCEPT/01-grundlagen.md, 1): +// +// [@] Name [ ( Argument {, Argument} ) ] +// +// Names ignore case and the characters '.' and '_' ("ListOptions" = "List.Options" = +// "list_options"). Arguments are positional or named (name=value; named ones only at the +// end), separated by commas at the top level; strings are "quoted" (\" and \\ escaped) or a +// single word, lists use [a, b]. The parser only splits a line; the types are checked against +// the command's parameter list by the console (E_BAD_ARGUMENT before anything happens). + +#include +#include +#include +#include +#include + +namespace bmh::cli::console { + +// One argument as written: `text` without the surrounding quotes, `quoted` if it was a +// "string", `name` empty for a positional argument. +struct Arg { + std::string name; + std::string text; + bool quoted = false; +}; + +struct Command { + int player = 0; // the @n prefix (1-4), 0 = the active player + std::string name; // as written + std::string key; // canonical(name) + std::vector args; +}; + +class ParseError final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +// Lower case without '.' and '_': the key commands are compared with. +std::string canonical(std::string_view name); + +// Splits one command line. Throws ParseError with a short reason on a syntax error. +Command parse_command(std::string_view line); + +// What a line of input is, before parsing: a command, the block confirmation "go.", the +// block reset "clear.", or nothing (empty line or // comment). +enum class LineKind { command, go, clear, skip }; +LineKind classify_line(std::string_view line); + +// Value conversion for the parameter check. Integers allow '_' as thousands separator and a +// sign; booleans accept true/false/yes/no/on/off/1/0. Quoted text is never a number/bool. +std::optional to_int(const Arg& arg); +std::optional to_bool(const Arg& arg); + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_balance.cpp b/src/cli/console/windows_balance.cpp new file mode 100644 index 0000000..fe489d9 --- /dev/null +++ b/src/cli/console/windows_balance.cpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// The balance plan (menu 28, mode III; docs/CLI_CONCEPT/06-verein.md 11, H2 p. 26-27): the +// projected income and expenses of the business year in three views, every item can be +// changed; leaving the window stores the plan figure the DFB gets on the 16th Bundesliga +// matchday. +// +// The screen logic is the engine's (src/game/balance_plan.hpp, a port of BalanceFromGame2); the +// console keeps the screen's draft while the window is open and closes it on GoBack. + +#include + +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/balance_plan.hpp" +#include "game/messages.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// row names in screen order (labels BalancePlan_DrawRows_TextPointer5 and BalancePlan_DrawRows_TextPointer4) +const std::vector kRowNames = { + "IncomeShirt", "IncomeBoards", "IncomeTv", "IncomeGate", "IncomePeriphery", "IncomeRentInterest", + "IncomeMisc", "ExpenseSalaries", "ExpenseStadium", "ExpenseYouth", "ExpenseCoTrainer", "ExpenseDoctor", + "ExpensePhysio", "ExpenseTrainingCamp", "ExpenseFanCare", "ExpensePr", "ExpenseInterest", "ExpenseMisc", + "LeagueHomeGames", "OtherHomeGames", "AverageGate", "TicketPrice", "GateSoFar", "Account"}; +const char* const kViews[] = {"SoFar", "Real", "Future"}; + +} // namespace + +void Console::register_balance_commands() { + auto show = [this] { + const BalancePlanDraft& d = *balance_draft_; + std::vector> rows; + for (int i = 0; i < kBalanceRows; i++) { + const bool money_row = i < kBalanceItems || i == kBalanceAccount; + rows.push_back({kRowNames[size_t(i)], money_row ? money(d.rows[size_t(i)]) : std::to_string(d.rows[size_t(i)]), + balance_row_maximum(d, i) >= 0 ? "yes" : "no"}); + } + emit('i', std::string("view ") + kViews[int(d.view)] + ", " + std::to_string(d.months_left) + " months left"); + emit_table({"Item", "Value", "Changeable"}, rows); + if (d.depreciation != 0) emit('i', "depreciation " + money(d.depreciation)); + emit('i', std::string(d.total < 0 ? "planned loss " : "planned profit ") + money((long long)(d.total < 0 ? -d.total : d.total))); + }; + openers_[28] = [this, show] { + balance_draft_ = app::BalanceActions(*session_).open_draft(active_slot()); + open_window("Balance"); + show(); + }; + closers_["Balance"] = [this] { + const BalancePlanDraft d = *balance_draft_; + balance_draft_.reset(); + const bool warning = app::BalanceActions(*session_).close_draft(d, revision_); + close_window(); + // the original's message box BalancePlan_BalanceFromGame_TextPointer2 (the plan is stored nevertheless) + if (warning) emit('i', bmh::message_text(session_->state(), ::bmh::layout::BalancePlan_BalanceFromGame_TextPointer2)); + emit('+', "balance plan stored: " + money((long long)d.total)); + }; + add({"Balance", "ShowBalance", {}, "all items, the view and the planned profit or loss", false}, [show](const Values&) { show(); }); + add({"Balance", "SetBalanceView", {choice("view", {kViews[0], kViews[1], kViews[2]})}, "left button: so far / real / future", false}, + [this, show](const Values& v) { + while (int(balance_draft_->view) != v.choice("view")) app::BalanceActions(*session_).cycle_draft(*balance_draft_); + show(); + }); + std::vector editable; + for (int i = 0; i < 0x16; i++) + if (balance_row_maximum(BalancePlanDraft{}, i) >= 0) editable.push_back(kRowNames[size_t(i)]); + add({"Balance", "SetBalanceItem", {choice("item", editable), integer("value", 0, 30000000)}, "change a planned value (views Real and Future)", false}, + [this, show, editable](const Values& v) { + const std::string& name = editable[size_t(v.choice("item"))]; + const int row = int(std::find(kRowNames.begin(), kRowNames.end(), name) - kRowNames.begin()); + switch (app::BalanceActions(*session_).edit_draft(*balance_draft_, row, int32_t(v.integer("value")))) { + case BalanceEditStatus::changed: break; + case BalanceEditStatus::view_so_far: fail("E_RULE", "Bitte den linken Button auf REAL oder ZUKUNFT stellen (SetBalanceView)"); + case BalanceEditStatus::out_of_range: + fail("E_BAD_ARGUMENT", name + " goes up to " + std::to_string(balance_row_maximum(*balance_draft_, row))); + default: fail("E_RULE", name + " cannot be changed"); + } + show(); + }); + add({"Balance", "TakeActuals", {}, "\"Werte akt.\": drop the own changes, back to the game's figures", false}, [this, show](const Values&) { + app::BalanceActions(*session_).reset_draft(*balance_draft_); + show(); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_club.cpp b/src/cli/console/windows_club.cpp new file mode 100644 index 0000000..f9e39e2 --- /dev/null +++ b/src/cli/console/windows_club.cpp @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The club windows of docs/CLI_CONCEPT/06-verein.md: Tactics (menu 18), Training (menu 16) +// and TrainingCamp (menu 15). The views come from CareerSession::preparation_projection, the +// changes go through dispatch_tactics / dispatch_training / dispatch_training_camp with the +// same requests the SDL screens build (src/ui/tactics.cpp, training.cpp, training_camp.cpp). + +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// 06-verein 2: the value range of the eight tactics settings (H2 p. 71) +constexpr int kTacticMax[8] = {3, 3, 3, 3, 1, 1, 1, 11}; + +const std::vector kTypes = {"TOR", "ABW", "MIT", "STU"}; +const std::vector kAreas = {"Fitness", "Skill", "Corner", "FreeKick", "Tackling", "Pass", "Shot", "Speed", "Game"}; +constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU (TrainingPlayer::position 0-3) + +// TEXTD indices (docs/formats/textd_inventory.csv) +constexpr int kCampQualityTitles = 362; // campPitchQuality .. campAccommodation (362-365) +constexpr int kCampResorts = 371; // campResortLodz .. (371-378), names differ per edition +constexpr int kCampPlayersReturnHappy = 1259; +constexpr int kCampRecentlyVisited = 1265; +constexpr int kCampBoardDeniesFurtherVisits = 1266; + +std::string balls(int n) { return std::string(size_t(std::max(0, n)), 'o'); } + +} // namespace + +void Console::register_club_commands() { + // --- Tactics (06-verein 2) ------------------------------------------------------------ + auto show_tactics = [this] { + const ui::TacticsState t = prep().tactics; + std::vector> rows; + for (size_t i = 0; i < 8; ++i) + rows.push_back({std::to_string(i), detail::kTacticNames[i], std::to_string(t.values[i]), std::to_string(kTacticMax[i])}); + emit_table({"Item", "Setting", "Value", "Max"}, rows); + emit('i', std::string("assistant attitude control: ") + on_off(t.assistant_attitude != 0)); + }; + openers_[18] = [this, show_tactics] { + open_window("Tactics"); + show_tactics(); + }; + add({"Tactics", "ShowTactics", {}, "the eight settings with value and maximum", false}, [show_tactics](const Values&) { show_tactics(); }); + auto set_tactic = [this, show_tactics](int item, int value) { + const ui::TacticsState t = prep().tactics; + if (value < 0 || value > kTacticMax[item]) + fail("E_BAD_ARGUMENT", "item " + std::to_string(item) + " takes 0.." + std::to_string(kTacticMax[item])); + if (t.values[size_t(item)] == value) { + emit('+', "item " + std::to_string(item) + " already " + std::to_string(value)); + return; + } + ui::TacticsRequest req; + req.kind = ui::TacticsRequestKind::set_tactic; + req.manager_slot = t.manager_slot; + req.runtime_club = t.runtime_club; + req.revision = revision_; + req.index = item; + req.desired_value = value; + // the offensive/defensive arrows switch the assistant's attitude control off + if (item == 0) req.desired_assistant_attitude = 0; + std::string error; + require_engine(session_->dispatch_tactics(req, revision_, error), "tactics", error); + emit('+', "item " + std::to_string(item) + " = " + std::to_string(value)); + }; + add({"Tactics", "SetTactic", {integer("item", 0, 7), integer("value", 0, 11)}, "set a value directly (item 0 ends the assistant's D/O control)", true}, + [set_tactic](const Values& v) { set_tactic(int(v.integer("item")), int(v.integer("value"))); }); + add({"Tactics", "CycleTactic", {integer("item", 0, 6)}, "a click: value + 1, after the maximum 0", true}, [this, set_tactic](const Values& v) { + const int item = int(v.integer("item")); + const int value = prep().tactics.values[size_t(item)]; + set_tactic(item, value >= kTacticMax[item] ? 0 : value + 1); + }); + + // --- Training (06-verein 3) ----------------------------------------------------------- + auto training = [this] { + const auto p = prep(); + if (!p.training) fail("E_MODE_LOCKED", "there is no training in mode I"); + return *p.training; + }; + auto training_request = [this](const ui::TrainingState& t, ui::TrainingRequestKind kind) { + ui::TrainingRequest r; + r.kind = kind; + r.manager_slot = t.manager_slot; + r.runtime_club = t.runtime_club; + r.revision = revision_; + r.desired_types = t.types; + r.desired_areas = t.areas; + r.desired_automation = t.automation; + return r; + }; + auto dispatch_training = [this](const ui::TrainingRequest& r) { + std::string error; + require_engine(session_->dispatch_training(r, revision_, error), "training", error); + }; + auto players_of = [](const ui::TrainingState& t) { + std::vector refs; + for (const auto& p : t.players) refs.push_back({p.row, p.player_id, utf8(p.name)}); + return refs; + }; + auto show_training = [this, training] { + const ui::TrainingState t = training(); + int type_sum = 0, fitness = 0, other = 0; + std::vector> types, areas; + for (size_t i = 0; i < 4; ++i) { + type_sum += t.types[i]; + types.push_back({kTypes[i], std::to_string(t.types[i]), balls(t.types[i])}); + } + for (size_t i = 0; i < 9; ++i) { + (i < 2 ? fitness : other) += t.areas[i]; + areas.push_back({kAreas[i], std::to_string(t.areas[i]), balls(t.areas[i])}); + } + emit_table({"Type", "Balls", ""}, types); + emit_table({"Area", "Balls", ""}, areas); + emit('i', "balls: type=" + std::to_string(type_sum) + "/8 areas=" + std::to_string(other) + "/18 (Fitness+Skill=" + + std::to_string(fitness) + "/4)" + (other > 14 ? " [specialTraining]" : "")); + std::vector> players; + for (const auto& p : t.players) + players.push_back({"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name), + p.position >= 0 && p.position < 4 ? text(kPositionNames + p.position) : "?", std::to_string(p.intensity), + std::to_string(p.focus)}); + emit_table({"Row", "Id", "Player", "Pos", "Intensity", "Focus"}, players); + emit('i', "automation bits: " + std::to_string(t.automation & 0x1f) + (t.needs_initialization() ? " (not initialized)" : "")); + }; + openers_[16] = [this, training, training_request, dispatch_training, show_training] { + const ui::TrainingState t = training(); + open_window("Training"); + // Initialize: the first opening initializes the plan (06-verein 3) + if (t.needs_initialization()) { + auto r = training_request(t, ui::TrainingRequestKind::initialize); + r.desired_automation = 0x9f; + dispatch_training(r); + emit('+', "Training initialized"); + } + show_training(); + }; + add({"Training", "ShowTraining", {}, "types, areas, sums, players, automation", false}, [show_training](const Values&) { show_training(); }); + // The engine accepts 1-3 balls (CareerSession::dispatch_training, valid_plan); the + // concept's 0..3 would leave a field empty, which the original screen does not allow. + add({"Training", "SetTrainingType", {choice("type", kTypes), integer("balls", 1, 3)}, "balls of a player type (sum <= 8)", true}, + [this, training, training_request, dispatch_training](const Values& v) { + const ui::TrainingState t = training(); + const int type = v.choice("type"), value = int(v.integer("balls")); + if (t.types[size_t(type)] == value) { + emit('+', kTypes[size_t(type)] + " already " + std::to_string(value)); + return; + } + auto r = training_request(t, ui::TrainingRequestKind::set_type); + r.index = type; + r.value = value; + r.desired_types[size_t(type)] = uint8_t(value); + r.desired_automation &= uint8_t(~2); + int sum = 0; + for (auto b : r.desired_types) sum += b; + if (sum > 8) fail("E_RULE", "the four player types may have 8 balls together (would be " + std::to_string(sum) + ")"); + dispatch_training(r); + emit('+', kTypes[size_t(type)] + " = " + std::to_string(value)); + }); + add({"Training", "SetTrainingArea", {choice("area", kAreas), integer("balls", 1, 3)}, "balls of a training area (F+S <= 4, rest <= 18)", true}, + [this, training, training_request, dispatch_training](const Values& v) { + const ui::TrainingState t = training(); + const int area = v.choice("area"), value = int(v.integer("balls")); + if (t.areas[size_t(area)] == value) { + emit('+', kAreas[size_t(area)] + " already " + std::to_string(value)); + return; + } + auto r = training_request(t, ui::TrainingRequestKind::set_area); + r.index = area; + r.value = value; + r.desired_areas[size_t(area)] = uint8_t(value); + r.desired_automation &= uint8_t(~4); + int fitness = 0, other = 0; + for (size_t i = 0; i < 9; ++i) (i < 2 ? fitness : other) += r.desired_areas[i]; + if (fitness > 4) fail("E_RULE", "Fitness and Skill may have 4 balls together (would be " + std::to_string(fitness) + ")"); + if (other > 18) fail("E_RULE", "the seven other areas may have 18 balls together (would be " + std::to_string(other) + ")"); + dispatch_training(r); + emit('+', kAreas[size_t(area)] + " = " + std::to_string(value)); + }); + Param player = detail::text("player"); + player.display = "player:Player"; + add({"Training", "SetPlayerIntensity", {player, integer("intensity", 1, 3)}, "training intensity of a player", true}, + [this, training, training_request, dispatch_training, players_of](const Values& v) { + const ui::TrainingState t = training(); + const auto& p = t.players[resolve_player(v.text("player"), players_of(t))]; + const int value = int(v.integer("intensity")); + if (p.intensity == value) { + emit('+', utf8(p.name) + " already " + std::to_string(value)); + return; + } + auto r = training_request(t, ui::TrainingRequestKind::set_player_intensity); + r.index = p.row; + r.player_id = p.player_id; + r.value = value; + r.desired_automation &= uint8_t(~8); + dispatch_training(r); + emit('+', utf8(p.name) + ": intensity " + std::to_string(value)); + }); + add({"Training", "CyclePlayerFocus", {player}, "the player's focus symbol: next focus", true}, + [this, training, training_request, dispatch_training, players_of](const Values& v) { + const ui::TrainingState t = training(); + const auto& p = t.players[resolve_player(v.text("player"), players_of(t))]; + auto r = training_request(t, ui::TrainingRequestKind::set_player_focus); + r.index = p.row; + r.player_id = p.player_id; + r.value = (int(p.focus) + 1) % 8; + dispatch_training(r); + emit('+', utf8(p.name) + ": focus " + std::to_string(r.value)); + }); + add({"Training", "SetTrainingAutomation", {integer("index", 0, 4), boolean("on")}, "one automation bit (D p. 109)", true}, + [this, training, training_request, dispatch_training](const Values& v) { + const ui::TrainingState t = training(); + const int index = int(v.integer("index")); + const bool on = v.boolean("on"); + const uint8_t mask = uint8_t(1u << index); + if (((t.automation & mask) != 0) == on) { + emit('+', "automation bit " + std::to_string(index) + " already " + on_off(on)); + return; + } + auto r = training_request(t, ui::TrainingRequestKind::set_automation); + r.index = index; + r.value = on ? 1 : 0; + r.desired_automation = uint8_t((t.automation & ~mask) | (on ? mask : 0)); + dispatch_training(r); + emit('+', "automation bit " + std::to_string(index) + " " + on_off(on)); + }); + add({"Training", "InitializeTraining", {}, "the original initialization (only when needed)", true}, + [this, training, training_request, dispatch_training](const Values&) { + const ui::TrainingState t = training(); + if (!t.needs_initialization()) { + emit('+', "training is already initialized"); + return; + } + auto r = training_request(t, ui::TrainingRequestKind::initialize); + r.desired_automation = 0x9f; + dispatch_training(r); + emit('+', "Training initialized"); + }); + + // --- TrainingCamp (06-verein 4) ------------------------------------------------------- + auto camp = [this] { + const auto p = prep(); + if (!p.training_camp) fail("E_MODE_LOCKED", "no training camp available"); + return *p.training_camp; + }; + auto camp_request = [this](const ui::TrainingCampState& c, ui::TrainingCampRequestKind kind) { + ui::TrainingCampRequest r; + r.kind = kind; + r.manager_slot = c.manager_slot; + r.runtime_club = c.runtime_club; + r.revision = revision_; + r.focus = c.focus; + return r; + }; + auto visits_text = [this](const ui::TrainingCampState& c) { + if (c.booked_this_week()) return "booked this week"; + return c.visit_count() < 3 ? "" : "no visit possible"; + }; + auto show_camp = [this, camp, visits_text] { + const ui::TrainingCampState c = camp(); + emit_table({"Slider", "Value"}, + {{text(367), std::to_string(c.focus[0])}, {text(368), std::to_string(c.focus[1])}, + {text(369), std::to_string(c.focus[2])}, {text(370), std::to_string(c.focus[3])}}); + std::string state = visits_text(c); + emit('i', "visits this season: " + std::to_string(c.visit_count()) + "/3" + (state.empty() ? "" : " (" + state + ")") + + ", balance " + money(c.balance)); + }; + openers_[15] = [this, camp, camp_request, show_camp] { + const ui::TrainingCampState c = camp(); + open_window("TrainingCamp"); + // SetTrainingCampFocus derives the fourth slider while drawing; the screen writes it back + // once when it differs (TrainingCampScreen::initialize_focus) + if (c.focus_normalization_required) { + std::string error; + require_engine(session_->dispatch_training_camp(camp_request(c, ui::TrainingCampRequestKind::set_focus), revision_, error), + "training camp", error); + } + show_camp(); + }; + add({"TrainingCamp", "ListResorts", {}, "the eight sports schools with stars and price", false}, [this, camp, visits_text](const Values&) { + const ui::TrainingCampState c = camp(); + std::vector> rows; + for (size_t r = 0; r < 8; ++r) + rows.push_back({std::to_string(r), text(kCampResorts + int(r)), std::to_string(c.quality[r][0]), std::to_string(c.quality[r][1]), + std::to_string(c.quality[r][2]), std::to_string(c.quality[r][3]), money(c.prices[r])}); + emit_table({"Resort", "Name", text(kCampQualityTitles), text(kCampQualityTitles + 1), text(kCampQualityTitles + 2), + text(kCampQualityTitles + 3), "Price"}, + rows); + std::string state = visits_text(c); + emit('i', "visits this season: " + std::to_string(c.visit_count()) + "/3" + (state.empty() ? "" : " (" + state + ")")); + }); + add({"TrainingCamp", "ShowCamp", {}, "sliders, recuperation, visits", false}, [show_camp](const Values&) { show_camp(); }); + add({"TrainingCamp", "SetCampFocus", {integer("fitness", 0, 15), integer("skill", 0, 15), integer("game", 0, 15)}, + "the three sliders; recuperation follows", true}, + [this, camp, camp_request, show_camp](const Values& v) { + const ui::TrainingCampState c = camp(); + auto r = camp_request(c, ui::TrainingCampRequestKind::set_focus); + r.focus[0] = uint8_t(v.integer("fitness")); + r.focus[1] = uint8_t(v.integer("skill")); + r.focus[2] = uint8_t(v.integer("game")); + r.focus[3] = uint8_t(15 - (r.focus[0] + r.focus[1] + r.focus[2]) / 3); // SetTrainingCampFocus + if (r.focus == c.focus) { + emit('+', "sliders unchanged"); + return; + } + std::string error; + require_engine(session_->dispatch_training_camp(r, revision_, error), "training camp", error); + show_camp(); + }); + add({"TrainingCamp", "BookCamp", {integer("resort", 0, 7)}, "MACH ICH: book the sports school", true}, + [this, camp, camp_request](const Values& v) { + const ui::TrainingCampState c = camp(); + if (c.booked_this_week()) fail("E_RULE", text(kCampRecentlyVisited), "campRecentlyVisited"); + if (c.visit_count() >= 3) fail("E_RULE", text(kCampBoardDeniesFurtherVisits), "campBoardDeniesFurtherVisits"); + auto r = camp_request(c, ui::TrainingCampRequestKind::book); + r.resort = int(v.integer("resort")); + std::string error; + require_engine(session_->dispatch_training_camp(r, revision_, error), "training camp", error); + const ui::TrainingCampState after = camp(); + switch (after.feedback) { + case ui::TrainingCampFeedback::insufficient_funds: fail("E_INSUFFICIENT_FUNDS", "the camp costs " + money(c.prices[size_t(r.resort)])); + case ui::TrainingCampFeedback::booked_this_week: fail("E_RULE", text(kCampRecentlyVisited), "campRecentlyVisited"); + case ui::TrainingCampFeedback::visit_limit: fail("E_RULE", text(kCampBoardDeniesFurtherVisits), "campBoardDeniesFurtherVisits"); + default: break; + } + emit('+', text(kCampResorts + r.resort) + " booked for " + money(c.prices[size_t(r.resort)]) + ". " + text(kCampPlayersReturnHappy)); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_desk.cpp b/src/cli/console/windows_desk.cpp new file mode 100644 index 0000000..27eb471 --- /dev/null +++ b/src/cli/console/windows_desk.cpp @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The desk (docs/CLI_CONCEPT/04-schreibtisch.md): its displays, Open/Key, the widgets +// (ticket price, automation), Kickoff with the day's results, and the mailbox "Kicker". + +#include +#include + +#include "app/window_actions.hpp" +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/schedule.hpp" +#include "ui/advertising.hpp" +#include "ui/desk_state.hpp" +#include "ui/desktop.hpp" +#include "ui/league_table.hpp" +#include "ui/matchday_results.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// 02-fenster 6: menu_kind -> window +const char* const kMenuWindows[30] = { + "LeagueTable", "Fixtures", "Strengths", "Lineup", "Achievements", "OtherGames", "Friendlies", "Reschedule", + "Calendar", "IndoorTable", "LoadGame", "SaveGame", "Kickoff", "Toto", "Bank", "TrainingCamp", + "Training", "Transfer", "Tactics", "Settings", "TopScorers", "Advertising", "Stadium", "Statistics", + "Environment", "FairPlay", "HighScore", "Contracts", "Balance", "NewPlayer"}; +constexpr int kMailboxMenu = 63; // the mailbox shortcut (desk item kind 63) + +// 02-fenster 5: the desk's keys (H2 S. 17). The training camp has no key (conflict with L). +const std::map kKeys = {{'Z', 28}, {'T', 0}, {'S', 2}, {'X', 5}, {'K', 8}, {'G', 12}, {'B', 14}, {'I', 16}, + {'E', 19}, {'W', 21}, {'U', 24}, {'N', 29}, {'L', 1}, {'A', 3}, {'F', 6}, {'H', 9}, + {'O', 13}, {'M', 17}, {'D', 18}, {'C', 20}, {'Y', 22}, {'V', 27}}; + +// The ten warning lamps in the order of DeskState::warnings (Fill, 04-schreibtisch 2). +const char* const kLamps[10] = {"shares", "overdraft", "freeAdSlots", "specialTraining", "exhaustedPlayer", + "squadSize", "reserve", "tacticsEmphasis", "contracts", "license"}; +// The five automations in the order of DeskState::automation (ManagerAutomation + manager * 5). +const std::vector kAutomation = {"Lineup", "Substitution", "Tactics", "Marking", "Training"}; + +constexpr int kCompetitionNames = 579; // CupDraw_FormatError_ExecutableField6: competitionNameDfbCup, UefaCup, ... + +const char* const kWeekdays[7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; + +} // namespace + +namespace detail { + +std::string menu_window(int menu) { + if (menu >= 0 && menu < 30) return kMenuWindows[menu]; + if (menu == kMailboxMenu) return "Mailbox"; + return {}; +} + +int menu_of_window(std::string_view name) { + for (int i = 0; i < 30; ++i) + if (canonical(kMenuWindows[i]) == canonical(name)) return i; + if (canonical(name) == "mailbox") return kMailboxMenu; + return -1; +} + +} // namespace detail + +int Console::active_slot() const { return session_->desktop_projection(revision_).manager_slot; } + +void Console::own_view_only(int player, const std::string& command) const { + if (player && player_ && player != player_) + detail::fail("E_NOT_YOUR_TURN", command + " shows the manager on turn (player " + std::to_string(player_) + + "), not yours - WaitTurn waits for your turn"); +} +ui::DeskState Console::desk() const { return session_->desktop_projection(revision_); } +ui::PreparationState Console::prep() const { return session_->preparation_projection(revision_); } + +// The engine says why it refused; the console passes it on (E_INSUFFICIENT_FUNDS for money). +// The engine reports refusals in two internal forms: snake_case codes of the session +// ("amount_unavailable") and, from the ported Source functions, "SubmitTransferBidSourceHumanBuyer: " for a +// case the port does not cover yet. Players and agents get readable text instead: codes +// with a known meaning get a sentence, other codes their words, and a FUN prefix marks an +// engine gap (the reason stays for the bug report, the internal name goes). +void Console::require_engine(bool ok, const std::string& what, const std::string& error) { + if (ok) return; + static const std::pair kReadable[] = { + {"invalid_amount", "the amount is not valid (1 to 99,999,999)"}, + {"amount_unavailable", "not that much money there (account balance or fixed deposit)"}, + {"insufficient_funds", "not enough money"}, + {"invalid_ticket_price", "the ticket price is out of range"}, + {"invalid_share_count", "the number of shares is not valid"}, + {"invalid_fund_count", "the number of fund shares is not valid"}, + {"investment_limit", "the investment limit is reached"}, + {"visit_limit", "no more visits possible"}, + {"career_complete", "the game is over"}, + {"toto_coupon_requires_eleven_matches", "the coupon needs a tip for all eleven matches"}, + {"free_agent_loan_refused", "a free agent (Spielerberater) can only be bought, not loaned - the original refuses it too"}, + }; + std::string text = error.empty() ? std::string("refused") : error; + if (text.size() > 4 && text.compare(0, 3, "FUN") == 0) { + const size_t colon = text.find(": "); + if (colon != std::string::npos && colon < 12) + fail("E_ENGINE_GAP", what + ": this case is not ported yet (" + text.substr(colon + 2) + ")"); + } + bool code = !text.empty(); + for (const char c : text) code = code && ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'); + if (code) { + std::string readable; + for (const auto& [key, sentence] : kReadable) + if (text == key) readable = sentence; + if (readable.empty()) { + readable = text; + std::replace(readable.begin(), readable.end(), '_', ' '); + } + text = readable; + } + if (error.find("insufficient") != std::string::npos || error.find("funds") != std::string::npos) + fail("E_INSUFFICIENT_FUNDS", what + ": " + text); + fail("E_RULE", what + ": " + text); +} + +// The desk of the active manager: window, player, and the messages not yet reported. +void Console::enter_desktop() { + const ui::DeskState d = desk(); + set_window("Desktop", d.manager_slot + 1); + report_new_mail(); + // Advertising places whose contract ran out stay blocked until the manager answers the + // renewal (CheckAdvertisingRenewal, on the click = ListAdOffers); the month-change message is easy + // to miss, so the desk repeats it (issue #44). + if (!d.national_team) { + try { + const ui::AdvertisingState a = ui::advertising_from_game(session_->state(), d.manager_slot, revision_); + std::string expired; + for (int slot = 0; slot < 16; ++slot) + if (a.offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension) + expired += (expired.empty() ? "" : ", ") + + (slot < 14 ? "Board" + std::to_string(slot + 1) : std::string(slot == 14 ? "Shirt" : "Tv")); + if (!expired.empty()) + emit('i', "advertising contracts ran out: " + expired + " (Open(Advertising), ListAdOffers() renews or frees them)"); + } catch (const std::exception&) { + } + } +} + +// New messages show as "i" lines on the desk of the manager they belong to (04-schreibtisch 3). +// The mailbox has no read flag; the console remembers what it has shown per manager. +void Console::report_new_mail() { + const int slot = active_slot(); + const ui::MailboxState mail = ui::mailbox_state_from_game(session_->state(), slot, revision_); + auto& seen = seen_mail_[slot]; + for (const auto& m : mail.messages) { + const std::string key = std::to_string(m.date_counter) + "|" + m.text; + if (seen.insert(key).second) emit('i', "New message: " + m.text); + } +} + +void Console::register_desk_commands() { + // --- Desktop: displays (04-schreibtisch 1) --------------------------------------------- + auto show_date = [this] { + const ui::DeskState d = desk(); + std::vector> rows = { + {"date", date_text(d.date.day, d.date.month, d.date.year)}, + {"weekday", d.date.weekday >= 0 && d.date.weekday < 7 ? kWeekdays[d.date.weekday] : "?"}, + {"season", std::to_string(d.season_index + 1)}, + {"seasonDay", std::to_string(d.season_day)}}; + if (d.league_round) rows.push_back({"leagueRound", std::to_string(*d.league_round)}); + emit_table({"Date", "Value"}, rows); + }; + auto show_finance = [this] { + const ui::DeskState d = desk(); + emit_table({"Finance", "Value"}, + {{"balance", money(d.balance)}, {"savings", money(d.savings)}, {"ticketPrice", std::to_string(d.ticket_price)}}); + }; + auto show_fans = [this] { emit_table({"Fans", "Value"}, {{"standing", std::to_string(desk().fans)}}); }; + auto show_lamps = [this] { + const ui::DeskState d = desk(); + std::vector> rows; + for (size_t i = 0; i < 10; ++i) + rows.push_back({std::to_string(i / 5 + 1) + "." + std::to_string(i % 5 + 1), kLamps[i], + d.warnings[i] ? on_off(*d.warnings[i]) : "unknown"}); + emit_table({"Lamp", "Name", "State"}, rows); + }; + auto show_automation = [this] { + const ui::DeskState d = desk(); + std::vector> rows; + for (size_t i = 0; i < 5; ++i) { + // Lineup holds the number of the saved formation used (0 = off, SizeT6); + // the others are bit 0 of their option byte + std::string state = i == 0 ? (d.automation[0] ? "on (formation " + std::to_string(d.automation[0]) + ")" : "off") + : on_off(d.automation[i] & 1); + rows.push_back({kAutomation[i], state}); + } + emit_table({"Automation", "State"}, rows); + }; + auto show_opponent = [this] { + const ui::DeskState d = desk(); + std::vector> rows; + rows.push_back({"competition", utf8(d.next_competition_label) + + (d.next_competition_detail.empty() ? "" : " " + utf8(d.next_competition_detail))}); + rows.push_back({"opponent", d.next_opponent_name.empty() ? "-" : utf8(d.next_opponent_name)}); + if (!d.next_opponent_name.empty()) rows.push_back({"venue", d.next_match_away ? "away" : "home"}); + if (d.table_position) rows.push_back({"ownTablePosition", std::to_string(*d.table_position)}); + if (d.strength) rows.push_back({"ownStrength", std::to_string(*d.strength)}); + emit_table({"Next game", "Value"}, rows); + }; + add({"Desktop", "ShowDesk", {}, "all displays of the desk", false}, + [this, show_date, show_finance, show_fans, show_lamps, show_automation, show_opponent](const Values&) { + const ui::DeskState d = desk(); + emit_table({"Manager", "Club"}, {{utf8(d.manager_name), utf8(d.club_name)}}); + show_date(); + show_finance(); + show_fans(); + show_opponent(); + show_lamps(); + show_automation(); + const auto mail = ui::mailbox_state_from_game(session_->state(), d.manager_slot, revision_); + emit_table({"Mailbox", "Value"}, {{"messages", std::to_string(mail.messages.size())}}); + }); + add({"Desktop", "ShowDate", {}, "date, weekday, season day, league round", false}, [show_date](const Values&) { show_date(); }); + add({"Desktop", "ShowFinance", {}, "balance, savings, ticket price", false}, [show_finance](const Values&) { show_finance(); }); + add({"Desktop", "ShowFanStanding", {}, "standing with the fans", false}, [show_fans](const Values&) { show_fans(); }); + add({"Desktop", "ShowLamps", {}, "the ten warning lamps", false}, [show_lamps](const Values&) { show_lamps(); }); + add({"Desktop", "ShowLastGames", {}, "the last six games", false}, [](const Values&) { + fail("E_ENGINE_GAP", "the last games are not in the desk projection yet"); + }); + add({"Desktop", "ShowOpponent", {}, "the next game and opponent", false}, [show_opponent](const Values&) { show_opponent(); }); + Param curves = detail::text("which", 0, true); + curves.display = "[own|opponent]"; + add({"Desktop", "ShowPositionCurves", {curves}, "table positions per matchday", false}, [](const Values&) { + fail("E_ENGINE_GAP", "the position curves are not in the desk projection yet"); + }); + add({"Desktop", "ShowAutomation", {}, "the five automations", false}, [show_automation](const Values&) { show_automation(); }); + + // --- Desktop: actions ------------------------------------------------------------------ + Param target = detail::text("window"); + target.display = "window:enum|menu:int"; + add({"Desktop", "Open", {target}, "open a window (click on its icon); see the lines below", false}, [this](const Values& v) { + Arg a; + a.text = v.text("window"); + int menu = menu_of_window(a.text); + if (menu < 0) + if (const auto n = to_int(a); n && (*n >= 0 && *n < 30)) menu = int(*n); + if (menu < 0) fail("E_BAD_ARGUMENT", "no window " + a.text + " on the desk (ListOptions shows them)"); + open_menu(menu); + }); + add({"Desktop", "Key", {choice("letter", {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", + "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"})}, + "a key on the desk (G = Kickoff)", false}, + [this](const Values& v) { + const char letter = char('A' + v.choice("letter")); + const auto it = kKeys.find(letter); + if (it == kKeys.end()) fail("E_BAD_ARGUMENT", std::string("the key ") + letter + " has no function on the desk"); + open_menu(it->second); + }); + // The desk settings without the drawer layout (CareerSession::dispatch_ticket_price / + // dispatch_automation, issue #11): the same writes as the open widgets. + auto setting_owner = [this] { + const ui::DeskState d = desk(); + app::DeskSettingIdentity id; + id.manager_slot = d.manager_slot; + id.runtime_club = d.runtime_club; + if (d.runtime_club >= 0 && size_t(d.runtime_club) < session_->state().club_ids.size()) + id.stable_club_identity = int(session_->state().club_ids[size_t(d.runtime_club)]); + id.revision = revision_; + return id; + }; + add({"Desktop", "SetTicketPrice", {integer("price", 8, 25)}, "the ticket price (price scale)", true}, [this](const Values& v) { + std::string error; + require_engine(app::DeskActions(*session_).ticket_price(desk(), int(v.integer("price")), revision_, error), "ticket price", error); + emit('+', "ticket price: " + std::to_string(desk().ticket_price)); + }); + Param formation = integer("formation", 1, 8, true); + add({"Desktop", "SetAutomation", {choice("feature", kAutomation), boolean("on"), formation}, + "switch one of the five automations (Lineup: a saved formation 1-8)", true}, + [this, setting_owner](const Values& v) { + const int feature = v.choice("feature"); + const bool on = v.boolean("on"); + app::AutomationRequest r; + r.identity = setting_owner(); + r.automation = static_cast(feature); + r.enabled = on; + if (feature == 0 && on) { + // the line-up automation uses a saved formation: the given one, or the first available + int slot = int(v.integer("formation", 0)); + if (!slot) { + const auto p = prep(); + if (p.pitch) + for (int f = 0; f < 8 && !slot; ++f) + if (p.pitch->formation_mask & (1 << f)) slot = f + 1; + } + if (!slot) fail("E_RULE", "no saved formation for the lineup automation"); + r.formation = slot; + } else if (v.has("formation")) { + fail("E_BAD_ARGUMENT", "only Lineup on takes a formation"); + } + std::string error; + require_engine(session_->dispatch_automation(r, revision_, error), "automation", error); + emit('+', kAutomation[size_t(feature)] + " " + on_off(on) + (r.formation ? " (formation " + std::to_string(*r.formation) + ")" : "")); + }); + add({"Desktop", "Kickoff", {}, "hand over to the next player or start the day", true}, [this](const Values&) { kickoff(); }); + add({"Desktop", "OpenMailbox", {}, "open the mailbox (Kicker)", false}, [this](const Values&) { open_menu(kMailboxMenu); }); + add({"Desktop", "OpenDrawer", {}, "open the menu bar", false}, [](const Values&) { + fail("E_ENGINE_GAP", "the desk layout (drawer, folders) is not ported yet"); + }); + add({"Desktop", "PullPlug", {}, "the plug: quit after a question", false}, [this](const Values&) { + ask("Quit the game? Unsaved progress is lost.", {"Yes", "No"}, "No", [this](const std::string& answer) { + if (answer == "Yes") { + ended_ = true; + emit('+', "session ended"); + } else { + emit('+', "quit cancelled"); + } + }); + }); + + // --- Mailbox (04-schreibtisch 3) ------------------------------------------------------- + add({"Mailbox", "ListMessages", {}, "the messages of this manager (msg numbers for Keep/Delete)", false}, [this](const Values&) { + const ui::MailboxState mail = ui::mailbox_state_from_game(session_->state(), active_slot(), revision_); + listed_mail_ = mail.messages; + std::vector> rows; + for (size_t i = 0; i < mail.messages.size(); ++i) { + const auto& m = mail.messages[i]; + std::string to = m.general_broadcast ? "all" : ""; + if (!m.general_broadcast) + for (int r : m.recipient_managers) to += (to.empty() ? "P" : ",P") + std::to_string(r + 1); + rows.push_back({std::to_string(i + 1), std::to_string(m.date_counter), m.text, m.kept_for_manager ? "yes" : "no", to}); + } + emit_table({"Msg", "Day", "Text", "Kept", "To"}, rows); + }); + auto mail_action = [this](const Values& v, ui::MailboxActionKind kind) { + const size_t n = size_t(v.integer("msg")); + if (n < 1 || n > listed_mail_.size()) fail("E_BAD_ARGUMENT", "msg numbers refer to the last ListMessages"); + const auto& m = listed_mail_[n - 1]; + const auto req = app::MailboxActions::request(active_slot(), revision_, kind, m); + std::string error; + if (!app::MailboxActions(*session_).dispatch(req, revision_, error)) fail("E_RULE", "mailbox: " + error); + listed_mail_.clear(); // entries are compacted; numbers are no longer valid + }; + add({"Mailbox", "KeepMessage", {integer("msg", 1, 1000)}, "keep a message / let it go (at most five)", true}, + [this, mail_action](const Values& v) { + mail_action(v, ui::MailboxActionKind::toggle_keep); + emit('+', "keep toggled (list again for new numbers)"); + }); + add({"Mailbox", "DeleteMessage", {integer("msg", 1, 1000)}, "throw a message away", true}, [this, mail_action](const Values& v) { + mail_action(v, ui::MailboxActionKind::delete_for_manager); + emit('+', "message deleted (list again for new numbers)"); + }); +} + +// A click on a desk icon. Mode-locked icons answer E_MODE_LOCKED (02-fenster 4); windows the +// console does not have yet answer E_ENGINE_GAP. +void Console::open_menu(int menu) { + const ui::DeskState d = desk(); + if (menu == 12) { + kickoff(); + return; + } + const bool shortcut = menu == kMailboxMenu && d.mailbox_shortcut; + const auto item = std::find_if(d.items.begin(), d.items.end(), [menu](const ui::DeskItem& i) { return i.kind == menu; }); + // An icon is dimmed by the game mode, at the national coach's desk, or for the moment + // (HasNoEquivalentCondition's button states); name the reason that applies. + if (!shortcut && (item == d.items.end() || item->disabled)) + fail("E_MODE_LOCKED", menu_window(menu) + + (d.national_team ? " is not available while you coach the national team" + : item == d.items.end() + ? " is not available in this game (mode " + std::to_string(d.options.mode) + ")" + : " is not available at the moment")); + switch (menu) { + case 0: + open_window("LeagueTable"); + table_league_ = -1; + show_league_table(); + return; + case 1: + open_fixtures(); + return; + case 10: + case 11: + browse_directory_ = std::filesystem::absolute(save_directory()).lexically_normal(); + selected_file_.clear(); + open_window(menu == 10 ? "LoadGame" : "SaveGame"); + emit('+', "directory: " + shown_directory()); + return; + case kMailboxMenu: + open_window("Mailbox"); + listed_mail_.clear(); + emit('+', "mailbox opened (ListMessages)"); + return; + default: + if (const auto it = openers_.find(menu); it != openers_.end()) { + it->second(); + return; + } + fail("E_ENGINE_GAP", menu_window(menu) + " is not in the console yet (stage 2/3 of docs/CLI_CONCEPT)"); + } +} + +// The calendar (key G): the active manager hands over; after the last one the day runs +// (04-schreibtisch 4). Time mode "instant": the matches run without intervention and the +// results are printed afterwards (Info.FinalResults, 07-spieltag). +void Console::kickoff() { + const ui::DeskState before = desk(); + ui::DeskRequest req; + req.kind = ui::DeskRequestKind::advance_turn; + req.manager_slot = before.manager_slot; + req.revision = revision_; + // The day runs on the engine thread (windows_match.cpp): a human match pauses it in the + // Match window (time mode stepped), a question of the engine (offers for own players) + // pauses it in any mode; finish_kickoff follows when the engine is done. + start_matchday(req, before); +} + +// After the engine finished a kickoff: the info windows, the day's results and the next desk. +void Console::finish_kickoff(const ui::DeskState& before, const TurnAdvanceResult& advanced, const std::string& error) { + if (advanced.kind == TurnDeskKind::Failed || advanced.kind == TurnDeskKind::WaitingAtDesk) { + pending_info_.clear(); + fail("E_INTERNAL", "kickoff failed: " + (error.empty() ? advanced.reason : error)); + } + flush_info(); + if (const auto& results = session_->completed_matchday_results(); results && results->valid && !results->groups.empty()) { + set_window("Info.FinalResults", 0); + emit('i', "Results " + results->date_label); + for (const auto& group : results->groups) { + // the group's own competition: a league by its table title, a cup by the TEXTD + // competition names CupDraw_FormatError_ExecutableField6 (competitionNameDfbCup ..), as the cup draw does + std::string name = group.competition; + if (group.league_id) + name = ui::league_table_from_game(session_->state(), active_slot(), *group.league_id).league_name; + // (the indoor tournament, 0xb, has a runtime name: TEXTD only holds the placeholder + // "...xxx"; the projection already carries the name frozen for these results) + else if (group.cup_id && *group.cup_id >= 0 && *group.cup_id < 13 && (*group.cup_id != 0xb || bmh::kEnglishCompetitions)) + name = text(kCompetitionNames + *group.cup_id); + if (group.matches.empty()) continue; + emit('i', name + ":"); + std::vector> rows; + for (const auto& m : group.matches) { + std::string result; + switch (m.status) { + case ui::MatchResultStatus::played: + result = (m.home_goals ? std::to_string(*m.home_goals) : "?") + ":" + (m.away_goals ? std::to_string(*m.away_goals) : "?"); + // a cup match beyond 90 minutes; on penalties the score holds the + // shoot-out goals too (as the original stores it) + if (m.decided == 1) result += " aet"; + if (m.decided == 2) result += " pen (incl. shoot-out)"; + break; + case ui::MatchResultStatus::postponed: result = "postponed"; break; + case ui::MatchResultStatus::not_played: result = "not played"; break; + case ui::MatchResultStatus::unknown: result = "?"; break; + } + rows.push_back({m.home, m.away, result}); + } + emit_table({"Home", "Away", "Result"}, rows); + } + } + if (advanced.kind == TurnDeskKind::CareerComplete) { + set_window("GameEnd", 0); + emit('+', "Game over (" + std::to_string(session_->state().season) + " seasons)"); + career_ = false; + return; + } + const ui::DeskState after = desk(); + set_window("Desktop", after.manager_slot + 1); + if (after.day_counter == before.day_counter && after.manager_slot != before.manager_slot) + emit('+', "Next: Player " + std::to_string(after.manager_slot + 1)); + else + emit('+', std::string(advanced.kind == TurnDeskKind::SeasonEndDesk ? "Season end: " : "Next day: ") + + date_text(after.date.day, after.date.month, after.date.year)); + report_new_mail(); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_environment.cpp b/src/cli/console/windows_environment.cpp new file mode 100644 index 0000000..db064d6 --- /dev/null +++ b/src/cli/console/windows_environment.cpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-only +// OpenBMH deviates from the original: uses monthly staff levels in increments of five thousand and the supported youth-academy controls. +// The club environment (menu 24, docs/CLI_CONCEPT/06-verein.md 10, H2 p. 93, supported rule profile p. 107, +// 111): co-trainer, doctor and physio in levels of 5 000 a month, and the supported rule profile youth +// academy that costs a season price of the league. +// +// The rules are the engine's (src/game/environment.hpp, a port of Image with the +// supported rule profile patch); a command is one click of the original screen. + +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/environment.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +void Console::register_environment_commands() { + auto show = [this] { + const EnvironmentState s = environment_state(session_->state(), active_slot()); + std::vector> rows = { + {"AssistantCoach", std::to_string(s.level[kCoTrainer]), money(s.monthly[kCoTrainer])}, + {"Doctor", std::to_string(s.level[kDoctor]), money(s.monthly[kDoctor])}, + {"Physio", std::to_string(s.level[kPhysio]), money(s.monthly[kPhysio])}, + {"YouthAcademy", s.monthly[kYouthAcademy] != 0 ? "on" : "off", money(s.youth_price) + " per season"}}; + emit_table({"Item", "Level", "Costs"}, rows); + emit('i', std::string("youth academy: ") + (s.youth_paid ? "paid this season" : s.youth_open ? "can be started (July/August)" + : "too late for this season")); + }; + openers_[24] = [this, show] { + open_window("Environment"); + show(); + }; + add({"Environment", "ShowEnvironment", {}, "staff levels and the youth academy", false}, [show](const Values&) { show(); }); + auto apply = [this, show](int item, int level) { + std::string error; + const auto r=app::EnvironmentActions(*session_).set_console( + ui::environment_from_game(session_->state(),revision_),item,level,revision_,error, + [this](const GameState&,const std::string& message) { emit('i',utf8(message));return true; }); + if(!r||*r==EnvironmentResult::invalid) fail("E_BAD_ARGUMENT", "no such item or level"); + show(); + }; + add({"Environment", "SetStaffLevel", {choice("role", {"AssistantCoach", "Doctor", "Physio"}), integer("level", 0, 6)}, + "click a staff tile: level 0..6, 5 000 a month each", true}, + [apply](const Values& v) { apply(kCoTrainer + v.choice("role"), int(v.integer("level"))); }); + add({"Environment", "SetYouthAcademy", {choice("state", {"On", "Off"})}, "start (July/August) or stop the youth academy", true}, + [this, apply](const Values& v) { + const bool on = environment_state(session_->state(), active_slot()).monthly[kYouthAcademy] != 0; + const bool want = v.choice("state") == 0; + // the original's click on an active academy switches it off: click only for a change + if (on == want) emit('+', std::string("youth academy already ") + (on ? "on" : "off")); + else apply(kYouthAcademy, want ? 6 : 0); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_friendly.cpp b/src/cli/console/windows_friendly.cpp new file mode 100644 index 0000000..b414a1f --- /dev/null +++ b/src/cli/console/windows_friendly.cpp @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Friendly matches (menu 6, docs/CLI_CONCEPT/06-verein.md, H2 p. 50-51): choose an opponent and +// the venue, see the costs, pick a free date and book it. +// +// The engine functions are the ones the SDL app's controller uses (src/app/controller.cpp +// serve_friendly_action): quote_friendly_match (pure), friendly_match_date_status (pure) and +// book_friendly_match, which writes the plan. A human opponent must agree and the paying +// manager must accept the costs; the console asks those managers (hot seat) before booking. + +#include + +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/desk_actions.hpp" +#include "game/schedule.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +void Console::register_friendly_commands() { + auto manager = [this] { return active_slot(); }; + openers_[6] = [this] { + friendly_quote_.reset(); + open_window("Friendlies"); + emit('+', "friendlies: ListFriendlyOpponents, ProposeFriendly(club, Home|Away)"); + }; + add({"Friendlies", "ListFriendlyOpponents", {integer("league", 0, kLeagueCount - 1, true)}, "the clubs of a league (default: own)", false}, + [this](const Values& v) { + const ui::DeskState d = desk(); + const int league = v.has("league") ? int(v.integer("league")) : std::max(0, d.league); + const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), d.manager_slot, league); + std::vector> rows; + for (const auto& r : t.rows) + if (r.runtime_team_id != d.runtime_club) rows.push_back({"club:" + std::to_string(r.runtime_team_id), r.name}); + emit('i', t.league_name); + emit_table({"Club", "Name"}, rows); + }); + Param club = detail::text("club"); + club.display = "club:Club"; + add({"Friendlies", "ProposeFriendly", {club, choice("venue", {"Home", "Away"})}, "the offer: costs and who pays", false}, + [this, manager](const Values& v) { + // a club by club: or a unique part of a name (all leagues) + const std::string reference = v.text("club"); + int opponent = -1; + std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference; + Arg a; + a.text = number; + if (const auto id = to_int(a)) { + opponent = int(*id); + } else { + std::vector found; + for (int league = 0; league < kLeagueCount; ++league) + for (const auto& r : ui::league_table_from_game(session_->state(), manager(), league).rows) + if (fold(r.name).find(fold(reference)) != std::string::npos) found.push_back(r.runtime_team_id); + if (found.size() != 1) fail(found.empty() ? "E_BAD_ARGUMENT" : "E_AMBIGUOUS", "\"" + reference + "\" fits " + + std::to_string(found.size()) + " clubs; use club:"); + opponent = found.front(); + } + const FriendlyBookingQuote q = app::FriendlyActions(*session_).quote(manager(), opponent, v.choice("venue") == 0); + if (q.status != FriendlyQuoteStatus::quoted) fail("E_RULE", "no friendly possible against this club"); + friendly_quote_ = q; + const GameState& g = session_->state(); + emit('+', utf8(g.club_name(q.home_team)) + " - " + utf8(g.club_name(q.away_team)) + ", costs " + money(q.cost) + + (q.payer_manager >= 0 ? " (paid by player " + std::to_string(q.payer_manager + 1) + ")" : "") + + (q.opponent_manager >= 0 ? ", player " + std::to_string(q.opponent_manager + 1) + " must agree" : "") + + "; ListFreeDates, SetFriendlyDate(YYYY-MM-DD)"); + }); + auto free_dates = [this]() { + if (!friendly_quote_) fail("E_RULE", "no offer (ProposeFriendly first)"); + std::vector> dates; + const GameState& g = session_->state(); + for (int day = 0; day <= 365; ++day) { + const FriendlyDateStatus s = app::FriendlyActions(*session_).date_status(*friendly_quote_, uint16_t(day)); + if (s != FriendlyDateStatus::available && s != FriendlyDateStatus::available_with_calendar_event) continue; + const ui::DeskDate date = ui::desk_date(g.season_start + uint32_t(day), exe_); + dates.push_back({day, date_text(date.day, date.month, date.year)}); + } + return dates; + }; + add({"Friendlies", "ListFreeDates", {}, "the days the friendly can be played", false}, [this, free_dates](const Values&) { + std::vector> rows; + for (const auto& [day, date] : free_dates()) rows.push_back({date, std::to_string(day)}); + emit_table({"Date", "SeasonDay"}, rows); + }); + add({"Friendlies", "SetFriendlyDate", {detail::text("date")}, "book the friendly on a free date (YYYY-MM-DD)", true}, + [this, free_dates](const Values& v) { + int day = -1; + for (const auto& [d, date] : free_dates()) + if (date == v.text("date")) day = d; + if (day < 0) fail("E_RULE", v.text("date") + " is not free (ListFreeDates)"); + const FriendlyBookingQuote q = *friendly_quote_; + // the costs are accepted by the paying manager, a human opponent agrees; then book + auto book = [this, q, day](bool accept_cost, bool accept_opponent) { + const FriendlyBookingResult r = app::FriendlyActions(*session_).book_console( + q, uint16_t(day), accept_opponent, q.opponent_manager, accept_cost, q.payer_manager, revision_); + friendly_quote_.reset(); + switch (r.status) { + case FriendlyBookingStatus::booked: break; + case FriendlyBookingStatus::insufficient_funds: fail("E_INSUFFICIENT_FUNDS", "the money is not enough for this match"); + case FriendlyBookingStatus::declined: fail("E_RULE", "the costs were declined"); + case FriendlyBookingStatus::opponent_declined: fail("E_RULE", "the opponent did not agree"); + default: fail("E_RULE", "the date could not be booked"); + } + const ui::DeskDate date = ui::desk_date(session_->state().season_start + uint32_t(day), exe_); + emit('+', "friendly booked for " + date_text(date.day, date.month, date.year)); + }; + auto ask_opponent = [this, q, book](bool accept_cost) { + if (q.opponent_manager < 0) { + book(accept_cost, false); + return; + } + const int previous = player_; + player_ = q.opponent_manager + 1; + ask("Player " + std::to_string(q.manager + 1) + " proposes a friendly. Agree?", {"Yes", "No"}, "No", + [this, book, accept_cost, previous](const std::string& answer) { + player_ = previous; + book(accept_cost, answer == "Yes"); + }); + }; + if (q.cost > 0 && q.payer_manager >= 0) { + const int previous = player_; + player_ = q.payer_manager + 1; + ask("The friendly costs " + money(q.cost) + ". Pay?", {"Yes", "No"}, "No", [this, ask_opponent, previous](const std::string& answer) { + player_ = previous; + ask_opponent(answer == "Yes"); + }); + return; + } + ask_opponent(false); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_info.cpp b/src/cli/console/windows_info.cpp new file mode 100644 index 0000000..cd6b15b --- /dev/null +++ b/src/cli/console/windows_info.cpp @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// Information windows of docs/CLI_CONCEPT/05-information.md that the engine can already +// project: TeamInfo (club information, from LeagueTable / Fixtures), HighScore (menu 26) and +// TopScorers (menu 20). +// +// TeamInfo opens like the SDL app's club information (src/app/main.cpp +// present_club_information): CareerSession::enter_club_information prepares the entry +// (OpenTransferEditor's entry step, prepare_club_info_entry) for league teams, then the pure +// ui::club_info_from_game projection is read. +// +// Strengths, Achievements, OtherGames, TopScorers, FairPlay, Statistics and Calendar have no +// projection in the engine/UI yet; Open() answers E_ENGINE_GAP for them (windows_desk.cpp). + +#include +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/highscore.hpp" +#include "game/schedule.hpp" +#include "game/top_scorers.hpp" +#include "ui/club_info.hpp" +#include "ui/league_table.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU +constexpr int kHighscorePrefix = 889; // the high score file prefix ("high/h.") of TEXTD + +} // namespace + +void Console::register_info_commands() { + // --- TopScorers (05-information 7, menu 20) ------------------------------------------- + // Codex's read-only port of TopScorersFromGame (game/top_scorers.hpp): the best ten of the own + // league by goals, assists or both (one point each), for the whole league or only the + // managers' clubs. No state changes and no random draws, so the console reads it directly. + struct ScorerView { + game::TopScorersMetric metric = game::TopScorersMetric::goals; + game::TopScorersScope scope = game::TopScorersScope::league; + }; + auto scorers = std::make_shared(); + auto show_scorers = [this, scorers] { + const game::TopScorersProjection t = game::top_scorers_from_game(session_->state(), active_slot(), scorers->metric, scorers->scope); + static const char* const kMetric[3] = {"goals", "assists", "scorer points"}; + emit('i', std::string("top ") + kMetric[int(scorers->metric)] + + (scorers->scope == game::TopScorersScope::league ? ", whole league" : ", managers' clubs only")); + if (t.no_results) { + emit('i', "no results yet"); + return; + } + std::vector> rows; + for (const auto& r : t.rows) + rows.push_back({std::to_string(r.rank), "id:" + std::to_string(r.player), utf8(r.player_name), utf8(r.team_name), + std::to_string(r.goals), std::to_string(r.assists), std::to_string(r.score)}); + emit_table({"Rank", "Id", "Player", "Club", "Goals", "Assists", "Points"}, rows); + }; + openers_[20] = [this, scorers, show_scorers] { + *scorers = ScorerView{}; + open_window("TopScorers"); + show_scorers(); + }; + Param list = choice("list", {"Goals", "Assists", "Score"}, true), scope = choice("scope", {"League", "Managers"}, true); + add({"TopScorers", "ShowScorers", {list, scope}, "the best ten: goals, assists or both; whole league or managers' clubs", false}, + [scorers, show_scorers](const Values& v) { + if (v.has("list")) scorers->metric = game::TopScorersMetric(v.choice("list")); + if (v.has("scope")) scorers->scope = game::TopScorersScope(v.choice("scope")); + show_scorers(); + }); + Param list_needed = choice("list", {"Goals", "Assists", "Score"}), scope_needed = choice("scope", {"League", "Managers"}); + add({"TopScorers", "SetList", {list_needed}, "TORSCHÜTZEN / VORLAGEN / SCORER", false}, [scorers, show_scorers](const Values& v) { + scorers->metric = game::TopScorersMetric(v.choice("list")); + show_scorers(); + }); + add({"TopScorers", "SetScope", {scope_needed}, "GESAMTE LIGA / NUR MANAGER", false}, [scorers, show_scorers](const Values& v) { + scorers->scope = game::TopScorersScope(v.choice("scope")); + show_scorers(); + }); + + // --- TeamInfo (05-information 4) ------------------------------------------------------ + // A club of the nine leagues by name (unique part) or club:. + auto team_of = [this](const std::string& reference) { + std::vector> teams; + for (int league = 0; league < kLeagueCount; ++league) + for (const auto& row : ui::league_table_from_game(session_->state(), active_slot(), league).rows) + teams.push_back({row.runtime_team_id, row.name}); + std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference; + Arg a; + a.text = number; + if (const auto id = to_int(a)) { + for (const auto& t : teams) + if (t.first == *id) return t.first; + fail("E_BAD_ARGUMENT", "no club " + reference + " in the leagues"); + } + std::vector exact, partial; + for (const auto& t : teams) { + const std::string name = fold(t.second); + if (name == fold(reference)) exact.push_back(t.first); + else if (name.find(fold(reference)) != std::string::npos) partial.push_back(t.first); + } + const auto& found = exact.empty() ? partial : exact; + if (found.size() == 1) return found.front(); + if (found.empty()) fail("E_BAD_ARGUMENT", "no club named \"" + reference + "\" in the leagues"); + std::string candidates; + for (size_t i = 0; i < found.size() && i < 8; ++i) + candidates += (i ? ", " : "") + utf8(session_->state().club_name(found[i])) + " = club:" + std::to_string(found[i]); + fail("E_AMBIGUOUS", "\"" + reference + "\" fits several clubs: " + candidates); + }; + auto show_team = [this] { + if (!team_info_) fail("E_INTERNAL", "no club information"); + const auto& t = *team_info_; + emit('i', utf8(t.original_club_name) + (t.has_squad ? "" : " (no squad data)")); + std::vector> rows; + for (const auto& p : t.players) { + if (p.player_id < 0) continue; // free squad places + const auto& a = p.attributes; + rows.push_back({"id:" + std::to_string(p.player_id), utf8(p.original_name), text(kPositionNames + a.position()), + std::to_string(a.age()), std::to_string(a.condition()), std::to_string(a.technique()), + std::to_string(a.form()), std::to_string(a.strength()), p.borrowed ? "[loan]" : ""}); + } + emit_table({"Id", "Player", "Pos", "Age", "K", "T", "F", "Str", ""}, rows); + }; + auto open_team = [this, team_of, show_team](const std::string& reference) { + const int team = team_of(reference); + // The club-info entry rewrites the squad flags of the club (PrepareLineupEntry), which makes the + // engine's pairings draft stale: the fixtures page could neither act nor close any + // more. So the fixtures page closes first; GoBack from TEAM-INFO then returns to the + // window the fixtures were opened from. + if (window_ == "Fixtures" && pairings_) fixtures_action(LeaguePairingsAction::close); + std::string error; + ClubInfoEntry entry; + if (team < int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField))) { // league teams get the entry step (as the app does) + const auto prepared = session_->enter_club_information(team, error); + if (!prepared) fail("E_RULE", "club information: " + error); + entry = *prepared; + } + team_info_ = ui::club_info_from_game(session_->state(), team, entry, exe_, texts_); + // from TEAM-INFO itself the page is replaced: one club information at a time, so + // GoBack/CloseTeamInfo leads back to where the first one was opened + if (window_ != "TeamInfo") open_window("TeamInfo"); + show_team(); + }; + Param club = detail::text("club"); + club.display = "club:Club"; + for (const char* window : {"LeagueTable", "Fixtures", "TeamInfo"}) + add({window, "OpenTeamInfo", {club}, "TEAM-INFO of a club: club: or a name", false}, + [open_team](const Values& v) { open_team(v.text("club")); }); + add({"TeamInfo", "ShowTeamSquad", {choice("view", {"A", "B"}, true)}, "the club's squad", false}, [show_team](const Values&) { show_team(); }); + add({"TeamInfo", "ShowPlayer", {detail::text("player")}, "a player of this club", false}, [this](const Values& v) { + if (!team_info_) fail("E_INTERNAL", "no club information"); + // free squad places (player -1) are no players; `index` maps refs back to the rows + std::vector refs; + std::vector index; + for (size_t i = 0; i < team_info_->players.size(); ++i) { + const auto& p = team_info_->players[i]; + if (p.player_id < 0) continue; + refs.push_back({p.row, p.player_id, utf8(p.original_name)}); + index.push_back(i); + } + const auto& p = team_info_->players[index[resolve_player(v.text("player"), refs)]]; + const auto& a = p.attributes; + emit_table({"Player", "Value"}, + {{"name", utf8(p.original_name)}, + {"id", "id:" + std::to_string(p.player_id)}, + {"position", text(kPositionNames + a.position())}, + {"age", std::to_string(a.age())}, + {"condition/technique/form", std::to_string(a.condition()) + "/" + std::to_string(a.technique()) + "/" + std::to_string(a.form())}, + {"strength", std::to_string(a.strength())}}); + }); + add({"TeamInfo", "CloseTeamInfo", {}, "back to where it was opened", false}, [this](const Values&) { + team_info_.reset(); + close_window(); + emit('+', "club information closed"); + }); + for (const char* name : {"ShowTeamStatistics", "SetBroadcast"}) + add({"TeamInfo", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " is not in the console yet"); }); + + // --- HighScore (menu 26, H2 p. 94) ---------------------------------------------------- + auto show_highscore = [this] { + const GameState& g = session_->state(); + const uint16_t signature = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField7) ? g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) : 0; + if (signature != 0) { + // the ranked list of this game's level, stored next to the saved games + const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix)); + HighscoreTable rows{}; + std::error_code ec; + if (std::filesystem::exists(file, ec)) rows = load_highscore_table(file); + std::vector> table; + int rank = 0; + for (const auto& r : rows) + if (!r.manager_name.empty()) + table.push_back({std::to_string(++rank), utf8(r.manager_name), utf8(r.club_name), std::to_string(r.score)}); + if (table.empty()) emit('i', "the high score list is empty"); + else emit_table({"Rank", "Manager", "Club", "Score"}, table); + } else { + emit('i', "no ranked high score list in this game (level changed or signature 0)"); + } + const HighscoreScore s = highscore_score(g, active_slot()); + emit_table({"Score", "Points"}, {{"assets", std::to_string(s.assets)}, + {"patience", std::to_string(s.patience)}, + {"facilities", std::to_string(s.facilities)}, + {"team", std::to_string(s.team)}, + {"history", std::to_string(s.history)}, + {"titles", std::to_string(s.titles)}, + {"total", std::to_string(s.total)}}); + }; + openers_[26] = [this, show_highscore] { + open_window("HighScore"); + show_highscore(); + }; + add({"HighScore", "ShowHighScore", {}, "the high score list and your current score", false}, + [show_highscore](const Values&) { show_highscore(); }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_match.cpp b/src/cli/console/windows_match.cpp new file mode 100644 index 0000000..cf427f1 --- /dev/null +++ b/src/cli/console/windows_match.cpp @@ -0,0 +1,901 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// Stage 4 of docs/CLI_CONCEPT: the matchday window Match (07-spieltag 3) with a stepped clock. +// +// The engine plays a day inside one synchronous call (CareerSession::dispatch_kickoff -> +// TurnDriver::advance_to_next_desk) and calls TurnDriver::live_minute after every minute. +// The SDL app shows its live screen from inside that callback. The console cannot wait for +// input inside a call, so in time mode "stepped" the kickoff runs on an engine thread: the +// minute callback hands control to the console thread and blocks until the console lets the +// clock run again (Match.Step / Match.Run). Exactly one of the two threads runs at a time +// (a mutex/condition handshake), so the game stays deterministic: the same input gives the +// same game, whatever the timing. +// +// During a pause the console may change the human team as the original allows from the +// match (EndPhase -> line-up screen): Match.Substitute calls manual_substitution on the +// engine's state and MatchEngine::rerate_team, as tests/season_sim.cpp SIM_INTERVENE does. +// +// The events come from the engine's presentation log (MatchEngine::show, presentation.hpp): +// the console points it at its own vector at the first minute; appending draws no random +// numbers. Events of the first simulated minute are therefore not listed (the log is only +// reachable from the minute callback). + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/lineup.hpp" +#include "game/match_engine.hpp" +#include "game/presentation.hpp" +#include "game/schedule.hpp" +#include "game/season.hpp" +#include "game/messages.hpp" +#include "game/month.hpp" +#include "game/pending_offer.hpp" +#include "game/weekly.hpp" +#include "ui/incoming_transfer.hpp" +#include "ui/league_table.hpp" +#include "ui/live_matchday.hpp" +#include "ui/pending_offer.hpp" +#include "ui/tactics.hpp" +#include "app/window_actions.hpp" +#include "ui/preparation.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +struct Console::EngineRun { + std::thread worker; + std::mutex m; + std::condition_variable cv; + bool engine_turn = false; // true: the engine thread runs and the console waits + bool finished = false; + TurnAdvanceResult result; + std::string error; + ui::DeskState before; + + // the pause (valid while the engine waits in the minute callback) + int minute = 0; + MatchEngine* engine = nullptr; + std::vector* groups = nullptr; + GameState* state = nullptr; + bool intro_shown = false; + + // the clock: minutes to run before the next pause, or a minute to run to + int steps = 0; + int until = -1; + bool to_end = false; + + std::vector events; // the engine's presentation log + std::set> human_matches; // (group, match) with a human team + size_t printed = 0; + bool quiet = false; // time mode instant: no minute pauses, no "~" lines + + // a question of the engine during the kickoff (stage 5): the engine thread waits in a + // hook until the console has the answer (PendingOfferHooks, 07-spieltag 7.3) + enum class Pause { minute, question, loan_offer } pause = Pause::minute; + bool aborted = false; + bool loan_question = false; + // These capabilities refer to the month caller's staged transaction, never + // CareerSession's live state. They live only while its synchronous hook waits. + GameState* loan_state = nullptr; + GameRandom* loan_game = nullptr; + WatcomRandom* loan_random = nullptr; + app::ClubModalServices* loan_services = nullptr; + TransferOfferEditorState loan_owner; + HumanBuyerSaleHooks loan_hooks; + int loan_result = -1; + int question_player = 0; // 1-4 + std::string question_text, question_default, answer; + std::vector question_options; + std::vector notices; // the engine's notices, printed when the console runs + + // Engine thread: hands a question to the console and waits for its answer. + std::string ask(int player, std::string text, std::vector options, std::string fallback) { + std::unique_lock lock(m); + if (aborted) throw std::runtime_error("console matchday aborted"); + pause = Pause::question; + question_player = player; + question_text = std::move(text); + question_options = std::move(options); + question_default = std::move(fallback); + answer.clear(); + engine_turn = false; + cv.notify_all(); + cv.wait(lock, [this] { return engine_turn; }); + pause = Pause::minute; + if (aborted) throw std::runtime_error("console matchday aborted"); + return answer.empty() ? question_default : answer; + } +}; + +Console::~Console() { + if (run_) { + try { + stop_matchday(); + } catch (...) { + } + } +} + +namespace { + +// The human teams in this minute's groups. +bool human_playing(const std::vector& groups, const GameState& g) { + for (const auto& group : groups) + for (size_t side = 0; side < group.fixtures.size(); ++side) + if (!(group.void_mask() >> (side / 2) & 1) && + g.manager_of(group.fixtures[side]) >= 0) return true; + return false; +} + +const char* booking_name(int kind) { + switch (kind) { + case 0: return "yellow card"; + case 1: return "red card"; + case 2: return "injury"; + case 3: return "yellow-red card"; + default: return "booking"; + } +} + +} // namespace + +void Console::start_matchday(const ui::DeskRequest& request, const ui::DeskState& before) { + run_ = std::make_shared(); + run_->before = before; + EngineRun* run = run_.get(); + if (options_.time == TimeMode::instant) run->quiet = run->to_end = true; + session_->set_loan_return_presenter([run](GameState&, WatcomRandom&, int manager, const std::string& question) { + run->loan_question = true; + struct Reset { bool& flag; ~Reset() { flag = false; } } reset{run->loan_question}; + return run->ask(manager + 1, utf8(question), {"Yes", "No"}, "No") == "Yes" ? 1 : 0; + }); + session_->set_loan_return_offer_presenter([run](GameState& state, GameRandom& game, WatcomRandom& random, + app::ClubModalServices& services, int manager, int source_slot, int list_entry, + const HumanBuyerSaleHooks& hooks) -> int { + if (run->aborted || manager < 0 || size_t(manager) >= state.manager_teams.size() || + list_entry < 40 || list_entry >= 44 || source_slot != 2928 + list_entry || + !state.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57)) return -1; + const uint32_t row = ::bmh::layout::EditorList + uint32_t(list_entry) * 0x58; + TransferOfferEditorRequest input; + input.manager = manager; + input.runtime_club = state.manager_teams.at(size_t(manager)); + input.list_entry = list_entry; + input.source_slot = source_slot; + input.expected_player = state.squad_slots.at(size_t(source_slot)) & 0x0fff; + input.expected_seller_word = state.memory.u16(row + 8); + for (int bid = 0; bid < 4; ++bid) { + const uint16_t club = state.memory.u16(row + uint32_t(bid) * 2); + if (club == 0xffff || club == input.runtime_club) { input.expected_bid_slot = bid; break; } + } + input.loan_return_entry = true; + auto owner = open_transfer_offer_editor_source(state, input, game, random); + if (!owner.supported || owner.closed) return -1; + std::unique_lock lock(run->m); + run->loan_state = &state; + run->loan_game = &game; + run->loan_random = &random; + run->loan_services = &services; + run->loan_owner = std::move(owner); + run->loan_hooks = hooks; + run->loan_result = -1; + run->pause = EngineRun::Pause::loan_offer; + run->engine_turn = false; + run->cv.notify_all(); + run->cv.wait(lock, [run] { return run->engine_turn; }); + run->pause = EngineRun::Pause::minute; + run->loan_state = nullptr; + run->loan_game = nullptr; + run->loan_random = nullptr; + run->loan_services = nullptr; + run->loan_hooks = {}; + return run->aborted ? -1 : run->loan_result; + }); + // DayStepRest2 can enter InstallDefaultHooks while advancing the calendar. Bridge + // that synchronous Source callback through the same engine-question pause + // used by the kickoff's transfer questions. Offers are the actual four + // Source demands; no guessed renewal term or salary is applied. + session_->set_contract_expiry_presenter([run](GameState& state, WatcomRandom& random, int manager, int row) { + if (manager < 0 || size_t(manager) >= state.manager_teams.size()) + throw std::runtime_error("contract expiry: invalid manager owner"); + const SquadRange squad = squad_range(state.manager_teams[size_t(manager)]); + if (row < 0 || size_t(row) >= squad.count || squad.first + size_t(row) >= state.squad_slots.size()) + throw std::runtime_error("contract expiry: invalid squad row"); + const size_t board = size_t(manager) * 0x840 + size_t(row) * 0x58; + if (board + 0x54 > state.tactics.size()) + throw std::runtime_error("contract expiry: missing board row"); + const int player = int(state.squad_slots[squad.first + size_t(row)] & 0x0fff); + if (player == 0x0fff || size_t(player) >= state.players.size()) + throw std::runtime_error("contract expiry: missing player"); + const std::string player_name = utf8(state.player_name(player)); + const GameState before = state; + const WatcomRandom before_random = random; + + std::array demands{}; + try { + // InstallDefaultHooks passes the physical squad row as param5, so + // ContractBonuses enters with from_desk=false (the 0x80 desk bit is absent). + demands = contract_demands(state, manager, row, false, random); + } catch (const std::exception&) { + state = before; + random = before_random; + throw; + } + std::vector options; + std::vector columns; + for (int year = 0; year < 4; ++year) { + const uint32_t demand = demands[size_t(year)]; + if (demand == 0 || demand == std::numeric_limits::max()) continue; + columns.push_back(year); + options.push_back(std::to_string(year + 1) + " year" + (year == 0 ? "" : "s") + + " — " + std::to_string(demand) + " monthly"); + } + options.push_back("No offer (release player)"); + const std::string fallback = options.back(); + const std::string prompt = player_name + utf8(message_text(state, ::bmh::layout::Month_BoardMonth_TextPointer4)) + + " Choose an offer at the player's salary demand or release the player."; + const std::string answer = run->ask(manager + 1, prompt, options, fallback); + if (answer == fallback) return 0; + const auto selected = std::find(options.begin(), options.end() - 1, answer); + if (selected == options.end() - 1) + throw std::runtime_error("contract expiry: invalid question answer"); + const size_t index = size_t(selected - options.begin()); + const int column = columns[index]; + bool accepted = false; + try { + accepted = contract_offer(state, manager, row, column, demands[size_t(column)], demands[size_t(column)], + false, true, random); + } catch (const std::exception&) { + state = before; + random = before_random; + throw; + } + if (!accepted) { + // With an exact Source demand the acceptance threshold is necessarily + // met. Keep an unexpected rejection distinct from the Source close path: + // ContractBonuses returns to the still-open InstallDefaultHooks screen. + throw std::runtime_error("contract expiry: unexpected rejection of the exact salary demand"); + } + run->notices.push_back("Contract renewed: " + player_name); + return 1; + }); + // The engine's questions during the kickoff, as the SDL app asks them (src/app/main.cpp + // make_pending_offer_hooks): a club's salary demand or severance (yes/no) and the + // choice among the clubs' fee offers for an own player. normal_interactive is the + // session's mode for a frontend that presents them (legacy_unpresented answers them + // without asking). + PendingOfferHooks hooks; + hooks.answer = [run](const GameState&, const PendingOfferQuestion& q) { + // the severance a sold player's management asks for: refusing it ends the transfer + // (QA: sales of 2.7M and 3.4M were lost on a "No" that looked like a side question) + const std::string hint = + q.kind == PendingOfferQuestionKind::severance ? " [No = the transfer does not take place]" : ""; + const std::string answer = + run->ask(q.manager + 1, utf8(q.original_message) + hint, {"Yes", "No"}, "No"); + return answer == "Yes" ? PendingOfferAnswer::yes : PendingOfferAnswer::no; + }; + hooks.select_transfer = [run](const GameState& staged, const TransferOfferListView& offers) { + const ui::IncomingTransferDecisionState panel = ui::pending_offer_transfer_decision_from_game(staged, offers); + std::string text = "Offers for " + utf8(panel.player_name) + ":"; + std::vector options; + std::vector slots; + for (size_t i = 0; i < panel.offers.size(); ++i) { + const auto& o = panel.offers[i]; + if (!o.present) continue; + options.push_back("Accept" + std::to_string(options.size() + 1)); + slots.push_back(int(i)); + text += " " + options.back() + " = " + (o.loan ? "loan to " : "sell to ") + utf8(panel.buyer_names[i]) + " for " + std::to_string(o.fee) + " (" + + std::to_string(o.monthly_salary) + " monthly" + (o.loan ? ", loan" : "") + ");"; + } + options.push_back("Decline"); + // IncomingTransferScreen: the right mouse button declines (IncomingTransferScreen::click) + const std::string answer = run->ask(panel.viewer_manager + 1, text, options, "Decline"); + for (size_t i = 0; i < slots.size(); ++i) + if (options[i] == answer) return PendingOfferTransferChoice{PendingOfferTransferChoiceKind::bid, slots[i]}; + return PendingOfferTransferChoice{PendingOfferTransferChoiceKind::decline, -1}; + }; + hooks.notice = [run](const GameState&, const PendingOfferNotice& n) { run->notices.push_back(utf8(n.original_message)); }; + session_->set_pending_offer_hooks(std::move(hooks)); + // IncomingTransferScreen at the weekly list deadline: the bids for a player a manager put on the + // transfer list. Without this chooser the engine declines every bid for a human seller + // (GameState::transfer_offer_selector), so listed players could never be sold. + session_->set_transfer_offer_selector([run](const GameState& g, const TransferOfferListView& view) -> int { + const std::string notice = view.notice_text_address ? utf8(message_text(g, view.notice_text_address)) : std::string(); + if (view.offer_count <= 0) { // the final refusal notice; the response is ignored + if (!notice.empty()) run->notices.push_back(notice); + return -1; + } + std::string text = (notice.empty() ? std::string() : notice + " ") + "Offers for " + utf8(g.player_name(view.player)) + ":"; + std::vector options; + std::vector slots; + for (const auto& o : view.offers) { + if (!o.present) continue; + options.push_back("Accept" + std::to_string(options.size() + 1)); + slots.push_back(o.bid_index); + text += " " + options.back() + " = " + (o.loan ? "loan to " : "sell to ") + utf8(g.club_name(o.buyer)) + " for " + std::to_string(o.fee) + " (" + + std::to_string(o.monthly_salary) + " monthly" + (o.loan ? ", loan" : "") + ");"; + } + options.push_back("Decline"); + const std::string answer = run->ask(view.seller_manager + 1, text, options, "Decline"); + for (size_t i = 0; i < slots.size(); ++i) + if (options[i] == answer) return slots[i]; + return -1; + }); + // IncomingTransferScreen also presents the automatic result when a human bid loses + // to another club. The engine already supplies this read-only snapshot; + // relay it at the next thread handoff instead of silently dropping it. + session_->set_transfer_decision_observer([this, run](const TransferDecisionEvent& event) { + const auto& g = session_->state(); + const std::string player = utf8(g.player_name(event.offers.player)); + if (event.kind == TransferDecisionEventKind::last_week) { + run->notices.push_back(player + utf8(message_text(g, event.result_text_address))); + return; + } + if (event.kind == TransferDecisionEventKind::confirmation) { + run->notices.push_back(player + ": " + utf8(message_text(g, event.result_text_address))); + return; + } + // The Original marks each row NEIN up to the accepted row (OK), or + // every row NEIN when no bid is accepted. It stops at the OK row. + for (const auto& offer : event.offers.offers) { + if (!offer.present) continue; + const bool accepted = event.accepted && offer.bid_index == event.selected_bid_index; + run->notices.push_back(player + ": " + utf8(g.club_name(offer.buyer)) + ": " + + utf8(message_text(g, accepted ? ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer3 : ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer4))); + if (accepted) break; + } + // The rows stop at the accepted bid, so a human bid behind it never shows up; a manager + // then waits for a player who has gone (learning session, finding G-006). The console + // says it for every human bidder that lost (OpenBMH deviates from the original screen + // here: an extra line, nothing in the engine changes). + for (const auto& offer : event.offers.offers) { + if (!offer.present || (event.accepted && offer.bid_index == event.selected_bid_index)) continue; + if (g.manager_of(offer.buyer) < 0) continue; + std::string line = player + ": the bid of " + utf8(g.club_name(offer.buyer)) + " was not accepted"; + for (const auto& winner : event.offers.offers) + if (event.accepted && winner.present && winner.bid_index == event.selected_bid_index) + line += " - he signs for " + utf8(g.club_name(winner.buyer)); + run->notices.push_back(line); + } + }); + session_->set_pending_offer_entry_policy(app::PendingOfferEntryPolicy::normal_interactive); + // The season change inside the kickoff (season_transition): the tax notice and the + // question whether to "adjust" the tax return (GameEndTaxAnimationScreen, Season_SeasonApplyProfitTax_TextPointer3; caught or not + // follows), the promoted/relegated clubs and the cup draws, as the SDL app shows them. + SeasonTaxHooks tax; + tax.observe = [run](const GameState&, const SeasonTaxEvent& e) { + if (!e.text.empty()) run->notices.push_back(utf8(e.text)); + }; + tax.choose = [run](const GameState&, const SeasonTaxEvent& e) { + return run->ask(e.manager_slot + 1, utf8(e.text), {"Yes", "No"}, "No") == "Yes"; + }; + session_->set_season_tax(std::move(tax)); + session_->set_season_promotion([run](const GameState& g, const SeasonPromotionEvent& e) { + // The first promotion screen comes before any club changes its league: the tables + // are final here. The managers' leagues are listed once each (the table window + // shows the new season afterwards). + if (e.group == 0) { + std::set shown; + for (size_t m = 0; m < g.manager_teams.size(); ++m) { + const int league = team_league(g.manager_teams[m]); + if (league < 0 || league >= kLeagueCount || !shown.insert(league).second) continue; + const ui::LeagueTableState t = ui::league_table_from_game(g, int(m), league); + std::string line = "final table " + t.league_name + ":"; + for (const auto& r : t.rows) + line += " " + std::to_string(r.rank) + ". " + r.name + " " + std::to_string(r.points) + ";"; + run->notices.push_back(line); + } + } + static const char* const kGroups[4] = {"1st division", "2nd division", "3rd divisions", "4th division"}; + std::string up, down; + for (size_t i = 0; i < e.count && i < e.promoted.size(); ++i) up += (up.empty() ? "" : ", ") + utf8(g.club_name(e.promoted[i])); + for (size_t i = 0; i < e.count && i < e.relegated.size(); ++i) down += (down.empty() ? "" : ", ") + utf8(g.club_name(e.relegated[i])); + run->notices.push_back(std::string(kGroups[std::clamp(e.group, 0, 3)]) + ": relegated " + down + "; promoted " + up); + }); + session_->set_season_cup_draw([run](const GameState& g, const SeasonCupDrawEvent& e) { + if (e.phase != SeasonCupDrawPhase::draw) return; + std::string pairs; + for (size_t i = 0; i + 1 < e.participants.size() && i + 1 < e.count; i += 2) + pairs += (pairs.empty() ? "" : "; ") + utf8(g.club_name(e.participants[i])) + " - " + utf8(g.club_name(e.participants[i + 1])); + run->notices.push_back("cup draw (competition " + std::to_string(e.competition) + ", round " + std::to_string(e.round + 1) + "): " + pairs); + }); + session_->set_live_minute([run](int minute, MatchEngine& engine, std::vector& groups, GameState& g) { + if (run->aborted) throw std::runtime_error("console matchday aborted"); + if (!engine.show) engine.show = &run->events; + // remember which matches have a human team: only their events are printed (07-spieltag 3.1) + for (size_t gi = 0; gi < groups.size(); ++gi) + for (size_t mi = 0; mi * 2 + 1 < groups[gi].fixtures.size(); ++mi) + for (int side = 0; side < 2; ++side) + if (std::find(g.manager_teams.begin(), g.manager_teams.end(), groups[gi].fixtures[mi * 2 + size_t(side)]) != + g.manager_teams.end()) + run->human_matches.insert({int(gi), int(mi)}); + if (run->to_end || !human_playing(groups, g)) return; + if (run->until >= 0) { + if (minute < run->until) return; + run->until = -1; + } else if (run->steps > 0 && --run->steps > 0) { + return; + } + // pause: hand the clock to the console until it lets the engine run again + std::unique_lock lock(run->m); + run->minute = minute; + run->engine = &engine; + run->groups = &groups; + run->state = &g; + run->engine_turn = false; + run->cv.notify_all(); + run->cv.wait(lock, [run] { return run->engine_turn; }); + run->engine = nullptr; + run->groups = nullptr; + run->state = nullptr; + if (run->aborted) throw std::runtime_error("console matchday aborted"); + }); + run->engine_turn = true; + run->worker = std::thread([this, run, request] { + TurnAdvanceResult result; + std::string error; + try { + result = session_->dispatch_kickoff(request, revision_, error); + } catch (const std::exception& e) { + result.kind = TurnDeskKind::Failed; + error = std::string("engine exception: ") + e.what(); + } + std::unique_lock lock(run->m); + run->result = result; + run->error = error; + run->finished = true; + run->engine_turn = false; + run->cv.notify_all(); + }); + { + std::unique_lock lock(run->m); + run->cv.wait(lock, [run] { return !run->engine_turn; }); + } + engine_returned(); +} + +// Lets the engine run until the next pause or the end of the day. +void Console::resume_matchday() { + EngineRun* run = run_.get(); + if (!run) fail("E_RULE", "no matchday is running"); + if (!run->finished) { + std::unique_lock lock(run->m); + run->engine_turn = true; + run->cv.notify_all(); + run->cv.wait(lock, [run] { return !run->engine_turn; }); + } + engine_returned(); +} + +// The engine thread waits (a minute pause or a question) or has finished the kickoff: +// show the pause, ask the question, or finish (results, next desk). +void Console::engine_returned() { + EngineRun* run = run_.get(); + for (const auto& n : run->notices) emit('i', n); + run->notices.clear(); + if (!run->finished && run->pause == EngineRun::Pause::question) { + // the question belongs to the manager concerned (his desk); the answer resumes the engine + set_window("Desktop", run->question_player); + ask(run->question_text, run->question_options, run->question_default, [this](const std::string& answer) { + run_->answer = answer; + resume_matchday(); + }); + return; + } + if (loan_return_offer_active()) { + const auto& state = *run->loan_state; + offer_editor_ = app::loan_return_offer_editor_projection(state, run->loan_owner, revision_, + !state.memory.has(::bmh::layout::TextGradientDisabled) || state.memory.u8(::bmh::layout::TextGradientDisabled) == 0); + offer_submitted_ = false; + set_window("Transfer.Negotiate", run->loan_owner.request.manager + 1); + emit('i', "Loan returned: negotiate a purchase with ShowNegotiation, SetOfferField, SubmitOffer; GoBack cancels the offer"); + return; + } + if (!run->finished) { + show_match_pause(); + return; + } + run->worker.join(); + session_->set_live_minute({}); + session_->set_pending_offer_hooks({}); + session_->set_transfer_offer_selector({}); + session_->set_transfer_decision_observer({}); + session_->set_season_tax({}); + session_->set_season_promotion({}); + session_->set_season_cup_draw({}); + session_->set_pending_offer_entry_policy(app::PendingOfferEntryPolicy::legacy_unpresented); + session_->set_contract_expiry_presenter({}); + session_->set_loan_return_presenter({}); + session_->set_loan_return_offer_presenter({}); + // the events after the last pause + if (!run->aborted && !run->quiet && run->printed < run->events.size()) show_match_pause(); + const ui::DeskState before = run->before; + const TurnAdvanceResult result = run->result; + const std::string error = run->error; + const bool aborted = run->aborted; + run_.reset(); + if (aborted) { + set_window("Desktop", int(session_->state().memory.u8(::bmh::layout::ActiveManager)) + 1); + return; + } + finish_kickoff(before, result, error); +} + +void Console::stop_matchday() { + if (!run_) return; + run_->to_end = true; + // Termination must not silently choose a default answer or commit a staged + // return/purchase. Wake the Source owner with an abort; CareerSession owns rollback. + run_->aborted = true; + question_.reset(); + offer_editor_.reset(); + resume_matchday(); +} + +bool Console::loan_return_offer_active() const { + return run_ && !run_->finished && run_->pause == EngineRun::Pause::loan_offer; +} + +bool Console::loan_return_modal_active() const { + return run_ && (run_->loan_question || loan_return_offer_active()); +} + +std::optional Console::dispatch_loan_return_offer( + const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& presenters, std::string& error, + const app::TransferOfferTeamInfoPresenter& team_info, + const app::TransferOfferPlayerInfoPresenter& player_info) { + error.clear(); + if (!loan_return_offer_active()) { error = "no loan-return editor"; return std::nullopt; } + auto& run = *run_; + // Match the complete identity/quote to the Source owner. The UI fields may + // already contain the proposed value, so validate against a fresh projection. + const auto projected = app::loan_return_offer_editor_projection(*run.loan_state, run.loan_owner, revision_, false); + const auto expected = app::TransferActions::editor(projected, request.kind, request.field, request.value); + if (request.identity.manager_slot != expected.identity.manager_slot || + request.identity.runtime_club != expected.identity.runtime_club || + request.identity.list_entry != expected.identity.list_entry || + request.identity.source_slot != expected.identity.source_slot || + request.identity.player != expected.identity.player || request.identity.seller != expected.identity.seller || + request.identity.bid_slot != expected.identity.bid_slot || request.identity.revision != revision_ || + request.quoted_fee != expected.quoted_fee || request.quoted_monthly_salary != expected.quoted_monthly_salary || + request.quoted_years != expected.quoted_years) { + error = "loan return: mismatched editor identity or quote"; return std::nullopt; + } + auto next = *run.loan_state; + auto game = *run.loan_game; + auto random = *run.loan_random; + auto owner = run.loan_owner; + TransferActionResult action; + int completed = -1; + const bool information = request.kind == ui::OutgoingTransferRequestKind::team_info || + request.kind == ui::OutgoingTransferRequestKind::player_info; + try { + if (request.kind == ui::OutgoingTransferRequestKind::quote_change) { + owner = app::edit_transfer_offer_from_ui(next, owner, request, game, random); + } else if (request.kind == ui::OutgoingTransferRequestKind::cancel) { + owner = cancel_transfer_offer_editor_source(next, owner); + completed = 0; + } else if (request.kind == ui::OutgoingTransferRequestKind::team_info || + request.kind == ui::OutgoingTransferRequestKind::player_info) { + // These services already belong to the staged month transaction. + const auto valid = cancel_transfer_offer_editor_source(next, owner); + if (!valid.supported) { error = valid.reason; return std::nullopt; } + auto& services = *run.loan_services; + if (request.kind == ui::OutgoingTransferRequestKind::team_info) { + if (!team_info || !team_info(services, int(owner.request.expected_seller_word & 0x7fff), Image{})) + throw std::runtime_error("loan return: TeamInfo presenter stopped"); + next = *run.loan_state; game = *run.loan_game; random = *run.loan_random; + owner = resume_transfer_offer_team_info_source(next, owner, random); + } else { + const auto selection = transfer_offer_player_info_selection_source(next, owner); + services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField, 1); + if (!player_info || !player_info(services, selection, Image{})) + throw std::runtime_error("loan return: PlayerInfo presenter stopped"); + next = *run.loan_state; game = *run.loan_game; random = *run.loan_random; + owner = resume_transfer_offer_player_info_source(next, owner, + services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField), services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), random); + } + } else if (request.kind == ui::OutgoingTransferRequestKind::submit) { + auto hooks = run.loan_hooks; + hooks.confirm = presenters.confirm; + hooks.notice = presenters.notice; + MinuteReport report; + auto result = submit_transfer_offer_editor_source(next, owner, random, hooks, report); + owner = std::move(result.editor); action = result.action; + if (report.unsupported || action.status == TransferActionStatus::unsupported) { + error = report.reason; return std::nullopt; + } + // DayStepRest2's SDL owner returns after these statuses even when the + // generic market editor would remain open. The month caller clears its row. + if (owner.closed || action.status == TransferActionStatus::pending || + action.status == TransferActionStatus::rejected || action.status == TransferActionStatus::insufficient_funds) + completed = 1; + } else { error = "loan return: unsupported editor event"; return std::nullopt; } + if (!owner.supported) { + error = owner.reason; + if (information) stop_matchday(); + return std::nullopt; + } + app::CareerSession::TransferOfferEditorDispatch result; + result.editor = app::loan_return_offer_editor_projection(next, owner, revision_, false); + result.editor.closed = owner.closed || completed >= 0; + result.action = action; + *run.loan_state = std::move(next); + *run.loan_game = game; + *run.loan_random = random; + run.loan_owner = std::move(owner); + run.loan_result = completed; + return result; + } catch (const std::exception& e) { + error = e.what(); + // ClubModalServices also owns opaque transient bytes. Once an info + // presenter has entered, a failed event must discard the whole month + // transaction, not leave its partial effects for a later Cancel/Submit. + if (information) { + stop_matchday(); + throw; // A presenter exception is an internal failure, not a rule refusal. + } + return std::nullopt; + } +} + +void Console::finish_loan_return_offer() { + if (loan_return_offer_active() && run_->loan_result >= 0) resume_matchday(); +} + +// The new events since the last pause as "~" lines, then the human matches' scores. +void Console::show_match_pause() { + EngineRun* run = run_.get(); + set_window("Match", 0); + if (!run->intro_shown && run->groups && run->state) { + // Info.MatchdayIntro (07-spieltag 2): the day's human matches + run->intro_shown = true; + emit('i', "Matchday: the clock stops after every minute; Step(n) or Run(Halftime|End)"); + } + for (; run->printed < run->events.size(); ++run->printed) { + const ShowEvent& e = run->events[run->printed]; + if (!run->human_matches.count({int(e.group), int(e.match)})) continue; + std::string what; + switch (e.what) { + case Show::Booking: what = std::string(booking_name(e.kind)) + ": "; break; + case Show::Substitution: what = "substitution: "; break; + case Show::Chance: what = e.flag ? "GOAL: " : "chance: "; break; + case Show::PenaltyKick: what = std::string("penalty ") + (e.flag ? "scored: " : "missed: "); break; + case Show::ShootoutEnd: what = "shoot-out: "; break; + default: continue; // set pieces and shots are picture data only + } + std::string text = utf8(e.text); + if (e.what == Show::Substitution && run->state && e.player >= 0 && e.player < 0xfff && e.other >= 0 && e.other < 0xfff) + text = utf8(run->state->player_name(e.other)) + " for " + utf8(run->state->player_name(e.player)); + if (text.empty() && run->state && e.player >= 0 && e.player < 0xfff) text = utf8(run->state->player_name(e.player)); + Json::Object data{{"kind", int(e.what)}, {"group", int(e.group)}, {"match", int(e.match)}, {"side", int(e.side)}, + {"team", int(e.team)}, {"player", int(e.player)}, {"other", int(e.other)}}; + emit('~', std::to_string(e.minute) + "' [match " + std::to_string(e.group) + "." + std::to_string(e.match) + "] " + what + text, + Json(std::move(data))); + } + if (!run->groups || !run->state) return; + const ui::LiveMatchdayFrame frame = ui::live_matchday_frame(run->minute, *run->groups, *run->state); + const auto& teams = run->state->manager_teams; + for (const auto& m : frame.matches) { + const bool human = std::find(teams.begin(), teams.end(), m.home_team) != teams.end() || + std::find(teams.begin(), teams.end(), m.away_team) != teams.end(); + if (!human) continue; + emit('i', std::to_string(run->minute) + "' " + utf8(m.home) + " " + std::to_string(m.home_goals) + ":" + + std::to_string(m.away_goals) + " " + utf8(m.away)); + } +} + +void Console::register_match_commands() { + auto paused = [this]() -> EngineRun& { + if (!run_ || run_->finished || !run_->state) fail("E_RULE", "no match is running"); + return *run_; + }; + add({"Match", "Step", {integer("minutes", 1, 130, true)}, "let the clock run n minutes (default 1)", true}, [this, paused](const Values& v) { + paused().steps = int(v.integer("minutes", 1)); + resume_matchday(); + }); + add({"Match", "Run", {choice("until", {"Halftime", "End"}, true)}, "run to half time or to the end of the day", true}, + [this, paused](const Values& v) { + EngineRun& run = paused(); + if (v.has("until") && v.choice("until") == 0) { + // the indoor tournament plays 2 x 20 minutes (driver.cpp): its half time is at + // 20; waiting for 45 there ran the whole day through (learning session F-run2-004) + const int half = run.state && run.state->indoor ? 20 : 45; + if (run.minute >= half) fail("E_RULE", "half time is over"); + run.until = half; + } else { + run.to_end = true; + } + resume_matchday(); + }); + add({"Match", "ShowMatchStats", {integer("match", 0, 99, true)}, "the scoreboard: score, chances, cards, spectators, weather", false}, + [this, paused](const Values&) { + EngineRun& run = paused(); + const ui::LiveMatchdayFrame frame = ui::live_matchday_frame(run.minute, *run.groups, *run.state); + std::vector> rows; + for (const auto& m : frame.matches) + rows.push_back({utf8(m.home), utf8(m.away), std::to_string(m.home_goals) + ":" + std::to_string(m.away_goals), + std::to_string(m.home_stats[1]) + "/" + std::to_string(m.away_stats[1]), + m.spectators_known ? std::to_string(m.spectators) : "-", utf8(m.temperature_text)}); + emit_table({"Home", "Away", "Score", "Chances", "Spectators", "Weather"}, rows); + }); + // the human team a command acts for: @n, or the only human team playing + auto team_of = [this, paused](const Values& v) { + EngineRun& run = paused(); + const auto& teams = run.state->manager_teams; + if (v.player) { + if (size_t(v.player) > teams.size()) fail("E_BAD_ARGUMENT", "there is no player " + std::to_string(v.player)); + return teams[size_t(v.player - 1)]; + } + if (teams.size() > 1) fail("E_BAD_ARGUMENT", "with several managers write @n before the command"); + return teams.front(); + }; + // the squad rows of a team in the running match: 0-10 on the pitch, bench rows have 0x4000 + auto squad_refs = [this, paused](int team) { + EngineRun& run = paused(); + const SquadRange range = squad_range(team); + std::vector refs; + for (size_t row = 0; row < range.count; ++row) { + const uint16_t slot = run.state->squad_slots.at(range.first + row); + if ((slot & 0x0fff) == 0x0fff || !(slot & 0xc000)) continue; + refs.push_back({int(row), slot & 0x0fff, utf8(run.state->player_name(slot & 0x0fff))}); + } + return refs; + }; + add({"Match", "ShowSquad", {}, "your team on the pitch and on the bench", false}, [this, paused, team_of, squad_refs](const Values& v) { + EngineRun& run = paused(); + const int team = team_of(v); + const SquadRange range = squad_range(team); + std::vector> rows; + for (const auto& r : squad_refs(team)) { + const uint16_t slot = run.state->squad_slots.at(range.first + size_t(r.row)); + rows.push_back({"row:" + std::to_string(r.row), r.name, (slot & 0x8000) ? "pitch" : "bench"}); + } + emit_table({"Row", "Player", "Place"}, rows); + }); + Param out = detail::text("out"), in = detail::text("in"); + out.display = "out:Player"; + in.display = "in:Player"; + add({"Match", "Substitute", {out, in}, "a substitution: a player leaves, a bench player comes on", true}, + [this, paused, team_of, squad_refs](const Values& v) { + EngineRun& run = paused(); + const int team = team_of(v); + const auto refs = squad_refs(team); + const PlayerRef leaving = refs[resolve_player(v.text("out"), refs)]; + const PlayerRef coming = refs[resolve_player(v.text("in"), refs)]; + const SquadRange range = squad_range(team); + if (!(run.state->squad_slots.at(range.first + size_t(leaving.row)) & 0x8000)) + fail("E_RULE", leaving.name + " is not on the pitch"); + if (!(run.state->squad_slots.at(range.first + size_t(coming.row)) & 0x4000)) + fail("E_RULE", coming.name + " is not on the bench"); + // manual_substitution refuses after kMaxSubstitutions or for a player who already played + if (!manual_substitution(*run.state, team, leaving.row, coming.row)) + fail("E_RULE", "no substitution possible (" + std::to_string(kMaxSubstitutions) + " used, or the player already played)"); + MinuteReport report; + run.engine->rerate_team(team, report); + if (report.unsupported) fail("E_INTERNAL", "re-rating after the substitution: " + report.reason); + emit('+', std::to_string(run.minute) + "' substitution: " + coming.name + " for " + leaving.name); + }); + // --- the tactics board during the match (the original's live tactics, mode 8) --------- + // The tactics of the manager's team as the match sees them (ActiveManager set to him, as + // the SDL live tactics screen does). + auto live_tactics = [this, paused](int manager) { + EngineRun& run = paused(); + GameState view = *run.state; + if (view.memory.has(::bmh::layout::ActiveManager)) view.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + return ui::tactics_from_game(view, exe_, revision_); + }; + add({"Match", "ShowTactics", {}, "the eight tactic settings of your team in this match", false}, + [this, paused, team_of, live_tactics](const Values& v) { + EngineRun& run = paused(); + const int team = team_of(v); + const ui::TacticsState t = live_tactics(run.state->manager_of(team)); + std::vector> rows; + for (size_t i = 0; i < 8; ++i) rows.push_back({std::to_string(i), detail::kTacticNames[i], std::to_string(t.values[i])}); + emit_table({"Item", "Setting", "Value"}, rows); + if (t.assistant_attitude) emit('i', "the assistant adapts the attitude (item 0) to the score"); + }); + // One change of a tactic setting in the running match: the session opens the live + // intervention (begin_live_intervention, mode 8), applies the request like the tactics + // window (dispatch_live_tactic re-rates the side) and closes it; a refused change aborts + // the intervention, so the match goes on as before. From minute 3 on, as in the SDL app. + add({"Match", "SetTactic", {integer("item", 0, 7), integer("value", 0, 11)}, + "change a tactic setting during the match (item 0 ends the assistant's D/O control)", true}, + [this, paused, team_of, live_tactics](const Values& v) { + EngineRun& run = paused(); + const int team = team_of(v); + const int manager = run.state->manager_of(team); + if (manager < 0) fail("E_RULE", "not a human team"); + if (run.minute <= 2) fail("E_RULE", "tactics can be changed from minute 3 on"); + const int item = int(v.integer("item")), value = int(v.integer("value")); + std::string error; + if (!session_->begin_live_intervention(run.minute, 8, manager, team, *run.engine, revision_, error)) + require_engine(false, "live tactics", error); + const ui::TacticsState t = live_tactics(manager); + ui::TacticsRequest req; + req.kind = ui::TacticsRequestKind::set_tactic; + req.manager_slot = t.manager_slot; + req.runtime_club = t.runtime_club; + req.revision = revision_; + req.index = item; + req.desired_value = value; + if (item == 0) req.desired_assistant_attitude = 0; + if (!session_->dispatch_live_tactic(req, run.minute, 8, *run.engine, revision_, error)) { + session_->abort_live_intervention(run.minute, 8, manager, team, *run.engine, revision_); + require_engine(false, "live tactics", error); + } + if (!session_->finish_live_intervention(run.minute, 8, manager, team, *run.engine, revision_, error)) { + session_->abort_live_intervention(run.minute, 8, manager, team, *run.engine, revision_); + require_engine(false, "live tactics", error); + } + emit('+', std::to_string(run.minute) + "' tactics: item " + std::to_string(item) + " = " + std::to_string(value)); + }); + // Re-arranging the side in the running match (the live line-up, mode 2). The original's + // PitchScreen offers no formation templates during a match (its param_2 is nonzero: + // formations and automatic weights belong to the preparation only); a starter can be + // placed on another depth/lane, as Lineup.Pitch MovePlayer does before the match. + Param mover = detail::text("player"); + mover.display = "player:Player"; + add({"Match", "MovePlayer", {mover, integer("depth", 0, 19), integer("lane", 0, 8)}, + "place a starter on another position for the rest of the match (from minute 3)", true}, + [this, paused, team_of](const Values& v) { + EngineRun& run = paused(); + const int team = team_of(v); + const int manager = run.state->manager_of(team); + if (manager < 0) fail("E_RULE", "not a human team"); + if (run.minute <= 2) fail("E_RULE", "positions can be changed from minute 3 on"); + std::string error; + if (!session_->begin_live_intervention(run.minute, 2, manager, team, *run.engine, revision_, error)) + require_engine(false, "live position", error); + auto abort = [&](const std::string& why) { + session_->abort_live_intervention(run.minute, 2, manager, team, *run.engine, revision_); + require_engine(false, "live position", why); + }; + // the projection of the paused match for the manager (as the SDL live line-up) + GameState view = *run.state; + if (view.memory.has(::bmh::layout::ActiveManager)) view.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + ui::PreparationState p = ui::preparation_from_game(view, exe_, revision_); + p.lineup.in_match = true; + p.lineup.entry_prepared = true; + if (!p.pitch || !p.pitch->indoor.has_value()) abort("no pitch projection in this match"); + std::vector refs; + for (const auto& pl : p.lineup.players) + if (pl.player_id >= 0) refs.push_back({pl.row, pl.player_id, utf8(pl.name)}); + const int index = resolve_player(v.text("player"), refs); + const ui::LineupPlayer& player = p.lineup.players.at(size_t(refs[size_t(index)].row)); + if (player.row >= 11 || !(player.slot & 0x8000)) abort(utf8(player.name) + " is not on the pitch"); + const ui::PitchRequest r = app::LineupActions::move(p, player, int(v.integer("depth")), int(v.integer("lane"))); + const app::LiveSubstitutionResult result = session_->dispatch_live_pitch_result(r, run.minute, 2, *run.engine, revision_); + if (result.status == app::LiveSubstitutionStatus::rejected) abort(result.error.empty() ? "refused" : result.error); + if (!session_->finish_live_intervention(run.minute, 2, manager, team, *run.engine, revision_, error)) abort(error); + emit('+', std::to_string(run.minute) + "' " + utf8(player.name) + " to depth " + std::to_string(v.integer("depth")) + + ", lane " + std::to_string(v.integer("lane"))); + }); + add({"Match", "SetFormation", {integer("slot", 1, 8)}, "not during a match (move single players with MovePlayer)", true}, + [](const Values&) { + fail("E_RULE", "the original offers no formation templates during a match; MovePlayer places single players"); + }); + for (const char* name : {"SetMarking", "SetOrder", "Open", "Watch", "Pause", "Resume"}) + add({"Match", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " during the match is not in the console yet"); }); + // GoBack in the match: the original opens the tactics of the own team (02-fenster 3); + // until Match.Tactics exists the clock simply keeps waiting + closers_["Match"] = [this] { emit('+', "the match waits: Step(n) or Run(Halftime|End)"); }; +} + +std::string Console::match_status() const { + if (!run_) return {}; + if (loan_return_offer_active()) return "matchday paused for loan-return negotiation"; + return "matchday running, minute " + std::to_string(run_->minute); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_money.cpp b/src/cli/console/windows_money.cpp new file mode 100644 index 0000000..abcf27d --- /dev/null +++ b/src/cli/console/windows_money.cpp @@ -0,0 +1,544 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The money windows of docs/CLI_CONCEPT/06-verein.md: Bank (menu 14) with savings, shares and +// real estate, Stadium (menu 22) with the periphery and the stand blocks, and Toto (menu 13). +// Views from CareerSession::preparation_projection; changes through dispatch_bank / +// dispatch_stadium / dispatch_toto with the requests the SDL screens build. +// +// Opening the stadium draws random numbers (CareerSession::dispatch_stadium "open": +// construction_price_percent restarts the game generator), so the console opens it through +// the engine exactly when the window opens, never as a side effect of a read command. + +#include +#include + +#include "app/window_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/bank_credit.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// TEXTD indices (docs/formats/textd_inventory.csv) +constexpr int kFinanceLabels = 339; // Bank_OriginalToUtf8_RuntimeField6: the seven lines of the finance overview +constexpr int kCreditLabels = 352; // Bank_OriginalToUtf8_TextPointer4: the credit view's eight lines +constexpr int kShareNames = 322; // Bank_FormatError_ExecutableField2: the twelve listed companies (sponsorNameC01..) +constexpr int kShareTips = 334; // Bank_FormatError_RuntimeField19: schnell verk. / verkaufen / halten / kaufen ... +constexpr int kPeripheryNames = 720; // Stadium_RenderPanorama_TextPointer: stadiumFeatureTrafficAccess .. FanShop4 (14) + +constexpr int32_t kMaxMoney = std::numeric_limits::max(); + +} // namespace + +void Console::register_money_commands() { + // --- Bank (06-verein: Bank) ----------------------------------------------------------- + auto bank = [this] { + const auto p = prep(); + if (!p.bank) fail("E_MODE_LOCKED", "no bank available (national team?)"); + return *p.bank; + }; + auto dispatch_bank = [this](const ui::BankRequest& r) { + std::string error; + require_engine(app::BankActions(*session_).dispatch(r, revision_, error), "bank", error); + }; + auto show_bank = [this, bank] { + const ui::BankState b = bank(); + emit_table({"Bank", "Value"}, + {{"balance", money(b.balance)}, {"savings", money(b.deposit)}, {"creditLine", money(b.credit_line)}, + // record +0x324: the balance the season result is measured from (season start, + // moved with deposits and share deals; result = balance - this, season.cpp) + {"seasonBase", money(b.investment_balance)}}); + }; + openers_[14] = [this, show_bank] { + open_window("Bank"); + show_bank(); + }; + add({"Bank", "ShowBank", {}, "balance, savings, credit line, season base", false}, [show_bank](const Values&) { show_bank(); }); + auto show_overview = [this, bank] { + const ui::BankState b = bank(); + std::vector> rows; + for (size_t i = 0; i < 7; ++i) rows.push_back({text(kFinanceLabels + int(i)), money(b.finance_values[i])}); + emit_table({"Finance", "Value"}, rows); + }; + // opening a bank page shows its content at once (as the original screen does) + add({"Bank", "OpenAccount", {}, "the finance overview (Bank.Account)", false}, [this, show_overview](const Values&) { + open_window("Bank.Account"); + show_overview(); + }); + add({"Bank", "OpenSavings", {}, "the fixed deposit (Bank.Savings)", false}, [this](const Values&) { open_window("Bank.Savings"); emit('+', "savings (ShowSavings, Deposit, Withdraw)"); }); + add({"Bank", "OpenShares", {}, "the stock market (Bank.Shares)", false}, [this](const Values&) { open_window("Bank.Shares"); emit('+', "shares (ListShares, ShowShare, BuyShares, SellShares)"); }); + add({"Bank", "OpenRealEstate", {}, "real estate funds (Bank.RealEstate)", false}, [this](const Values&) { open_window("Bank.RealEstate"); emit('+', "real estate (ListRealEstate shows the funds)"); }); + Param lender = choice("lender", {"Bank", "Manager1", "Manager2", "Manager3", "Manager4"}, true); + add({"Bank", "OpenCredit", {lender}, "the credit view (Bank.Credit)", false}, [this](const Values& v) { + // case 5 (MaxSharesToBuy): a credit from another human manager (row lender + 1) + const int lender = v.has("lender") ? v.choice("lender") - 1 : -1; + if (lender >= 0 && (size_t(lender) >= session_->state().manager_teams.size() || lender == active_slot())) + fail("E_RULE", "no other manager " + std::to_string(lender + 1) + " in this game"); + credit_counterparty_ = lender + 1; + credit_draft_.reset(); + open_window("Bank.Credit"); + emit('+', std::string("credit ") + (lender >= 0 ? "from player " + std::to_string(lender + 1) : "from the bank") + " (ShowCredit)"); + }); + + add({"Bank.Account", "ShowFinanceOverview", {}, "assets, debts and net worth", false}, + [show_overview](const Values&) { show_overview(); }); + add({"Bank.Account", "ShowAssetProfitLoss", {integer("asset", 0, 11)}, "profit/loss of a share", false}, [this, bank](const Values& v) { + const ui::BankState b = bank(); + const auto& s = b.stocks[size_t(v.integer("asset"))]; + emit_table({"Share", "Owned", "Paid", "Price", "Value"}, + {{text(kShareNames + int(v.integer("asset"))), std::to_string(s.owned), money(s.paid), std::to_string(s.price), + money(int64_t(s.owned) * s.price)}}); + }); + + auto show_savings = [this, bank] { + const ui::BankState b = bank(); + emit_table({"Savings", "Value"}, {{"balance", money(b.balance)}, {"savings", money(b.deposit)}}); + }; + add({"Bank.Savings", "ShowSavings", {}, "account and fixed deposit", false}, [show_savings](const Values&) { show_savings(); }); + add({"Bank.Savings", "Deposit", {integer("amount", 1, kMaxMoney)}, "account -> fixed deposit", true}, + [bank, dispatch_bank, show_savings](const Values& v) { + const auto r = app::BankActions::savings(bank(), int32_t(v.integer("amount"))); + dispatch_bank(r); + show_savings(); + }); + add({"Bank.Savings", "Withdraw", {integer("amount", 1, kMaxMoney)}, "fixed deposit -> account", true}, + [bank, dispatch_bank, show_savings](const Values& v) { + const auto r = app::BankActions::savings(bank(), -int32_t(v.integer("amount"))); + dispatch_bank(r); + show_savings(); + }); + + auto share_row = [this](const ui::BankState& b, size_t i) { + const auto& s = b.stocks[i]; + std::string trend = s.price > s.previous_price ? "up" : s.price < s.previous_price ? "down" : "="; + return std::vector{std::to_string(i), text(kShareNames + int(i)), std::to_string(s.price), trend, + std::to_string(s.owned), money(s.paid), std::to_string(s.max_to_buy)}; + }; + const std::vector share_header = {"Asset", "Share", "Price", "Trend", "Owned", "Paid", "MaxBuy"}; + add({"Bank.Shares", "ListShares", {}, "the twelve shares", false}, [this, bank, share_row, share_header](const Values&) { + const ui::BankState b = bank(); + std::vector> rows; + for (size_t i = 0; i < 12; ++i) rows.push_back(share_row(b, i)); + emit_table(share_header, rows); + }); + add({"Bank.Shares", "ShowShare", {integer("asset", 0, 11)}, "one share with its last 30 prices", false}, + [this, bank, share_row, share_header](const Values& v) { + const ui::BankState b = bank(); + const size_t i = size_t(v.integer("asset")); + emit_table(share_header, {share_row(b, i)}); + std::string history; + for (uint16_t p : b.stocks[i].history) history += (history.empty() ? "" : " ") + std::to_string(p); + emit('i', "history: " + history); + }); + add({"Bank.Shares", "ShareAdvice", {integer("asset", 0, 11)}, "the bank's tip for a share", true}, + [this, bank, dispatch_bank](const Values& v) { + const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::stock_tip, int(v.integer("asset"))); + dispatch_bank(r); + // the screen shows the TEXTD advice Bank_FormatError_RuntimeField19 + tip * 4 (src/ui/bank.cpp) + const ui::BankState b = bank(); + if (!b.last_tip) fail("E_INTERNAL", "the bank gave no tip"); + emit('+', text(kShareNames + r.asset_index) + ": " + text(kShareTips + *b.last_tip)); + }); + auto trade = [this, bank, dispatch_bank, share_row, share_header](const Values& v, ui::BankRequestKind kind) { + const auto r = app::BankActions::investment(bank(), kind, int(v.integer("asset")), int(v.integer("count"))); + dispatch_bank(r); + emit_table(share_header, {share_row(bank(), size_t(r.asset_index))}); + }; + add({"Bank.Shares", "BuyShares", {integer("asset", 0, 11), integer("count", 1, 9999)}, "buy shares", true}, + [trade](const Values& v) { trade(v, ui::BankRequestKind::buy_shares); }); + add({"Bank.Shares", "SellShares", {integer("asset", 0, 11), integer("count", 1, 9999)}, "sell shares", true}, + [trade](const Values& v) { trade(v, ui::BankRequestKind::sell_shares); }); + + auto show_funds = [this, bank] { + const ui::BankState b = bank(); + std::vector> rows; + for (size_t i = 0; i < 6; ++i) { + const auto& f = b.funds[i]; + // the original writes the name stem plus a singular/plural ending (Bank_OriginalToUtf8_RuntimeField) + rows.push_back({std::to_string(i), utf8(f.name) + f.plural_suffix, money(f.price), std::to_string(f.owned), money(f.paid), std::to_string(f.max_to_buy)}); + } + emit_table({"Type", "Fund", "Price", "Owned", "Paid", "MaxBuy"}, rows); + if (b.property_notice) emit('i', utf8(b.property_notice->text)); + }; + add({"Bank.RealEstate", "ListRealEstate", {}, "the six real estate funds", false}, [show_funds](const Values&) { show_funds(); }); + add({"Bank.RealEstate", "BuyRealEstate", {integer("type", 0, 5), integer("units", 1, 10)}, "buy units", true}, + [bank, dispatch_bank, show_funds](const Values& v) { + const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::buy_fund, + int(v.integer("type")), int(v.integer("units"))); + dispatch_bank(r); + show_funds(); + }); + add({"Bank.RealEstate", "SellRealEstate", {integer("type", 0, 5), integer("units", 1, 10)}, "sell units", true}, + [bank, dispatch_bank, show_funds](const Values& v) { + const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::sell_fund, + int(v.integer("type")), int(v.integer("units"))); + dispatch_bank(r); + show_funds(); + }); + + // --- Bank.Credit: the bank's credit editor (MaxSharesToBuy case 4, H2 p. 60-61) ---------- + // As the screen does it (src/ui/bank.cpp): a local draft of the eight rows, edited field + // by field within the engine's bounds (bank_credit_bounds / edit_bank_credit, read-only); + // ConfirmCredit books the edits through dispatch_bank (commit_bank_credit replays them + // against the saved loan). Fees (5,000 EU for a change, interest adjustment) need a yes. + // the loan row of the open credit: the bank's from the bank projection, a manager's from the + // engine (bank_credit_context with the counterparty) + auto credit_context = [this, bank] { + if (credit_counterparty_ == 0) return bank().credit; + return bank_credit_context(session_->state(), exe_, active_slot(), credit_counterparty_); + }; + auto credit_draft = [this, credit_context] { + if (!credit_draft_) credit_draft_ = bank_credit_draft(credit_context()); + return *credit_draft_; + }; + auto show_credit = [this, credit_context, credit_draft] { + const BankCreditDraft d = credit_draft(); + std::vector> rows; + for (int i = 0; i < 8; ++i) { + const BankCreditBounds bounds = bank_credit_bounds(credit_context(), d, i); + rows.push_back({std::to_string(i), text(kCreditLabels + i), money(d.values[size_t(i)]), + bounds.available ? money(bounds.minimum) + ".." + money(bounds.maximum) : "-"}); + } + emit_table({"Row", "Credit", "Value", "Editable"}, rows); + // only the bank charges fees and the interest adjustment (case 5 has none) + const int32_t fees = credit_counterparty_ ? 0 : d.fees + d.interest_adjustment; + if (!d.edits.empty()) emit('i', "changes not booked yet" + (fees ? ", fees and interest " + money(fees) : std::string())); + }; + // the editable rows: 0 amount paid out, 1 total amount, 3 term, 6 repayment + auto edit_credit = [this, credit_context, credit_draft, show_credit](int field, long long value) { + BankCreditDraft d = credit_draft(); + const BankCreditBounds bounds = bank_credit_bounds(credit_context(), d, field); + if (!bounds.available) fail("E_RULE", text(kCreditLabels + field) + " cannot be changed now"); + if (value < bounds.minimum || value > bounds.maximum) + fail("E_BAD_ARGUMENT", text(kCreditLabels + field) + " must be " + money(bounds.minimum) + ".." + money(bounds.maximum)); + if (!edit_bank_credit(credit_context(), d, field, uint32_t(value))) fail("E_RULE", "the bank does not accept this value"); + credit_draft_ = d; + show_credit(); + }; + add({"Bank.Credit", "ShowCredit", {lender}, "the credit rows with the editable ranges", false}, + [show_credit](const Values&) { show_credit(); }); + add({"Bank.Credit", "SetCreditAmount", {integer("amount", 0, kMaxMoney)}, "AUSGEZAHLTER BETRAG: the credit", false}, + [edit_credit](const Values& v) { edit_credit(0, v.integer("amount")); }); + add({"Bank.Credit", "SetCreditPayment", {integer("monthly", 0, kMaxMoney)}, + "the monthly payment: within 20 % of the annuity for a credit from a manager", false}, + [this, edit_credit](const Values& v) { + if (credit_counterparty_ == 0) fail("E_RULE", "the monthly payment follows from the amount and the term (SetCreditTerm)"); + edit_credit(2, v.integer("monthly")); + }); + add({"Bank.Credit", "SetCreditTerm", {integer("months", 1, 48)}, "LAUFZEIT in months", false}, + [edit_credit](const Values& v) { edit_credit(3, v.integer("months")); }); + Param repay = detail::text("amount"); + repay.display = "amount:money|All"; + add({"Bank.Credit", "RepayCredit", {repay}, "RÜCKZAHLUNG: pay back (All = as much as possible)", false}, + [this, credit_context, credit_draft, edit_credit](const Values& v) { + Arg a; + a.text = v.text("amount"); + long long amount = 0; + if (lower(a.text) == "all") { + const BankCreditBounds bounds = bank_credit_bounds(credit_context(), credit_draft(), 6); + if (!bounds.available) fail("E_RULE", "nothing to repay"); + amount = bounds.maximum; + } else if (const auto n = to_int(a)) { + amount = *n; + } else { + fail("E_BAD_ARGUMENT", "amount is a number or All"); + } + edit_credit(6, amount); + }); + auto book = [this, bank, credit_context, credit_draft, dispatch_bank](bool accept_fees) { + const BankCreditDraft d = credit_draft(); + const auto r = app::BankActions::credit(bank(), credit_context(), d, accept_fees, credit_counterparty_); + dispatch_bank(r); + credit_draft_.reset(); + const ui::BankState after = bank(); + if (after.credit_notice) emit('i', after.credit_notice->text); + emit('+', "credit booked, balance " + money(after.balance)); + }; + add({"Bank.Credit", "ConfirmCredit", {}, "book the changes (asks about fees)", true}, [this, credit_draft, book](const Values&) { + const BankCreditDraft d = credit_draft(); + if (d.edits.empty()) fail("E_RULE", "nothing changed"); + const int32_t fees = credit_counterparty_ ? 0 : d.fees + d.interest_adjustment; + if (fees == 0) { + book(false); + return; + } + // the screen's fee confirmation (credit_fee_confirmation_open_); the console's wording + ask("The change costs " + money(fees) + " in fees and interest. Book it?", {"Yes", "No"}, "No", [this, book](const std::string& answer) { + if (answer == "Yes") book(true); + else emit('+', "credit not changed (the draft stays)"); + }); + }); + add({"Bank.Credit", "CancelCredit", {}, "discard the changes", false}, [this](const Values&) { + credit_draft_.reset(); + emit('+', "credit changes discarded"); + }); + + // --- Stadium (06-verein 8) ------------------------------------------------------------ + auto stadium = [this] { + const auto p = prep(); + if (!p.stadium) fail("E_MODE_LOCKED", "no stadium view (national team?)"); + return *p.stadium; + }; + // Requests carry the engine's stadium scope (stable club, scope, sequence) as the SDL + // screen's do (StadiumScreen::request); a stale request is refused by the engine. + auto stadium_request = [](const ui::StadiumState& observed, ui::StadiumRequestKind kind, + int object = -1, int option = -1, int32_t price = 0, bool accept_tip = false) { + return app::StadiumActions::request(observed, kind, object, option, price, accept_tip); + }; + auto dispatch_stadium = [this](const ui::StadiumRequest& r) { + std::string error; + require_engine(app::StadiumActions(*session_).dispatch(r, revision_, error), "stadium", error); + }; + auto show_stadium = [this, stadium] { + const ui::StadiumState s = stadium(); + std::vector> rows; + for (size_t i = 0; i < 8; ++i) { + const auto& row = s.investments[i]; + std::string offers; + for (size_t o = 0; o < row.options.size(); ++o) + offers += (o ? ", " : "") + std::string("level ") + std::to_string(row.options[o].target_level) + " for " + + money(row.options[o].base_price); + rows.push_back({std::to_string(i), utf8(row.original_label), std::to_string(row.current_level), + row.construction_weeks ? std::to_string(row.construction_weeks) + " weeks" : "-", + row.available && !row.options.empty() ? offers : "-"}); + } + emit_table({"Item", "Name", "Level", "Building", "Options"}, rows); + std::vector> blocks; + for (size_t b = 0; b < 8; ++b) + blocks.push_back({std::string(1, char('A' + b)), std::to_string(int(s.blocks[b].capacity_level) * 1000), + s.blocks[b].construction_weeks ? std::to_string(int(s.blocks[b].capacity) * 1000) : "-", + s.blocks[b].construction_weeks ? std::to_string(s.blocks[b].construction_weeks) + " weeks" : "-"}); + emit_table({"Block", "Places", "PlannedPlaces", "Building"}, blocks); + emit('i', "balance " + money(s.balance) + ", construction prices " + std::to_string(s.construction_percent) + " %" + + (s.action_feedback.empty() ? "" : ", " + utf8(s.action_feedback))); + }; + auto show_periphery = [this, stadium] { + const ui::StadiumState s = stadium(); + std::vector> rows; + for (size_t o = 0; o < 14; ++o) { + const bool building = s.days[o] != 0; + const bool built = o == 0 ? s.level[o] >= 0xab : s.level[o] != 0; // as dispatch_stadium checks + rows.push_back({std::to_string(o), text(kPeripheryNames + int(o)), building ? "building" : built ? "built" : "-", + std::to_string(s.days[o])}); + } + emit_table({"Object", "Name", "State", "Days"}, rows); + emit('i', "balance " + money(s.balance)); + }; + openers_[22] = [this, stadium, stadium_request, dispatch_stadium, show_stadium] { + const ui::StadiumState s = stadium(); + open_window("Stadium"); + if (!s.opened) dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::open)); + show_stadium(); + }; + // leaving the stadium is an engine step (close), refused while an offer is open + closers_["Stadium"] = [this, stadium, stadium_request, dispatch_stadium] { + const ui::StadiumState s = stadium(); + if (s.opened) dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::close)); + close_window(); + emit('+', "stadium closed"); + }; + add({"Stadium", "ShowStadium", {}, "facilities, maintenance and blocks", false}, [show_stadium](const Values&) { show_stadium(); }); + add({"Stadium", "OpenPeriphery", {}, "SICHT: PANORAMA (Stadium.Periphery)", false}, [this, show_periphery](const Values&) { + open_window("Stadium.Periphery"); + show_periphery(); + }); + // AUSBAUEN for one of the eight investments (Front / PayConstruction): a tier is + // chosen, confirmed, then the builder asks about a tip; each answer is one engine step. + auto invest = [this, stadium, stadium_request, dispatch_stadium](int item) { + ui::StadiumState s = stadium(); + const auto& row = s.investments[size_t(item)]; + if (!row.available || row.options.empty()) + fail("E_RULE", utf8(row.original_label) + (row.construction_weeks ? " is being built" : " cannot be built now")); + const std::string label = utf8(row.original_label); + dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::select_investment, item)); + s = stadium(); + std::vector choices; + std::string list; + for (const auto& option : s.investments[size_t(item)].options) { + choices.push_back("Level" + std::to_string(option.target_level)); + list += (list.empty() ? "" : ", ") + choices.back() + " = " + money(option.base_price); + } + choices.push_back("Cancel"); + ask(label + ": " + list, choices, "Cancel", [this, item, label, stadium, stadium_request, dispatch_stadium](const std::string& answer) { + ui::StadiumState s = stadium(); + if (answer == "Cancel") { + dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::cancel_investment, item)); + emit('+', "nothing built"); + return; + } + const auto& options = s.investments[size_t(item)].options; + int index = -1; + for (size_t o = 0; o < options.size(); ++o) + if ("Level" + std::to_string(options[o].target_level) == answer) index = int(o); + if (index < 0) fail("E_INTERNAL", "the offer changed"); + const int32_t price = int32_t(options[size_t(index)].base_price); + dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::select_investment_option, item, index, price)); + dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::confirm_investment, item, index, price)); + s = stadium(); + if (!s.construction_tip_dialog) fail("E_INTERNAL", "the builder asked nothing"); + const int32_t tip_price = int32_t(s.construction_tip_price); + // the original's composed TEXTD sentence: a small tip of n percent makes them faster + ask(utf8(s.construction_tip_dialog->body) + " (" + money(tip_price) + " instead of " + money(price) + ")", {"Yes", "No"}, "No", + [this, item, index, price, tip_price, label, stadium, stadium_request, dispatch_stadium](const std::string& tip) { + const bool accept = tip == "Yes"; + dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::answer_construction_tip, item, index, + accept ? tip_price : price, accept)); + const ui::StadiumState after = stadium(); + if (!after.action_feedback.empty()) fail("E_INSUFFICIENT_FUNDS", utf8(after.action_feedback)); + emit('+', label + " ordered for " + money(accept ? tip_price : price)); + }); + }); + }; + add({"Stadium", "BuildFacility", {choice("facility", {"Floodlights", "Scoreboard", "PitchHeating", "VipLounge"})}, + "technical expansion (AUSBAUEN): tier and tip questions", true}, + [invest](const Values& v) { invest(v.choice("facility")); }); + add({"Stadium", "Maintain", {choice("item", {"Pitch", "Comfort", "Condition", "Safety"})}, "maintenance: tier and tip questions", true}, + [invest](const Values& v) { invest(4 + v.choice("item")); }); + // The GUI and CareerSession already implement the A-H block editor and stadium + // data. These console commands still lack their own argument/projection adapter + // (the stage-2 placeholders from issue #16); this is a console-only gap. + for (const char* name : {"QuoteBlockExpansion", "ConfirmBlockExpansion", "DeclineBlockExpansion", "ShowFutureExpansion", "OpenData"}) + add({"Stadium", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + ": the block editor / stadium data are not ported yet"); }); + add({"Stadium", "SetTicketPrice", {integer("price", 8, 25)}, "the ticket price (as on the desk)", true}, [this](const Values& v) { + // the same engine write as the desk's price scale (CareerSession::dispatch_ticket_price) + const ui::DeskState d = desk(); + std::string error; + require_engine(app::DeskActions(*session_).ticket_price(d, int(v.integer("price")), revision_, error), "ticket price", error); + emit('+', "ticket price: " + std::to_string(desk().ticket_price)); + }); + + add({"Stadium.Periphery", "ListPeriphery", {}, "the 14 objects: built, building, days", false}, [show_periphery](const Values&) { show_periphery(); }); + auto periphery = [this, stadium, stadium_request, dispatch_stadium](int object, int32_t price, bool build) { + try { + dispatch_stadium(stadium_request(stadium(), build ? ui::StadiumRequestKind::build_periphery : ui::StadiumRequestKind::decline_periphery, + object, -1, price)); + } catch (...) { + // a refused build (no money) must not leave the offer open: the stadium could not + // be closed any more. It ends like NEIN, then the refusal is reported. + if (build && stadium().quoted_object) { + try { + dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::decline_periphery, object, -1, price)); + } catch (...) {} + } + throw; + } + emit('+', text(kPeripheryNames + object) + (build ? " is being built for " + money(price) : " not built")); + }; + add({"Stadium.Periphery", "QuotePeriphery", {integer("object", 0, 13)}, "the building firm's current offer (question)", true}, + [this, stadium, stadium_request, dispatch_stadium, periphery](const Values& v) { + dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::quote_periphery, int(v.integer("object")))); + const ui::StadiumState s = stadium(); + if (!s.quoted_object) fail("E_INTERNAL", "the engine gave no offer"); + const int object = *s.quoted_object; + const int32_t price = s.quoted_price; + // OK / NEIN of the original; the console's own wording, the original shows a + // composed TEXTD sentence with the price + ask(text(kPeripheryNames + object) + ": offer " + money(price) + ". Accept?", {"Yes", "No"}, "No", + [periphery, object, price](const std::string& answer) { periphery(object, price, answer == "Yes"); }); + }); + add({"Stadium.Periphery", "BuildPeriphery", {integer("object", 0, 13), integer("price", 1, kMaxMoney)}, "accept the offer", true}, + [periphery](const Values& v) { periphery(int(v.integer("object")), int32_t(v.integer("price")), true); }); + add({"Stadium.Periphery", "DeclinePeriphery", {integer("object", 0, 13), integer("price", 1, kMaxMoney)}, "decline the offer", true}, + [periphery](const Values& v) { periphery(int(v.integer("object")), int32_t(v.integer("price")), false); }); + add({"Stadium.Periphery", "OpenInterior", {}, "SICHT: INNEN (back to Stadium)", false}, [this](const Values&) { close_window(); }); + + // --- Toto (05/06: Toto, H2 p. 56-57) -------------------------------------------------- + auto toto = [this] { + const auto p = prep(); + if (!p.toto) fail("E_MODE_LOCKED", "no Toto in this game"); + return *p.toto; + }; + // tip draft of the open coupon (the original keeps the picks in the screen until MACH ICH) + auto tips = std::make_shared>(); + auto stake = std::make_shared(0); + auto show_toto = [this, toto, tips, stake] { + const ui::TotoState t = toto(); + if (!t.available) { + emit('i', "no Toto coupon this week" + (t.feedback.empty() ? std::string() : ": " + utf8(t.feedback))); + return; + } + std::vector> rows; + for (size_t i = 0; i < t.matches.size(); ++i) { + const uint8_t pick = i < tips->size() ? (*tips)[i] : 0; + rows.push_back({std::to_string(i + 1), utf8(t.matches[i].home_name), utf8(t.matches[i].away_name), pick == 0 ? "1" : pick == 1 ? "X" : "2"}); + } + emit_table({"Match", "Home", "Away", "Tip"}, rows); + emit('i', "stake " + money(*stake) + ", balance " + money(t.balance) + (t.feedback.empty() ? "" : ", " + utf8(t.feedback))); + }; + openers_[13] = [this, toto, tips, stake, show_toto] { + const ui::TotoState t = toto(); + for (size_t i = 0; i < tips->size(); ++i) (*tips)[i] = i < t.matches.size() ? t.matches[i].pick : 0; + *stake = t.stake; + open_window("Toto"); + show_toto(); + }; + add({"Toto", "ShowToto", {}, "the eleven matches with your tips", false}, [show_toto](const Values&) { show_toto(); }); + // tips are written 1 (home), X or 0 (draw), 2 (away); stored 0, 1, 2 (src/ui/toto.cpp) + auto parse_tip = [](const std::string& s) -> int { + const std::string t = lower(s); + if (t == "1") return 0; + if (t == "x" || t == "0") return 1; + if (t == "2") return 2; + fail("E_BAD_ARGUMENT", "a tip is 1, X (or 0) or 2"); + }; + Param tip_param = detail::text("tip"); + tip_param.display = "tip:enum(1,X,2)"; + add({"Toto", "SetTip", {integer("match", 1, 11), tip_param}, "the tip for one match", false}, [this, tips, parse_tip](const Values& v) { + (*tips)[size_t(v.integer("match") - 1)] = uint8_t(parse_tip(v.text("tip"))); + emit('+', "match " + std::to_string(v.integer("match")) + ": " + v.text("tip")); + }); + add({"Toto", "SetStake", {integer("amount", 0, kMaxMoney)}, "the stake", false}, [this, stake](const Values& v) { + *stake = uint32_t(v.integer("amount")); + emit('+', "stake " + money(*stake)); + }); + Param tip_list = detail::text("tips", 0, true); + tip_list.display = "[tips:list(11)]"; + add({"Toto", "SubmitToto", {integer("stake", 0, kMaxMoney, true), tip_list}, "MACH ICH: hand in the coupon", true}, + [this, toto, tips, stake, parse_tip, show_toto](const Values& v) { + const ui::TotoState t = toto(); + if (!t.available) fail("E_RULE", "no Toto coupon this week"); + if (v.has("stake")) *stake = uint32_t(v.integer("stake")); + // submit_pools_coupon: no stake, or 10.000 to 400.000 + if (*stake != 0 && (*stake < 10000 || *stake > 400000)) fail("E_BAD_ARGUMENT", "the stake is 0 or 10000 to 400000"); + if (v.has("tips")) { + std::string list = v.text("tips"); + if (list.size() < 2 || list.front() != '[' || list.back() != ']') fail("E_BAD_ARGUMENT", "tips is a list [1, X, 2, ...]"); + list = list.substr(1, list.size() - 2); + std::vector parsed; + size_t start = 0; + while (start <= list.size()) { + size_t comma = list.find(',', start); + std::string item = list.substr(start, comma == std::string::npos ? std::string::npos : comma - start); + item.erase(0, item.find_first_not_of(' ')); + item.erase(item.find_last_not_of(' ') + 1); + parsed.push_back(parse_tip(item)); + if (comma == std::string::npos) break; + start = comma + 1; + } + if (parsed.size() != 11) fail("E_BAD_ARGUMENT", "tips needs 11 values"); + for (size_t i = 0; i < 11; ++i) (*tips)[i] = uint8_t(parsed[i]); + } + ui::TotoRequest r; + r.kind = ui::TotoRequestKind::submit; + r.manager_slot = t.manager_slot; + r.runtime_club = t.runtime_club; + r.revision = revision_; + r.stake = *stake; + r.tips = *tips; + std::string error; + require_engine(session_->dispatch_toto(r, revision_, error), "Toto", error); + emit('+', "coupon handed in, stake " + money(*stake)); + show_toto(); + }); + add({"Toto", "ClearToto", {}, "all tips back to 1, stake 0", false}, [this, tips, stake](const Values&) { + tips->fill(0); + *stake = 0; + emit('+', "coupon cleared"); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_office.cpp b/src/cli/console/windows_office.cpp new file mode 100644 index 0000000..ed86388 --- /dev/null +++ b/src/cli/console/windows_office.cpp @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +// The office windows of docs/CLI_CONCEPT: Advertising (menu 21, 06-verein 9), Contracts +// (menu 27, 06-verein 6) and Settings (menu 19, 08-einstellungen). Views from the pure +// projections ui::advertising_from_game / contracts_from_game / settings_from_game, changes +// through dispatch_advertising / dispatch_contract / dispatch_settings with the requests +// the SDL screens build (src/ui/advertising.cpp, contracts.cpp, settings.cpp). + +#include +#include + +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "ui/advertising.hpp" +#include "ui/contracts.hpp" +#include "ui/settings.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +const std::vector kAdSlots = {"Board1", "Board2", "Board3", "Board4", "Board5", "Board6", "Board7", "Board8", + "Board9", "Board10", "Board11", "Board12", "Board13", "Board14", "Shirt", "Tv"}; +// the seven bonuses, in the order of the manager record / ContractRequest::proposed_bonuses +// the three spending targets 16-18 (AdvertisingSpendingView::target_slot); the original +// labels them with pictures, its TEXTD labels ("Monatsausgaben:") do not tell PR from fan care +const std::vector kSpending = {"FanItems", "PublicRelations", "FanCare"}; +const std::vector kBonuses = {"Goal", "Points", "Appearance", "Champion", "Place2to5", "Place6to10", "AvoidRelegation"}; +// the first three bonuses are percentages up to 20, the others up to 200 (dispatch_contract) +int bonus_max(int kind) { return kind < 3 ? 20 : 200; } + +constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU + +// Settings: row A-T, column 1-9 (08-einstellungen); A1 = row 0, column 0. +std::pair switch_key(const std::string& key) { + if (key.size() < 2 || key.size() > 2) fail("E_BAD_ARGUMENT", "a switch is A1 ... T9"); + const int row = std::toupper(static_cast(key[0])) - 'A'; + const int column = key[1] - '1'; + if (row < 0 || row >= 20 || column < 0 || column >= 9) fail("E_BAD_ARGUMENT", "a switch is A1 ... T9"); + return {row, column}; +} + +} // namespace + +void Console::register_office_commands() { + // --- Advertising ---------------------------------------------------------------------- + auto adverts = [this] { return ui::advertising_from_game(session_->state(), active_slot(), revision_); }; + auto contract_of = [](const ui::AdvertisingState& a, int slot) -> const ui::AdvertisingContract& { + return slot < 14 ? a.boards.at(size_t(slot)) : slot == 14 ? a.shirt : a.television; + }; + auto show_adverts = [this, adverts, contract_of] { + const ui::AdvertisingState a = adverts(); + std::vector> rows; + for (int slot = 0; slot < 16; ++slot) { + const auto& c = contract_of(a, slot); + rows.push_back({kAdSlots[size_t(slot)], c.active ? utf8(c.sponsor_name) : "free", c.active ? money(c.monthly_amount) : "-", + c.active ? std::to_string(c.months_remaining) : "-", c.option_marker ? "option" : ""}); + } + emit_table({"Slot", "Sponsor", "Monthly", "Months", ""}, rows); + std::vector> spending; + for (size_t i = 0; i < 3; ++i) + spending.push_back({kSpending[i], money(a.spending[i].current_amount), money(a.spending[i].maximum_amount), + a.spending[i].available ? "" : "locked"}); + emit_table({"Spending", "Amount", "Maximum", ""}, spending); + emit('i', "monthly: income " + money(a.finance_preview.income) + ", expenses " + money(a.finance_preview.expenses) + + ", balance " + money(a.finance_preview.balance)); + if (!a.notification_text.empty()) emit('i', utf8(a.notification_text)); + }; + openers_[21] = [this, show_adverts] { + open_window("Advertising"); + show_adverts(); + }; + add({"Advertising", "ShowAdvertising", {}, "all boards, shirt, TV and the spending", false}, [show_adverts](const Values&) { show_adverts(); }); + auto offers_of = [](const ui::AdvertisingState& a, int slot) { + std::vector list; + for (const auto& o : a.offers[size_t(slot)].offers) + if (o.present && o.monthly_amount != 0) list.push_back(&o); + return list; + }; + add({"Advertising", "ListAdOffers", {choice("slot", kAdSlots)}, "the offers for a board, the shirt or TV (an expired contract: renewal first)", true}, + [this, adverts, offers_of](const Values& v) { + const int slot = v.choice("slot"); + // A contract whose months ran out: the click on it asks for the renewal first + // (CheckAdvertisingRenewal) - the sponsor may decline, otherwise the manager decides; a + // declined or refused renewal frees the place for the offers below. + if (adverts().offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension) { + std::string error; + const auto renewal = session_->check_advertising_renewal(adverts().manager_slot, slot, revision_, error); + if (!renewal) require_engine(false, "advertising", error); + if (renewal->status == AdvertisingRenewal::Status::declined_by_sponsor) { + emit('i', utf8(renewal->notice)); + } else if (renewal->status == AdvertisingRenewal::Status::offered) { + const int manager = adverts().manager_slot, contract = renewal->contract_slot; + ask(utf8(renewal->question), {"Yes", "No"}, "No", [this, manager, contract, slot](const std::string& answer) { + std::string err; + if (!session_->answer_advertising_renewal(manager, contract, answer == "Yes", revision_, err)) + require_engine(false, "advertising", err); + emit('+', answer == "Yes" ? "contract renewed" : "contract not renewed: ListAdOffers(" + + kAdSlots[size_t(slot)] + ") shows the offers"); + }); + return; + } + } + const ui::AdvertisingState a = adverts(); + const auto& list = a.offers[size_t(slot)]; + const auto& names = list.pool_group == 2 ? a.television_sponsor_names : a.board_sponsor_names; + std::vector> rows; + int n = 0; + for (const auto* o : offers_of(a, slot)) + rows.push_back({std::to_string(++n), utf8(names[size_t(std::clamp(int(o->sponsor_id), 0, 9))]), money(o->monthly_amount), + std::to_string(o->months), std::to_string(o->bundle_units), o->can_accept ? "" : "not possible"}); + if (rows.empty()) emit('i', "no offers for " + kAdSlots[size_t(slot)]); + else emit_table({"Offer", "Sponsor", "Monthly", "Months", "Boards", ""}, rows); + }); + add({"Advertising", "AcceptAdOffer", {choice("slot", kAdSlots), integer("offer", 1, 10)}, "ANNEHMEN", true}, + [this, adverts, offers_of, show_adverts](const Values& v) { + const ui::AdvertisingState a = adverts(); + const int slot = v.choice("slot"); + const auto list = offers_of(a, slot); + const size_t n = size_t(v.integer("offer")); + if (n > list.size()) fail("E_BAD_ARGUMENT", "no offer " + std::to_string(n) + " (ListAdOffers)"); + if (a.offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension) + fail("E_RULE", "the contract on " + kAdSlots[size_t(slot)] + " ran out: ListAdOffers(" + kAdSlots[size_t(slot)] + + ") asks for the renewal first"); + if (!list[n - 1]->can_accept) fail("E_RULE", "this offer cannot be accepted"); + std::string error; + if (!session_->accept_advertising_selection(a, slot, list[n - 1]->raw_slot, + next_request_id_++, revision_, error)) + require_engine(false, "advertising", error); + emit('+', "offer accepted for " + kAdSlots[size_t(slot)]); + show_adverts(); + }); + add({"Advertising", "DeclineAdOffer", {}, "ABBRECHEN", false}, [this](const Values&) { emit('+', "no offer accepted"); }); + auto spend = [this, adverts](int target, uint32_t amount) { + const ui::AdvertisingState a = adverts(); + const auto& view = a.spending[size_t(target - 16)]; + if (!view.available) fail("E_RULE", utf8(a.spending_blocked_text.empty() ? "not available now" : a.spending_blocked_text)); + if (amount > view.maximum_amount) fail("E_BAD_ARGUMENT", "at most " + money(view.maximum_amount)); + AdvertisingSpendingResult result; + std::string error; + if (!session_->set_advertising_budget(a, target, amount, next_request_id_++, revision_, error, result)) + require_engine(false, "advertising", error); + const std::string message = result.message_address >= ::bmh::layout::TextPointerTable ? text(int((result.message_address - ::bmh::layout::TextPointerTable) / 4)) : ""; + if (result.status == AdvertisingSpendingStatus::insufficient_funds) fail("E_INSUFFICIENT_FUNDS", message); + emit('+', kSpending[size_t(target - 16)] + ": " + money(amount) + (message.empty() ? "" : ". " + message)); + }; + add({"Advertising", "SetSpending", {choice("kind", {"PublicRelations", "FanCare"}), integer("amount", 0, std::numeric_limits::max())}, + "monthly budget for press work or fan care", true}, + [spend](const Values& v) { spend(17 + v.choice("kind"), uint32_t(v.integer("amount"))); }); + add({"Advertising", "BuyFanItems", {integer("amount", 1, std::numeric_limits::max())}, "buy fan articles (sold in 6-9 weeks)", true}, + [spend](const Values& v) { spend(16, uint32_t(v.integer("amount"))); }); + + // --- Contracts ------------------------------------------------------------------------ + auto contracts = [this] { return ui::contracts_from_game(session_->state(), active_slot(), revision_); }; + auto dispatch_contract = [this](const ui::ContractRequest& r) { + ui::ContractActionResult result; + std::string error; + require_engine(app::ContractActions(*session_).dispatch(r, revision_, result, error), "contracts", error); + return result; + }; + auto show_contracts = [this, contracts] { + const ui::ContractsState c = contracts(); + std::vector> rows; + for (const auto& p : c.players) + rows.push_back({"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name), + p.position >= 0 && p.position < 4 ? text(kPositionNames + p.position) : "?", std::to_string(p.age), + money(p.current_monthly_salary), std::to_string(p.remaining_months), + p.insurance ? std::to_string(p.insurance) : "-", p.offer_blocked ? "[sulking]" : ""}); + emit_table({"Row", "Id", "Player", "Pos", "Age", "Salary", "Months", "Insurance", ""}, rows); + }; + openers_[27] = [this, show_contracts] { + session_->clear_contract_quote(); + open_window("Contracts"); + show_contracts(); + }; + add({"Contracts", "ShowContracts", {choice("sheet", {"A", "B"}, true)}, "the squad with salaries and contract months", false}, + [show_contracts](const Values&) { show_contracts(); }); + add({"Contracts", "ShowTeamBonuses", {}, "the seven team bonuses (percent of the salary)", false}, [this, contracts](const Values&) { + const ui::ContractsState c = contracts(); + if (!c.mode_three) fail("E_MODE_LOCKED", "team bonuses only in mode III"); + std::vector> rows; + for (size_t i = 0; i < 7; ++i) rows.push_back({kBonuses[i], std::to_string(c.team_premiums[i]), std::to_string(bonus_max(int(i)))}); + emit_table({"Bonus", "Percent", "Max"}, rows); + }); + add({"Contracts", "SetTeamBonus", {choice("kind", kBonuses), integer("percent", 0, 200)}, "a team bonus; it can only be raised", true}, + [this, contracts, dispatch_contract](const Values& v) { + const ui::ContractsState c = contracts(); + if (!c.mode_three) fail("E_MODE_LOCKED", "team bonuses only in mode III"); + const int kind = v.choice("kind"), percent = int(v.integer("percent")); + if (percent > bonus_max(kind)) fail("E_BAD_ARGUMENT", kBonuses[size_t(kind)] + " is at most " + std::to_string(bonus_max(kind))); + const auto r = app::ContractActions::team_bonus(c, kind, uint8_t(percent), next_request_id_++); + const auto result = dispatch_contract(r); + if (!result.accepted) fail("E_RULE", result.feedback.empty() ? "the team does not accept this" : result.feedback); + emit('+', result.feedback.empty() ? kBonuses[size_t(kind)] + " = " + std::to_string(percent) : result.feedback); + }); + Param player = detail::text("player"); + player.display = "player:Player"; + add({"Contracts", "OpenNegotiation", {player}, "the player's demands (Contracts.Negotiate)", true}, + [this, contracts, dispatch_contract](const Values& v) { + const ui::ContractsState c = contracts(); + std::vector refs; + for (const auto& p : c.players) refs.push_back({p.row, p.player_id, utf8(p.name)}); + const auto& p = c.players[resolve_player(v.text("player"), refs)]; + if (p.offer_blocked) fail("E_RULE", utf8(p.name) + " does not negotiate at the moment"); + const auto r = app::ContractActions::demands(c, p, next_request_id_++); + const auto result = dispatch_contract(r); + negotiation_ = Negotiation{p.row, p.player_id, utf8(p.name), result.quote_id, result.demands, -1, 0, p.team_premiums}; + open_window("Contracts.Negotiate"); + std::vector> rows; + for (size_t y = 0; y < 4; ++y) rows.push_back({std::to_string(y + 1), money(result.demands[y])}); + emit('i', utf8(p.name) + ": " + std::to_string(p.remaining_months) + " months left, salary " + money(p.current_monthly_salary)); + emit_table({"Years", "Demand"}, rows); + }); + add({"Contracts.Negotiate", "ShowDemands", {}, "the demands for 1-4 years", false}, [this](const Values&) { + if (!negotiation_) fail("E_INTERNAL", "no negotiation"); + std::vector> rows; + for (size_t y = 0; y < 4; ++y) rows.push_back({std::to_string(y + 1), money(negotiation_->demands[y])}); + emit_table({"Years", "Demand"}, rows); + if (negotiation_->years > 0) + emit('i', "offer: " + std::to_string(negotiation_->years) + " years, " + money(negotiation_->salary) + " monthly"); + }); + add({"Contracts.Negotiate", "SetContractOffer", {integer("years", 1, 4), integer("salary", 1, 200000)}, "the salary offer (monthly)", false}, + [this](const Values& v) { + if (!negotiation_) fail("E_INTERNAL", "no negotiation"); + negotiation_->years = int(v.integer("years")); + negotiation_->salary = uint32_t(v.integer("salary")); + emit('+', "offer: " + std::to_string(negotiation_->years) + " years, " + money(negotiation_->salary) + " monthly"); + }); + add({"Contracts.Negotiate", "SetInsurance", {choice("form", {"A", "B", "C", "D"}), integer("months", 1, 60)}, "insure the player (no question)", true}, + [this, contracts, dispatch_contract](const Values& v) { + if (!negotiation_) fail("E_INTERNAL", "no negotiation"); + const auto r = app::ContractActions::insurance(contracts(), negotiation_->row, negotiation_->player_id, + negotiation_->quote_id, uint8_t(v.choice("form")), uint8_t(v.integer("months")), next_request_id_++); + const auto result = dispatch_contract(r); + negotiation_->quote_id = result.quote_id; + emit('+', "insured: form " + std::string(1, char('A' + v.choice("form"))) + ", " + std::to_string(v.integer("months")) + " months"); + }); + add({"Contracts.Negotiate", "SetPlayerBonus", {choice("kind", kBonuses), integer("percent", 0, 200)}, "a bonus for this player (PRÄMIEN)", false}, + [this](const Values& v) { + if (!negotiation_) fail("E_INTERNAL", "no negotiation"); + const int kind = v.choice("kind"), percent = int(v.integer("percent")); + if (percent > bonus_max(kind)) fail("E_BAD_ARGUMENT", kBonuses[size_t(kind)] + " is at most " + std::to_string(bonus_max(kind))); + negotiation_->bonuses[size_t(kind)] = uint8_t(percent); + emit('+', kBonuses[size_t(kind)] + " = " + std::to_string(percent)); + }); + add({"Contracts.Negotiate", "MakeOffer", {}, "ANGEBOT MACHEN: the player decides", true}, + [this, contracts, dispatch_contract](const Values&) { + if (!negotiation_) fail("E_INTERNAL", "no negotiation"); + const Negotiation n = *negotiation_; + const auto r = app::ContractActions::offer(contracts(), n.row, n.player_id, n.quote_id, + n.bonuses, n.years, n.salary, n.demands, next_request_id_++); + const auto result = dispatch_contract(r); + negotiation_.reset(); + close_window(); + emit('+', std::string(result.accepted ? "accepted: " : "rejected: ") + result.feedback); + }); + + // --- Settings ------------------------------------------------------------------------- + auto settings = [this] { return ui::settings_from_game(session_->state(), active_slot(), revision_, exe_); }; + // A cell as the screen shows it (SettingsScreen::render): columns 1-7 are switches, the + // stored 1 is OFF, 0 is ON, 2 is an empty cell; column 8 shows raw/2, column 9 the raw + // value; values >= 200 are empty cells. Bits 6/7 mark a switch unavailable. + auto cell_text = [](const ui::SettingsState& s, int row, int column) -> std::string { + const uint8_t raw = s.display_cells ? (*s.display_cells)[size_t(row * 9 + column)] : s.cells[size_t(row * 9 + column)]; + if (column < 7) { + const uint8_t value = raw & 0x3f; + if (value == 2) return " "; + return std::string(value == 1 ? "off" : "on") + ((raw & 0xc0) ? "*" : ""); + } + if (raw >= 200) return " "; + return std::to_string(column == 8 ? raw / 2 : raw); // column 9 shows half the raw value (SettingsScreen) + }; + auto show_settings = [this, settings, cell_text] { + const ui::SettingsState s = settings(); + std::vector> rows; + for (int row = 0; row < 20; ++row) { + std::vector cells = {std::string(1, char('A' + row))}; + for (int column = 0; column < 9; ++column) cells.push_back(cell_text(s, row, column)); + rows.push_back(cells); + } + emit_table({"", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, rows); + emit('i', "* = not available in this game; keys A1 ... T9 (08-einstellungen 3)"); + }; + openers_[19] = [this, show_settings] { + open_window("Settings"); + show_settings(); + }; + add({"Settings", "ShowSettings", {detail::text("group", 0, true)}, "the switch field A1-T9", false}, [show_settings](const Values& v) { + if (v.has("group")) fail("E_ENGINE_GAP", "the named groups of 08-einstellungen 3 are not in the console yet; ShowSettings shows all"); + show_settings(); + }); + add({"Settings", "ShowSwitch", {detail::text("key")}, "one switch", false}, [this, settings, cell_text](const Values& v) { + const auto [row, column] = switch_key(v.text("key")); + emit('+', v.text("key") + " = " + cell_text(settings(), row, column)); + }); + auto edit = [this, settings](int row, int column, ui::SettingsEdit operation) { + const ui::SettingsState s = settings(); + std::string error; + require_engine(app::DeskSettingsActions(*session_).edit(s, row, column, operation, revision_, error), "settings", error); + }; + add({"Settings", "SetSwitch", {detail::text("key"), detail::text("value")}, "set a switch (on/off or a number)", true}, + [this, settings, cell_text, edit](const Values& v) { + const auto [row, column] = switch_key(v.text("key")); + Arg value; + value.text = v.text("value"); + if (column < 7) { + const auto on = to_bool(value); + if (!on) fail("E_BAD_ARGUMENT", "a switch is on or off"); + const std::string now = cell_text(settings(), row, column); + if (now == " ") fail("E_RULE", v.text("key") + " is an empty cell"); + if ((now.rfind("on", 0) == 0) != *on) edit(row, column, ui::SettingsEdit::toggle_binary); + } else { + const auto target = to_int(value); + if (!target) fail("E_BAD_ARGUMENT", "the value is a number"); + for (int step = 0; step < 200; ++step) { + const std::string now = cell_text(settings(), row, column); + if (now == " ") fail("E_RULE", v.text("key") + " is an empty cell"); + const int current = std::stoi(now); + if (current == *target) break; + edit(row, column, current < *target ? ui::SettingsEdit::increment : ui::SettingsEdit::decrement); + if (std::stoi(cell_text(settings(), row, column)) == current) fail("E_BAD_ARGUMENT", "the value cannot go further"); + } + } + emit('+', v.text("key") + " = " + cell_text(settings(), row, column)); + }); + add({"Settings", "IncreaseSwitch", {detail::text("key")}, "the plus field (columns 8, 9)", true}, [this, settings, cell_text, edit](const Values& v) { + const auto [row, column] = switch_key(v.text("key")); + if (column < 7) fail("E_BAD_ARGUMENT", "only columns 8 and 9 have values"); + edit(row, column, ui::SettingsEdit::increment); + emit('+', v.text("key") + " = " + cell_text(settings(), row, column)); + }); + add({"Settings", "DecreaseSwitch", {detail::text("key")}, "the minus field (columns 8, 9)", true}, [this, settings, cell_text, edit](const Values& v) { + const auto [row, column] = switch_key(v.text("key")); + if (column < 7) fail("E_BAD_ARGUMENT", "only columns 8 and 9 have values"); + edit(row, column, ui::SettingsEdit::decrement); + emit('+', v.text("key") + " = " + cell_text(settings(), row, column)); + }); + for (const char* name : {"LoadSettings", "SaveSettings", "ShowReadme"}) + add({"Settings", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + ": the .EIN files are not ported yet (C4)"); }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_reschedule.cpp b/src/cli/console/windows_reschedule.cpp new file mode 100644 index 0000000..87ff840 --- /dev/null +++ b/src/cli/console/windows_reschedule.cpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Moving own home league matches (menu 7, docs/CLI_CONCEPT/06-verein.md 13, H2 p. 52): list +// the matches that can be moved, the days each one can move to, move it and take a move back. +// +// The rules are the engine's (src/game/reschedule.hpp, a port of the calendar screen +// CalendarCell in mode 2): own home league matches in the future, not on the first or the +// last two matchdays; target days free of other matches and friendlies, outside the winter +// break; the Friday before the matchday only with floodlights. Dates are written like the +// other date commands (YYYY-MM-DD). + +#include + +#include "app/desktop_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/reschedule.hpp" +#include "ui/desk_state.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +void Console::register_reschedule_commands() { + auto manager = [this] { return active_slot(); }; + auto day_text = [this](int day) { + const ui::DeskDate date = ui::desk_date(session_->state().season_start + uint32_t(day), exe_); + return date_text(date.day, date.month, date.year); + }; + // the movable match on the date `text` + auto find_game = [this, manager, day_text](const std::string& text) { + for (const LeagueMatchRef& m : reschedulable_matches(session_->state(), manager())) + if (day_text(m.day) == text) return m; + fail("E_RULE", "no movable home league match on " + text + " (ListRescheduleGames)"); + }; + openers_[7] = [this] { + open_window("Reschedule"); + emit('+', "reschedule: ListRescheduleGames, ListRescheduleDates(game:date), MoveGame(game:date, to:date), ListMovedGames, UndoMove(game:date)"); + }; + add({"Reschedule", "ListRescheduleGames", {}, "own home league matches that can be moved", false}, + [this, manager, day_text](const Values&) { + const GameState& g = session_->state(); + std::vector> rows; + for (const LeagueMatchRef& m : reschedulable_matches(g, manager())) + rows.push_back({day_text(m.day), std::to_string(m.round + 1), utf8(g.club_name(m.away))}); + if (rows.empty()) emit('i', "no home league match can be moved"); + emit_table({"Date", "Matchday", "Opponent"}, rows); + }); + Param game = detail::text("game"); + game.display = "game:date"; + Param to = detail::text("to"); + to.display = "to:date"; + add({"Reschedule", "ListRescheduleDates", {game}, "the days the match can be moved to", false}, + [this, manager, day_text, find_game](const Values& v) { + const LeagueMatchRef m = find_game(v.text("game")); + std::vector> rows; + for (int day : reschedule_target_days(session_->state(), manager(), m)) rows.push_back({day_text(day), std::to_string(day)}); + if (rows.empty()) emit('i', "no free day for this match"); + emit_table({"Date", "SeasonDay"}, rows); + }); + add({"Reschedule", "ListMovedGames", {}, "moved matches that can still be taken back (new date)", false}, + [this, manager, day_text](const Values&) { + const GameState& g = session_->state(); + std::vector> rows; + for (const LeagueMatchRef& m : moved_matches(g, manager())) + rows.push_back({day_text(m.day), std::to_string(m.round + 1), utf8(g.club_name(m.home)), utf8(g.club_name(m.away))}); + if (rows.empty()) emit('i', "no moved match"); + emit_table({"Date", "Matchday", "Home", "Away"}, rows); + }); + add({"Reschedule", "UndoMove", {game}, "take a move back (game = the new date); the match is played on its matchday again", true}, + [this, manager, day_text](const Values& v) { + const GameState& g = session_->state(); + for (const LeagueMatchRef& m : moved_matches(g, manager())) { + if (day_text(m.day) != v.text("game")) continue; + app::RescheduleActions(*session_).undo_console(manager(), m.day, revision_); + emit('+', utf8(g.club_name(m.home)) + " - " + utf8(g.club_name(m.away)) + " back on matchday " + std::to_string(m.round + 1)); + return; + } + fail("E_RULE", "no moved match on " + v.text("game") + " (ListMovedGames)"); + }); + add({"Reschedule", "MoveGame", {game, to}, "move the match to a free day", true}, + [this, manager, day_text, find_game](const Values& v) { + const LeagueMatchRef m = find_game(v.text("game")); + int target = -1; + for (int day : reschedule_target_days(session_->state(), manager(), m)) + if (day_text(day) == v.text("to")) target = day; + if (target < 0) fail("E_RULE", v.text("to") + " is not free for this match (ListRescheduleDates)"); + switch (app::RescheduleActions(*session_).move(manager(), m, target, revision_)) { + case RescheduleStatus::moved: break; + case RescheduleStatus::no_free_slot: fail("E_RULE", "too many postponed matches this season"); + case RescheduleStatus::day_full: + case RescheduleStatus::team_clash: fail("E_RULE", "that day is already full of replays"); + default: fail("E_RULE", "the match cannot be moved"); + } + const GameState& g = session_->state(); + emit('+', utf8(g.club_name(m.home)) + " - " + utf8(g.club_name(m.away)) + " moved from " + day_text(m.day) + " to " + + day_text(target)); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_squad.cpp b/src/cli/console/windows_squad.cpp new file mode 100644 index 0000000..152547f --- /dev/null +++ b/src/cli/console/windows_squad.cpp @@ -0,0 +1,429 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The squad windows of docs/CLI_CONCEPT/06-verein.md 1: Lineup (menu 3) with Lineup.Pitch, +// the player card PlayerCard (+ PlayerCard.Statistics) and the club information TeamInfo. +// +// Opening the line-up is an engine step: the original arranges the eleven through the human +// path when the screen opens (PitchScreen -> Int2, CareerSession::dispatch_lineup +// prepare_lineup); the console does the same when Open(Lineup) runs, never on a read command. + +#include + +#include "app/window_actions.hpp" +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "ui/club_info.hpp" +#include "ui/lineup.hpp" +#include "game/lineup.hpp" +#include "ui/pitch.hpp" +#include "ui/player_card.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// TEXTD indices (docs/formats/textd_inventory.csv) +constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU +constexpr int kSkillNames = 135; // skillTeamplay, Speed, Shot, Pass, Tackling, FreeKick, Corner +constexpr int kRatings = 142; // ratingLousy, Fair, Good, Great + +// The squad slot flags: 0x8000 on the pitch (starting eleven), 0x4000 on the bench. +std::string slot_state(uint16_t slot) { return (slot & 0x8000) ? "pitch" : (slot & 0x4000) ? "bench" : "-"; } + +// Why a player cannot play: w364 bits 16-19 hold the remaining duration, bit 20 marks a ban +// instead of an injury (Absence). The SDL line-up shows the same as a red cross / card. +std::string absence(const Player& a) { + const int duration = int(a.w364 >> 16 & 0xF); + if (duration == 0) return "-"; + return std::string(a.w364 & 0x100000 ? "ban " : "injury ") + std::to_string(duration); +} + +} // namespace + +void Console::register_squad_commands() { + auto lineup = [this] { return prep().lineup; }; + auto refs_of = [](const ui::LineupState& l) { + std::vector refs; + for (const auto& p : l.players) + if (p.player_id >= 0) refs.push_back({p.row, p.player_id, utf8(p.name)}); + return refs; + }; + auto player_at = [refs_of](const ui::LineupState& l, const std::string& reference) -> ui::LineupPlayer { + const auto refs = refs_of(l); + const int row = refs[resolve_player(reference, refs)].row; + return l.players[size_t(row)]; + }; + // DATEN-A / DATEN-B as the line-up screen draws them (src/ui/lineup.cpp, headers ClubInfo_Render_TextPointer3 / ClubInfo_Render_TextPointer4): + // A = position, KO/TE/FO/strength and this season's games, goals, assists, yellow and red + // cards (w364 >> 26, w364 bits 2-7, w368 bits 18-23, 14-17, 24-26); B = age, the seven + // skills and the career numbers: internationals (bonus & 127), league and UEFA games (board + // +7, +9), total games, goals and assists (board words +0x48, +0x4a, +0x4c). + auto show_squad = [this, lineup] { + const ui::LineupState l = lineup(); + std::vector> rows; + for (const auto& p : l.players) { + if (p.player_id < 0) continue; + const auto& a = p.attributes; + std::vector row{"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name)}; + if (!squad_view_b_) { + for (std::string v : {text(kPositionNames + a.position()), std::to_string(a.condition()), std::to_string(a.technique()), + std::to_string(a.form()), std::to_string(a.strength()), std::to_string(a.age()), + std::to_string(a.w364 >> 26), std::to_string((a.w364 >> 2) & 63), + std::to_string((a.w368 >> 18) & 63), std::to_string((a.w368 >> 14) & 15), + std::to_string((a.w368 >> 24) & 7)}) + row.push_back(v); + } else { + row.push_back(std::to_string(a.age())); + std::string skills; + for (int i = 0; i < 7; ++i) skills += std::to_string(a.skill(Player::Skill(i))); + row.push_back(skills); + const auto word = [&](size_t at) { return std::to_string(p.board[at] | p.board[at + 1] << 8); }; + for (std::string v : {std::to_string(p.bonus & 127), std::to_string(p.board[7]), std::to_string(p.board[9]), + word(0x48), word(0x4a), word(0x4c)}) + row.push_back(v); + } + row.push_back(slot_state(p.slot)); + row.push_back(absence(a)); + rows.push_back(std::move(row)); + } + if (!squad_view_b_) + emit_table({"Row", "Id", "Player", "Pos", "K", "T", "F", "Str", "Age", "Gm", "Gls", "Ast", "YC", "RC", "Place", "Out"}, rows); + else + emit_table({"Row", "Id", "Player", "Age", "Skills(TSShPTaFkC 0-3)", "Int", "LgGm", "EuGm", "TotGm", "TotGls", "TotAst", + "Place", "Out"}, rows); + // The starting eleven are the first rows of the squad list; a sale or the injury swap + // moves the list up, so the reserve keeper can end up on the pitch (as in the + // original). Point it out instead of leaving it to the match. + int keepers = 0; + for (const auto& p : l.players) + if (p.player_id >= 0 && (p.slot & 0x8000) && p.attributes.position() == 0) ++keepers; + if (keepers != 1) emit('i', "warning: " + std::to_string(keepers) + " goalkeepers on the pitch"); + }; + + // --- Lineup (06-verein 1) ------------------------------------------------------------- + openers_[3] = [this, lineup, show_squad] { + const ui::LineupState l = lineup(); + if (!l.entry_prepared) { + const auto r = app::LineupActions::prepare(l); + std::string error; + require_engine(app::LineupActions(*session_).lineup(r, revision_, error), "line-up", error); + } + open_window("Lineup"); + show_squad(); + }; + add({"Lineup", "ShowSquad", {choice("view", {"A", "B"}, true)}, "the squad: values, strength, place", false}, + [show_squad](const Values&) { show_squad(); }); + add({"Lineup", "SetSquadView", {choice("view", {"A", "B"})}, "DATEN-A / DATEN-B", false}, [this, show_squad](const Values& v) { + squad_view_b_ = v.choice("view") == 1; + show_squad(); + }); + Param first = detail::text("first"), second = detail::text("second"); + first.display = "first:Player"; + second.display = "second:Player"; + // A click on one row and then on another exchanges the two places (bench, pitch, stands). + auto swap = [this, lineup, player_at, show_squad](const std::string& a, const std::string& b) { + const ui::LineupState l = lineup(); + const auto& p = player_at(l, a); + const auto& q = player_at(l, b); + if (p.row == q.row) fail("E_BAD_ARGUMENT", "two different players are needed"); + const auto r = app::LineupActions::swap(l, p, q); + std::string error; + require_engine(app::LineupActions(*session_).lineup(r, revision_, error), "line-up", error); + emit('+', utf8(p.name) + " <-> " + utf8(q.name)); + show_squad(); + }; + add({"Lineup", "SwapPlayers", {first, second}, "exchange two players' places", true}, + [swap](const Values& v) { swap(v.text("first"), v.text("second")); }); + Param player = detail::text("player"); + player.display = "player:Player"; + add({"Lineup", "OpenPlayer", {player}, "the player card (PlayerCard)", false}, [this, lineup, player_at](const Values& v) { + const auto& p = player_at(lineup(), v.text("player")); + card_row_ = p.row; + open_window("PlayerCard"); + show_player_card(); + }); + for (const char* name : {"OpenTeamList", "ShowForeigners"}) + add({"Lineup", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " has no projection yet"); }); + + // --- Lineup.Pitch --------------------------------------------------------------------- + add({"Lineup.Pitch", "ShowPitch", {}, "the eleven with depth/lane, formations, automatic weights", false}, + [this](const Values&) { show_pitch(); }); + add({"Lineup.Pitch", "SwapPitch", {first, second}, "exchange two players on the pitch / bench", true}, + [this, player_at](const Values& v) { + const auto projection = prep(); + if (!projection.pitch || !projection.pitch->indoor.has_value()) + fail("E_ENGINE_GAP", "no pitch mode projection"); + const ui::LineupState& l = projection.lineup; + const auto& p = player_at(l, v.text("first")); + const auto& q = player_at(l, v.text("second")); + if (p.row == q.row) fail("E_BAD_ARGUMENT", "two different players are needed"); + const auto r = app::LineupActions::swap_pitch(projection, p, q); + std::string error; + require_engine(app::LineupActions(*session_).pitch_swap(r, revision_, error), "pitch", error); + emit('+', utf8(p.name) + " <-> " + utf8(q.name)); + }); + // Moving a player, the formations and the automatic weights: the requests the SDL pitch + // screen builds (src/ui/pitch.cpp click / save_formation), dispatched through + // CareerSession::dispatch_pitch (PitchScreen pitch branch, Codex's source port). + auto pitch_context = [this] { + const auto p = prep(); + if (!p.pitch || !p.pitch->indoor.has_value()) fail("E_ENGINE_GAP", "no pitch mode projection"); + if (!p.lineup.entry_prepared) fail("E_RULE", "the line-up entry has not been prepared"); + return p; + }; + auto send_pitch = [this](const ui::PitchRequest& r) { + std::string error; + require_engine(app::LineupActions(*session_).pitch(r, revision_, error), "pitch", error); + }; + auto team_page_request = [this] { + const auto p=prep(); + if(!p.pitch||!p.pitch->indoor.has_value()||!p.lineup.entry_prepared) + fail("E_ENGINE_GAP","no prepared Source pitch projection"); + return app::LineupActions::page(p); + }; + add({"Lineup", "OpenPitch", {}, "the pitch (Lineup.Pitch)", false}, [this, team_page_request, send_pitch](const Values&) { + send_pitch(team_page_request()); + open_window("Lineup.Pitch"); + show_pitch(); + }); + closers_["Lineup.Pitch"]=[this,team_page_request,send_pitch,show_squad] { + send_pitch(team_page_request()); + close_window(); + show_squad(); + }; + add({"Lineup.Pitch", "SetFormation", {integer("slot", 1, 8)}, "one of the eight formations (1-4 given, 5-8 own); the automatic line-up takes over", true}, + [this, pitch_context, send_pitch](const Values& v) { + const int f = int(v.integer("slot")) - 1; + if (!(prep().pitch->formation_mask & (1 << f))) fail("E_RULE", "formation slot " + std::to_string(f + 1) + " is empty"); + const auto r = app::LineupActions::formation(pitch_context(), ui::PitchRequestKind::apply_formation, f); + send_pitch(r); + show_pitch(); + }); + add({"Lineup.Pitch", "SaveFormation", {integer("slot", 5, 8)}, "save the current positions in an own formation slot (long press)", true}, + [this, pitch_context, send_pitch](const Values& v) { + const auto p = pitch_context(); + for (int row = 0; row < 11; ++row) { + const auto& pl = p.lineup.players.at(size_t(row)); + if (pl.player_id < 0 || !(pl.slot & 0x8000)) fail("E_RULE", "saving a formation needs eleven nominated starters"); + } + const auto r = app::LineupActions::formation(p, ui::PitchRequestKind::save_formation, int(v.integer("slot")) - 1); + send_pitch(r); + emit('+', "formation " + std::to_string(r.formation + 1) + " saved"); + }); + add({"Lineup.Pitch", "MovePlayer", {first, integer("depth", 0, 19), integer("lane", 0, 8)}, + "place a starter freely (switches the automatic line-up off)", true}, + [this, lineup, player_at, pitch_context, send_pitch](const Values& v) { + const ui::LineupState l = lineup(); + const auto& p = player_at(l, v.text("first")); + if (p.row >= 11 || !(p.slot & 0x8000)) fail("E_RULE", "only a starter can be placed"); + const auto r = app::LineupActions::move(pitch_context(), p, int(v.integer("depth")), int(v.integer("lane"))); + send_pitch(r); + show_pitch(); + }); + add({"Lineup.Pitch", "SetAutoWeights", {choice("kind", {"Position", "SideAndRole", "Fatigue"}), integer("value", 0, 3)}, + "an automatic line-up weight (the cup is clicked until the value); then SetFormation again", true}, + [this, pitch_context, send_pitch](const Values& v) { + if (desk().options.mode == 1) fail("E_MODE_LOCKED", "no automatic weights in mode I"); + const int index = v.choice("kind"), shift = 2 * index, want = int(v.integer("value")); + for (int guard = 0; guard < 4 && ((prep().pitch->automatic_weights >> shift) & 3) != want; ++guard) { + const auto r = app::LineupActions::weight(pitch_context(), index); + send_pitch(r); + } + emit('+', std::string("weight ") + v.text("kind") + " = " + std::to_string((prep().pitch->automatic_weights >> shift) & 3)); + }); + add({"Lineup.Pitch", "ShowAutoWeights", {}, "the three automatic line-up weights", false}, [this](const Values&) { + const auto p = prep(); + if (!p.pitch) fail("E_ENGINE_GAP", "no pitch projection"); + const char* names[3] = {"Position", "SideAndRole", "Fatigue"}; + std::vector> rows; + for (int i = 0; i < 3; ++i) rows.push_back({names[i], std::to_string((p.pitch->automatic_weights >> (2 * i)) & 3)}); + emit_table({"Weight", "Value"}, rows); + }); + add({"Lineup.Pitch", "SetSquadView", {choice("view", {"A", "B"})}, "DATEN-A / DATEN-B", false}, [this](const Values&) { show_pitch(); }); + // --- Lineup.Order: ORDER (06-verein 1.5): the four instructions of each starter ---------- + auto show_orders = [this, lineup] { + const ui::LineupState l = lineup(); + static const char* const kHead[5] = {"Row", "Player", "Offense", "Running", "Commitment"}; + std::vector> rows; + for (const auto& pl : l.players) { + if (pl.player_id < 0 || !(pl.slot & 0x8000)) continue; + rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), std::to_string(pl.board[2]), std::to_string(pl.board[3]), + std::to_string(pl.board[4]), std::to_string(pl.board[5])}); + } + emit_table({kHead[0], kHead[1], kHead[2], kHead[3], kHead[4], "Fighting"}, rows); + emit('i', "values " + std::to_string(kOrderMin) + ".." + std::to_string(kOrderMax)); + }; + add({"Lineup.Pitch", "OpenOrder", {}, "ORDER: the instructions of the starters (Lineup.Order)", false}, [this, show_orders](const Values&) { + open_window("Lineup.Order"); + show_orders(); + }); + add({"Lineup.Order", "ShowOrders", {}, "offense, running, commitment, fighting of every starter", false}, + [show_orders](const Values&) { show_orders(); }); + add({"Lineup.Order", "SetOrder", {first, choice("aspect", {"Offense", "Run", "Commitment", "Fighting"}), integer("value", kOrderMin, kOrderMax)}, + "one instruction of a starter (as a click in its bar)", true}, + [this, lineup, player_at, show_orders](const Values& v) { + const ui::LineupState l = lineup(); + const auto& p = player_at(l, v.text("first")); + if (!app::LineupActions(*session_).order(l, p, v.choice("aspect"), int(v.integer("value")), revision_)) + fail("E_RULE", "only a starter on the pitch gets instructions"); + show_orders(); + }); + add({"Lineup.Pitch", "ShowPairs", {}, "the Hall partners stored on the tactics board", false}, + [this](const Values&) { show_pairs(); }); + add({"Lineup.Pitch", "PairPlayers", {first, second, integer("depth", 0, 19), integer("lane", 0, 8)}, + "place the first Hall starter beside the second at the explicit target coordinates", true}, + [this, player_at, pitch_context, send_pitch](const Values& v) { + const auto projection = prep(); + if (!projection.pitch || projection.pitch->indoor != std::optional(true)) + fail("E_RULE", "pairs are only available for a Hall match"); + const auto first_player = player_at(projection.lineup, v.text("first")); + const auto second_player = player_at(projection.lineup, v.text("second")); + if (first_player.row == second_player.row) + fail("E_BAD_ARGUMENT", "two different players are needed"); + if (first_player.row >= 11 || second_player.row >= 11 || + !(first_player.slot & 0x8000) || !(second_player.slot & 0x8000)) + fail("E_RULE", "only two nominated Hall starters can form a pair"); + const auto r = app::LineupActions::move(pitch_context(), first_player, + int(v.integer("depth")), int(v.integer("lane"))); + const auto target = app::LineupActions(*session_).pair_target(r, second_player.row); + if (target == app::LineupActions::PairTarget::invalid) + fail("E_RULE", "the target is not a valid Hall placement"); + if (target != app::LineupActions::PairTarget::requested) + fail("E_RULE", "the target must form the requested pair; use a free place beside the second player"); + send_pitch(r); + show_pairs(); + }); + for (const char* name : {"OpenTeamList", "OpenMarking", "ShowZoneCoverage", "OpenSetPieces"}) + add({"Lineup.Pitch", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " has no projection/request yet"); }); + + // --- PlayerCard (06-verein 1.6) ------------------------------------------------------- + add({"PlayerCard", "ShowPlayer", {detail::text("player", 0, true)}, "the card (another player of the squad by name)", false}, + [this, lineup, player_at](const Values& v) { + if (v.has("player")) card_row_ = player_at(lineup(), v.text("player")).row; + show_player_card(); + }); + add({"PlayerCard", "OpenPlayer", {player}, "another player's card", false}, [this, lineup, player_at](const Values& v) { + card_row_ = player_at(lineup(), v.text("player")).row; + show_player_card(); + }); + add({"PlayerCard", "OpenPlayerStatistics", {}, "the development charts (own players)", false}, [this](const Values&) { + open_window("PlayerCard.Statistics"); + show_player_statistics(0, true); + }); + for (const char* name : {"Negotiate", "NationalSquadAdd", "NationalSquadRemove"}) + add({"PlayerCard", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " comes with the transfer offers (stage 3b)"); }); + const std::vector charts = {"Value", "Form", "Strength", "Total"}; + add({"PlayerCard.Statistics", "ShowPlayerStatistics", {choice("chart", charts, true), choice("mode", {"Absolute", "Relative"}, true)}, + "a development chart as a series", false}, + [this](const Values& v) { + if (v.has("chart")) chart_ = v.choice("chart"); + if (v.has("mode")) chart_absolute_ = v.choice("mode") == 0; + show_player_statistics(chart_, chart_absolute_); + }); + add({"PlayerCard.Statistics", "SetChart", {choice("chart", charts)}, "SPIELER-WERT / FORM / STÄRKE / GESAMT", false}, [this](const Values& v) { + chart_ = v.choice("chart"); + show_player_statistics(chart_, chart_absolute_); + }); + add({"PlayerCard.Statistics", "SetMode", {choice("mode", {"Absolute", "Relative"})}, "ABS / REL", false}, [this](const Values& v) { + chart_absolute_ = v.choice("mode") == 0; + show_player_statistics(chart_, chart_absolute_); + }); + add({"PlayerCard.Statistics", "BackToPlayerInfo", {}, "back to the card", false}, [this](const Values&) { + close_window(); + show_player_card(); + }); +} + +void Console::show_player_card() { + const auto p = prep(); + if (card_row_ < 0 || size_t(card_row_) >= p.player_cards.size()) fail("E_INTERNAL", "no such player card"); + const ui::PlayerCardState& card = p.player_cards[size_t(card_row_)]; + const auto& player = card.lineup.players.at(size_t(card.row)); + const auto& a = player.attributes; + const auto le32 = [&](size_t at) { + return uint32_t(player.board[at]) | uint32_t(player.board[at + 1]) << 8 | uint32_t(player.board[at + 2]) << 16 | + uint32_t(player.board[at + 3]) << 24; + }; + const auto value = ui::player_card_market_value(a, exe_); + emit_table({"Card", "Value"}, + {{"name", utf8(player.name)}, + {"id", "id:" + std::to_string(player.player_id)}, + {"age", std::to_string(a.age())}, + {"nationality", utf8(card.nationality_name)}, + {"position", text(kPositionNames + a.position())}, + {"place", slot_state(player.slot)}, + {"out", absence(a)}, + {"condition/technique/form", std::to_string(a.condition()) + "/" + std::to_string(a.technique()) + "/" + std::to_string(a.form())}, + {"strength", std::to_string(a.strength())}, + {"contractMonths", player.board[0xc] == 255 ? "-" : std::to_string(player.board[0xc])}, + {"salary", money(le32(0x50))}, + {"purchasePrice", le32(0x54) ? money(le32(0x54)) : "-"}, + {"marketValue", value ? money(*value) : "?"}, + {"monthsAtClub", std::to_string(player.board[0x11] + 1)}}); // "Seit N Monaten im Verein" (ClubPlayerDetail_RenderCard_ExecutableField..ClubPlayerDetail_RenderCard_ExecutableField4) + std::vector> skills; + for (int i = 0; i < 7; ++i) skills.push_back({text(kSkillNames + i), text(kRatings + a.skill(Player::Skill(i)))}); + emit_table({"Skill", "Rating"}, skills); + if (!card.unsupported_record.empty()) emit('i', "not shown: " + card.unsupported_record); +} + +void Console::show_player_statistics(int chart, bool absolute) { + const auto p = prep(); + if (card_row_ < 0 || size_t(card_row_) >= p.player_cards.size()) fail("E_INTERNAL", "no such player card"); + const ui::PlayerCardState& card = p.player_cards[size_t(card_row_)]; + if (!card.statistics) fail("E_RULE", "statistics only for own players"); + const auto points = ui::player_statistics_points(card, exe_, chart, absolute); + const char* names[4] = {"Value", "Form", "Strength", "Total"}; + std::string series; + for (const auto& [month, v] : points) series += (series.empty() ? "" : " ") + std::to_string(month) + ":" + std::to_string(v); + emit('i', std::string(names[chart]) + (absolute ? " (absolute)" : " (relative)") + ": " + (series.empty() ? "-" : series)); +} + +void Console::show_pairs() { + const auto p = prep(); + if (!p.pitch || p.pitch->indoor != std::optional(true)) + fail("E_RULE", "pairs are only available for a Hall match"); + std::vector> rows; + int pairs = 0; + for (const auto& pl : p.lineup.players) { + if (pl.row >= 11 || pl.player_id < 0 || !(pl.slot & 0x8000)) continue; + const size_t partner = pl.board[0x3f]; + std::string partner_row = "-", partner_name = "-"; + if (partner < 11 && partner != size_t(pl.row) && partner < p.lineup.players.size()) { + const auto& other = p.lineup.players[partner]; + if (other.player_id >= 0 && (other.slot & 0x8000) && other.board[0x3f] == pl.row) { + partner_row = "row:" + std::to_string(other.row); + partner_name = utf8(other.name); + if (pl.row < other.row) ++pairs; + } + } + rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), partner_row, partner_name}); + } + emit_table({"Row", "Player", "PartnerRow", "Partner"}, rows); + emit('i', "Hall pairs: " + std::to_string(pairs)); +} + +void Console::show_pitch() { + const auto p = prep(); + std::vector> rows; + for (const auto& pl : p.lineup.players) { + if (pl.player_id < 0 || !(pl.slot & 0xc000)) continue; + rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), slot_state(pl.slot), + (pl.slot & 0x8000) ? std::to_string(int8_t(pl.board[0x41])) : "-", + (pl.slot & 0x8000) ? std::to_string(int8_t(pl.board[0x42])) : "-"}); + } + emit_table({"Row", "Player", "Place", "Depth", "Lane"}, rows); + if (p.pitch) { + std::string saved; + for (int f = 0; f < 8; ++f) + if (p.pitch->formation_mask & (1 << f)) saved += (saved.empty() ? "" : " ") + std::to_string(f + 1); + emit('i', "formations available: " + (saved.empty() ? std::string("-") : saved) + "; automatic formation " + + std::to_string(p.lineup.automatic_formation)); + if (p.pitch->indoor == std::optional(true)) show_pairs(); + } +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_start.cpp b/src/cli/console/windows_start.cpp new file mode 100644 index 0000000..bb4d77e --- /dev/null +++ b/src/cli/console/windows_start.cpp @@ -0,0 +1,517 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The start of a game (docs/CLI_CONCEPT/03-start.md): the options screen NewGame, the manager +// selection NewGame.Select with its confirmation, the info sequence after the last manager, +// and the file windows (load browser at the start, LoadGame/SaveGame on the desk, 04-schreibtisch 8). + +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "ui/cup_draw.hpp" +#include "ui/desk_state.hpp" +#include "ui/season_entrants.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// TEXTD indices (docs/formats/textd_inventory.csv) +constexpr int kStrengthBottomThird = 18; // strengthBottomThird "unteres Drittel" +constexpr int kErrorNotAGameScore = 814; // "Dies ist kein BUNDESLIGA MANAGER Hattrick - Spielstand!" +constexpr int kSaveConfirmOverwrite = 854; // "Möchten Sie diese Datei wirklich überschreiben?" +constexpr int kManagerConfirmAllDetailsCorrect = 907; // "Sind alle Angaben richtig?" + +// The picker tabs as the console names them (03-start 3); index = ManagerScreen group. +const std::vector kTabs = {"Bundesliga", "SecondLeague", "RegionalA", "RegionalB", + "Oberliga", "AdditionalA", "AdditionalB"}; +const std::vector kStartLeagues = {"Bundesliga", "SecondLeague", "RegionalA", "RegionalB", "Oberliga"}; +// ManagerChoice::strength: 0 lower, 1 middle, 2 upper third +const std::vector kStrengths = {"Lower", "Middle", "Upper"}; + +} // namespace + +void Console::register_start_commands() { + // --- NewGame: the options screen (03-start 1) ----------------------------------------- + add({"NewGame", "ShowOptions", {}, "show the options with their current values", false}, [this](const Values&) { + emit_table({"Option", "Value"}, + {{"duration", setup_.duration == 5 ? "endless" : std::to_string(setup_.duration)}, + {"difficulty", std::to_string(setup_.difficulty + 1)}, + {"managers", std::to_string(setup_.managers)}, + {"mode", std::to_string(setup_.mode)}, + {"league", on_off(setup_.league)}, + {"world", on_off(setup_.world)}}); + }); + add({"NewGame", "NewGame", + {integer("duration", 1, 5), integer("difficulty", 1, 10), integer("managers", 1, 4), integer("mode", 1, 3), + boolean("league"), boolean("world")}, + "set all options and continue (= right mouse)", true}, + [this](const Values& v) { + if (!v.boolean("league") && !v.boolean("world")) + fail("E_BAD_ARGUMENT", "league and world mode cannot both be off"); + setup_.duration = int(v.integer("duration")); + setup_.difficulty = int(v.integer("difficulty")) - 1; // shown 1-10, stored 0-9 + setup_.managers = int(v.integer("managers")); + setup_.mode = int(v.integer("mode")); + setup_.league = v.boolean("league"); + setup_.world = v.boolean("world"); + new_game_continue(); + }); + add({"NewGame", "SetDuration", {integer("duration", 1, 5)}, "1-4 seasons, 5 = endless", true}, + [this](const Values& v) { setup_.duration = int(v.integer("duration")); emit('+', "duration set"); }); + add({"NewGame", "SetDifficulty", {integer("difficulty", 1, 10)}, "number of balls", true}, + [this](const Values& v) { setup_.difficulty = int(v.integer("difficulty")) - 1; emit('+', "difficulty set"); }); + add({"NewGame", "SetManagers", {integer("managers", 1, 4)}, "human managers", true}, + [this](const Values& v) { setup_.managers = int(v.integer("managers")); emit('+', "managers set"); }); + add({"NewGame", "SetMode", {integer("mode", 1, 3)}, "range of desk functions", true}, + [this](const Values& v) { setup_.mode = int(v.integer("mode")); emit('+', "mode set"); }); + add({"NewGame", "SetLeagueMode", {boolean("on")}, "league mode on/off", true}, [this](const Values& v) { + if (!v.boolean("on") && !setup_.world) fail("E_RULE", "league and world mode cannot both be off"); + setup_.league = v.boolean("on"); + emit('+', "league mode " + on_off(setup_.league)); + }); + add({"NewGame", "SetWorldMode", {boolean("on")}, "world cup mode on/off", true}, [this](const Values& v) { + if (!v.boolean("on") && !setup_.league) fail("E_RULE", "league and world mode cannot both be off"); + setup_.world = v.boolean("on"); + emit('+', "world mode " + on_off(setup_.world)); + }); + add({"NewGame", "OpenLoadBrowser", {}, "open the load browser", false}, + [this](const Values&) { + browse_directory_ = std::filesystem::absolute(save_directory()).lexically_normal(); + selected_file_.clear(); + set_window("NewGame.LoadGame", 1); + }); + add({"NewGame", "LoadGame", {detail::text("filename")}, "load a saved game", true}, [this](const Values& v) { + std::filesystem::path path(v.text("filename")); + if (path.is_relative()) path = save_directory() / path; + load_game(path); + }); + + // --- NewGame.Select: who plays? (03-start 3) ------------------------------------------ + Param tab = detail::text("league", 0, true); + tab.display = "[league:int|tab:enum]"; + add({"NewGame.Select", "ListTeams", {tab}, "clubs of a picker tab (Bundesliga ... AdditionalB)", false}, + [this](const Values& v) { + int group = -1; + if (v.has("league")) { + Arg a; + a.text = v.text("league"); + for (size_t i = 0; i < kTabs.size(); ++i) + if (canonical(kTabs[i]) == canonical(a.text)) group = int(i); + if (group < 0) + if (const auto n = to_int(a); n && *n >= 0 && *n < ui::ManagerScreen::group_count) group = int(*n); + if (group < 0) fail("E_BAD_ARGUMENT", "league must be 0..6 or one of Bundesliga, SecondLeague, RegionalA, " + "RegionalB, Oberliga, AdditionalA, AdditionalB"); + } else { + for (int g = 0; g < ui::ManagerScreen::group_count; ++g) + if (draft_.selection_club >= picker_->group_first(g) && draft_.selection_club <= picker_->group_last(g)) group = g; + if (group < 0) group = 0; + } + const std::string label = utf8(picker_->group_label(group)); + emit('i', canonical(label) == canonical(kTabs[size_t(group)]) ? label : kTabs[size_t(group)] + ": " + label); + std::vector> rows; + for (int sel = picker_->group_first(group); sel <= picker_->group_last(group); ++sel) { + const int master = picker_->master_of(sel); + std::string taken = "-"; + for (const auto& c : confirmed_) + if (c.master_club == master) taken = "P" + std::to_string(c.slot + 1); + std::string name = utf8(picker_->club_name(master)); + if (master == draft_.master_club) name += " [selected]"; + rows.push_back({"club:" + std::to_string(master), name, taken}); + } + emit_table({"Club", "Name", "Taken"}, rows); + }); + add({"NewGame.Select", "ListPortraits", {}, "the twelve portraits and who took them", false}, [this](const Values&) { + std::vector> rows; + for (int p = 0; p < 12; ++p) { + std::string taken = "-"; + for (const auto& c : confirmed_) + if (c.portrait == p) taken = "P" + std::to_string(c.slot + 1); + rows.push_back({std::to_string(p), taken + (p == draft_.portrait ? " [selected]" : "")}); + } + emit_table({"Portrait", "Taken"}, rows); + }); + add({"NewGame.Select", "ListStrengths", {}, "the three club strengths", false}, [this](const Values&) { + std::vector> rows; + for (int s = 2; s >= 0; --s) rows.push_back({kStrengths[size_t(s)], text(kStrengthBottomThird + s)}); + emit_table({"Strength", "Text"}, rows); + }); + add({"NewGame.Select", "ShowSelection", {}, "the choices of this player", false}, [this](const Values&) { + emit_table({"Field", "Value"}, + {{"managerName", utf8(draft_.name)}, + {"club", "club:" + std::to_string(draft_.master_club) + " " + utf8(picker_->club_name(draft_.master_club))}, + {"startLeague", kStartLeagues[size_t(draft_.start_league)]}, + {"strength", kStrengths[size_t(draft_.strength)]}, + {"portrait", std::to_string(draft_.portrait)}}); + }); + + // The single choices; SelectTeam sets all five and confirms. Each check happens before + // anything changes, so a failed SelectTeam leaves the draft as it was. + auto set_name = [this](ui::ManagerChoice& c, const std::string& utf8) { + if (utf8.empty()) fail("E_BAD_ARGUMENT", "the name must not be empty"); + std::string original; + try { + original = ui::utf8_to_original(utf8); + } catch (const std::exception&) { + fail("E_BAD_ARGUMENT", "the name has a character the game cannot show"); + } + if (original.size() > 20) fail("E_BAD_ARGUMENT", "the name has more than 20 characters"); + c.name = original; + }; + auto set_club = [this](ui::ManagerChoice& c, const std::string& reference) { + const int master = resolve_club(reference); + for (const auto& other : confirmed_) + if (other.master_club == master) + fail("E_RULE", "the club is taken by player " + std::to_string(other.slot + 1)); + for (int sel = 0; sel <= picker_->group_last(ui::ManagerScreen::group_count - 1); ++sel) + if (picker_->master_of(sel) == master) { + c.selection_club = sel; + c.master_club = master; + return; + } + fail("E_BAD_ARGUMENT", "the club cannot be chosen"); + }; + auto set_portrait = [this](ui::ManagerChoice& c, int portrait) { + for (const auto& other : confirmed_) + if (other.portrait == portrait) fail("E_RULE", "the portrait is taken by player " + std::to_string(other.slot + 1)); + c.portrait = portrait; + }; + add({"NewGame.Select", "SetManagerName", {detail::text("name", 0)}, "the manager's name (1-20 characters)", true}, + [this, set_name](const Values& v) { set_name(draft_, v.text("name")); emit('+', "name: " + utf8(draft_.name)); }); + Param club = detail::text("club"); + club.display = "club:Club"; + add({"NewGame.Select", "SetClub", {club}, "the club: club: from ListTeams or \"name\"", true}, + [this, set_club](const Values& v) { + set_club(draft_, v.text("club")); + emit('+', "club: " + utf8(picker_->club_name(draft_.master_club))); + }); + add({"NewGame.Select", "SetStartLeague", {choice("league", kStartLeagues)}, "the league to start in", true}, + [this](const Values& v) { draft_.start_league = v.choice("league"); emit('+', "start league: " + kStartLeagues[size_t(draft_.start_league)]); }); + add({"NewGame.Select", "SetStrength", {choice("strength", {"Upper", "Middle", "Lower"})}, "the club's strength", true}, + [this](const Values& v) { draft_.strength = 2 - v.choice("strength"); emit('+', "strength: " + kStrengths[size_t(draft_.strength)]); }); + add({"NewGame.Select", "SetPortrait", {integer("portrait", 0, 11)}, "the manager's portrait", true}, + [this, set_portrait](const Values& v) { set_portrait(draft_, int(v.integer("portrait"))); emit('+', "portrait: " + std::to_string(draft_.portrait)); }); + add({"NewGame.Select", "SelectTeam", + {detail::text("managerName"), club, choice("startLeague", kStartLeagues), choice("strength", {"Upper", "Middle", "Lower"}), + integer("portrait", 0, 11)}, + "set all five and ask for confirmation", true}, + [this, set_name, set_club, set_portrait](const Values& v) { + ui::ManagerChoice c = draft_; + set_name(c, v.text("managerName")); + set_club(c, v.text("club")); + c.start_league = v.choice("startLeague"); + c.strength = 2 - v.choice("strength"); + set_portrait(c, int(v.integer("portrait"))); + draft_ = c; + confirm_selection(); + }); + add({"NewGame.Select", "Confirm", {}, "show the summary and ask \"all details correct?\"", true}, + [this](const Values&) { confirm_selection(); }); + add({"NewGame.Select.Confirm", "ShowSummary", {}, "the choices of this player", false}, [this](const Values&) { + emit_table({"Field", "Value"}, + {{"managerName", utf8(draft_.name)}, + {"club", utf8(picker_->club_name(draft_.master_club))}, + {"startLeague", utf8(picker_->group_label(draft_.start_league))}, + {"strength", text(kStrengthBottomThird + draft_.strength)}, + {"portrait", std::to_string(draft_.portrait)}}); + }); +} + +// --------------------------------------------------------------------------------------- +// start flow + +std::string Console::options_text() const { + return "duration=" + (setup_.duration == 5 ? std::string("endless") : std::to_string(setup_.duration)) + + " difficulty=" + std::to_string(setup_.difficulty + 1) + " managers=" + std::to_string(setup_.managers) + + " mode=" + std::to_string(setup_.mode) + " league=" + on_off(setup_.league) + " world=" + on_off(setup_.world); +} + +void Console::new_game_continue() { + // The options are taken over with the first manager (CareerSession::confirm_manager). + set_window("NewGame.Select", 1); + emit('+', "Options set: " + options_text()); + begin_selection(0); +} + +// The manager dialog for `slot`: the original picker model gives the tab ranges and the +// defaults (name "Manager n", the first free club and portrait). The club order comes from +// the engine: confirming a manager can move clubs between leagues (ConfirmManager). +void Console::begin_selection(int slot) { + picker_ = std::make_unique(options_.data, slot, confirmed_, session_->selection_context(revision_)); + draft_ = picker_->choice(); +} + +// A club reference (01-grundlagen 1.3): club: / (master index) or a name. Names +// compare without case (also Ä/Ö/Ü); an exact name wins, otherwise a unique part of a name +// is enough ("Bayern"). +int Console::resolve_club(const std::string& reference) const { + std::string number = reference; + if (lower(number).rfind("club:", 0) == 0) number = number.substr(5); + Arg n; + n.text = number; + const int last = picker_->group_last(ui::ManagerScreen::group_count - 1); + if (const auto id = to_int(n)) { + for (int sel = 0; sel <= last; ++sel) + if (picker_->master_of(sel) == *id) return int(*id); + fail("E_BAD_ARGUMENT", "no club " + reference + " in the selection (see ListTeams)"); + } + const std::string wanted = fold(reference); + std::vector exact, partial; + for (int sel = 0; sel <= last; ++sel) { + const int master = picker_->master_of(sel); + const std::string name = fold(utf8(picker_->club_name(master))); + if (name == wanted) exact.push_back(master); + else if (name.find(wanted) != std::string::npos) partial.push_back(master); + } + const auto& found = exact.empty() ? partial : exact; + if (found.size() == 1) return found.front(); + if (found.empty()) fail("E_BAD_ARGUMENT", "no club named \"" + reference + "\" (see ListTeams)"); + std::string candidates; + for (size_t i = 0; i < found.size() && i < 8; ++i) + candidates += (i ? ", " : "") + utf8(picker_->club_name(found[i])) + " = club:" + std::to_string(found[i]); + fail("E_AMBIGUOUS", "\"" + reference + "\" fits several clubs: " + candidates); +} + +void Console::confirm_selection() { + // PresentManagerDialog: the summary and "Sind alle Angaben richtig?"; No = back to the same + // player's selection, everything can be changed (H2 S. 15). + open_window("NewGame.Select.Confirm"); + emit_table({"Field", "Value"}, + {{"managerName", utf8(draft_.name)}, + {"club", utf8(picker_->club_name(draft_.master_club))}, + {"startLeague", utf8(picker_->group_label(draft_.start_league))}, + {"strength", text(kStrengthBottomThird + draft_.strength)}, + {"portrait", std::to_string(draft_.portrait)}}); + ask(text(kManagerConfirmAllDetailsCorrect), {"Yes", "No"}, "No", [this](const std::string& answer) { + close_window(); + if (answer != "Yes") { + emit('+', "selection not confirmed"); + return; + } + std::string error; + if (!session_->confirm_manager(setup_, draft_, error)) + fail("E_RULE", "the engine rejects the manager: " + error); + confirmed_.push_back(draft_); + emit('+', "Manager " + std::to_string(confirmed_.size()) + " confirmed: " + utf8(draft_.name) + ", " + + utf8(picker_->club_name(draft_.master_club))); + if (int(confirmed_.size()) < setup_.managers) { + set_window("NewGame.Select", int(confirmed_.size()) + 1); + begin_selection(int(confirmed_.size())); + return; + } + finish_career(); + }); +} + +// After the last manager: the start values, the first season up to the first desk +// (CareerSession::finish), and the info windows of the intermediate sequence (03-start 4). +void Console::finish_career() { + ui::CareerInitializationResult init; + std::string error; + if (!session_->finish(init, error)) fail("E_INTERNAL", "the career cannot start: " + error); + career_ = true; + revision_ = init.desktop.revision; + picker_.reset(); + // the entrants and cup draws of the intermediate sequence came through the hooks + flush_info(); + enter_desktop(); +} + +// Installed on the session: the cup draws the engine makes inside finish() and kickoffs +// (CupDrawFromGame / Getenv). They are projected while the hook runs - the state moves +// on afterwards - and printed when the engine call returns (Info.CupDraw, 02-fenster 2). +// The projection is the SDL app's; it reads the state and draws no random numbers. +void Console::install_hooks() { + // SeasonEntrantsFromGame / CompetitionWinnerScreen: the German entrants of the European cups, at the start of + // a career (03-start 4) and at every season change. The engine pauses at this checkpoint + // inside finish() / a kickoff; the pages are projected there (Info.EuropeanEntrants). + session_->set_season_pause([this](const char* checkpoint, const GameState& state) { + if (std::string_view(checkpoint) != "the German entrants (CompetitionWinnerScreen)") return; + std::vector lines; + for (const auto& page : ui::season_entrants_from_game(state, exe_, texts_)) { + std::string names; + for (const auto& t : page.teams) names += (names.empty() ? "" : ", ") + t.name; + lines.push_back(page.footer + ": " + names); + } + if (lines.empty()) return; + pending_info_.push_back([this, lines] { + set_window("Info.EuropeanEntrants", 0); + for (const auto& l : lines) emit('i', l); + }); + }); + session_->set_season_cup_draw([this](const GameState& state, const SeasonCupDrawEvent& event) { + const ui::CupDrawProjection view = ui::cup_draw_from_game(state, event, exe_, texts_); + if (!view.source_eligible) return; + const std::string title = utf8(view.footer) + ", " + utf8(view.heading); + if (event.phase == SeasonCupDrawPhase::draw && !view.group_stage) { + std::vector> rows; + for (size_t i = 0; i + 1 < view.clubs.size(); i += 2) + rows.push_back({utf8(view.clubs[i].original_name), utf8(view.clubs[i + 1].original_name)}); + if (view.clubs.size() % 2) rows.push_back({utf8(view.clubs.back().original_name), "-"}); + pending_info_.push_back([this, title, rows] { + set_window("Info.CupDraw", 0); + emit('i', title + ":"); + emit_table({"Home", "Away"}, rows); + }); + } else if (event.phase == SeasonCupDrawPhase::overview && view.group_stage) { + std::vector> rows; + for (const auto& r : view.group_rows) + rows.push_back({std::to_string(r.rank), utf8(state.club_name(r.runtime_id))}); + const std::string caption = title + (view.group_caption.empty() ? "" : " " + utf8(view.group_caption)); + pending_info_.push_back([this, caption, rows] { + set_window("Info.CupDraw", 0); + emit('i', caption + ":"); + emit_table({"Rank", "Club"}, rows); + }); + } + }); +} + +void Console::flush_info() { + auto items = std::move(pending_info_); + pending_info_.clear(); + for (auto& f : items) f(); +} + +// --------------------------------------------------------------------------------------- +// file windows (03-start 2, 04-schreibtisch 8) + +std::filesystem::path Console::save_directory() const { + return options_.save_directory.empty() ? options_.data : options_.save_directory; +} + +// The browser's directory relative to the save directory ("." at the start), so logs and +// transcripts do not depend on where the installation lies. +std::string Console::shown_directory() const { + std::error_code ec; + const std::filesystem::path rel = std::filesystem::relative(browse_directory_, save_directory(), ec); + return ec || rel.empty() ? browse_directory_.generic_string() : rel.generic_string(); +} + +// A file name of the browser is a plain DOS name in the current directory: separators, drive +// colons and "." / ".." would write or read outside it (directories change only through +// ChangeDirectory / ParentDirectory, as in the original browser). +std::filesystem::path Console::browser_file(const std::string& name) const { + if (name == "." || name == ".." || name.find_first_of("/\\:") != std::string::npos) + fail("E_BAD_ARGUMENT", "not a file name: " + name + " (no directories; use ChangeDirectory)"); + std::filesystem::path path = browse_directory_ / name; + if (!path.has_extension()) path += ".FBM"; + return path; +} + +void Console::register_file_commands() { + // The original browser shows subdirectories and the *.FBM files of the current directory; + // a click selects a file (FILENAME field), a second click loads it. The same commands + // serve the load browser of the options screen and the desk's LoadGame/SaveGame. + for (const std::string window : {"NewGame.LoadGame", "LoadGame", "SaveGame"}) { + add({window, "ListFiles", {}, "directories and saved games here", false}, [this](const Values&) { + std::vector> dirs, files; + std::error_code ec; + for (const auto& entry : std::filesystem::directory_iterator(browse_directory_, ec)) { + if (entry.is_directory(ec)) dirs.push_back({entry.path().filename().string(), "dir"}); + else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) == ".fbm") + files.push_back({entry.path().stem().string(), "file"}); + } + if (ec) fail("E_IO", "cannot read the directory " + shown_directory()); + std::sort(dirs.begin(), dirs.end()); + std::sort(files.begin(), files.end()); + dirs.insert(dirs.end(), files.begin(), files.end()); + emit('i', "directory: " + shown_directory()); + emit_table({"Name", "Type"}, dirs); + }); + add({window, "ChangeDirectory", {detail::text("name")}, "into a subdirectory", false}, [this](const Values& v) { + const std::filesystem::path next = browse_directory_ / v.text("name"); + std::error_code ec; + if (!std::filesystem::is_directory(next, ec)) fail("E_BAD_ARGUMENT", "no directory " + v.text("name")); + browse_directory_ = next.lexically_normal(); + emit('+', "directory: " + shown_directory()); + }); + add({window, "ParentDirectory", {}, "one level up", false}, [this](const Values&) { + browse_directory_ = browse_directory_.parent_path(); + emit('+', "directory: " + shown_directory()); + }); + add({window, "SelectFile", {detail::text("name", 8)}, "select a file (FILENAME field, DOS name)", false}, + [this](const Values& v) { + selected_file_ = v.text("name"); + emit('+', "selected: " + selected_file_); + }); + add({window, "FileInfo", {detail::text("name")}, "short info of a saved game", false}, [](const Values&) { + fail("E_ENGINE_GAP", "the short info of saved games is not ported yet"); + }); + if (window != "SaveGame") { + add({window, "Load", {detail::text("name", 0, true)}, "load the selected or named file", true}, [this](const Values& v) { + const std::string name = v.has("name") ? v.text("name") : selected_file_; + if (name.empty()) fail("E_BAD_ARGUMENT", "no file selected (SelectFile or Load(name))"); + load_game(browser_file(name)); + }); + } else { + add({window, "Save", {detail::text("name", 8, true), boolean("overwrite", true)}, + "save under the selected or given name", true}, + [this](const Values& v) { + const std::string name = v.has("name") ? v.text("name") : selected_file_; + // "Leerer Name = nichts gespeichert" (04-schreibtisch 8) + if (name.empty()) { + emit('+', "nothing saved (no name)"); + return; + } + save_game(browser_file(name), v.boolean("overwrite")); + }); + } + } +} + +void Console::load_game(const std::filesystem::path& requested) { + std::filesystem::path path = requested; + if (!path.has_extension()) path += ".FBM"; + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) fail("E_IO", "file not found: " + path.filename().string()); + std::unique_ptr loaded; + try { + loaded = std::make_unique(options_.data, options_.seed, path); + } catch (const std::exception&) { + fail("E_RULE", text(kErrorNotAGameScore), "errorNotAGameScore"); + } + session_ = std::move(loaded); + install_hooks(); + career_ = true; + revision_ = 1; + confirmed_.clear(); + picker_.reset(); + seen_mail_.clear(); + pairings_.reset(); + table_league_ = -1; + const ui::DeskState d = session_->desktop_projection(revision_); + // The messages of a loaded game are not new: count them instead of repeating them all. + size_t messages = 0; + for (size_t slot = 0; slot < session_->state().manager_teams.size(); ++slot) + for (const auto& m : ui::mailbox_state_from_game(session_->state(), int(slot), revision_).messages) { + seen_mail_[int(slot)].insert(std::to_string(m.date_counter) + "|" + m.text); + if (int(slot) == d.manager_slot) ++messages; + } + set_window("Desktop", d.manager_slot + 1); + emit('+', "Game loaded: " + path.stem().string() + " (" + utf8(d.club_name) + ", " + + date_text(d.date.day, d.date.month, d.date.year) + ", " + std::to_string(messages) + " messages in the mailbox)"); + enter_desktop(); +} + +void Console::save_game(const std::filesystem::path& path, bool overwrite) { + std::error_code ec; + auto write = [this, path](bool allow_overwrite) { + std::string error; + if (!session_->save_game(path, active_slot(), allow_overwrite, error)) fail("E_IO", "not saved: " + error); + emit('+', "Game saved: " + path.stem().string()); + }; + if (std::filesystem::exists(path, ec) && !overwrite) { + ask(text(kSaveConfirmOverwrite), {"Yes", "No"}, "No", + [this, write](const std::string& answer) { + if (answer == "Yes") write(true); + else emit('+', "nothing saved"); + }, + "saveConfirmOverwrite"); + return; + } + write(overwrite); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_state.cpp b/src/cli/console/windows_state.cpp new file mode 100644 index 0000000..298a4ac --- /dev/null +++ b/src/cli/console/windows_state.cpp @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: GPL-3.0-only +// State(view): the engine projection behind a view as one structured record (Stufe 2.5 of +// docs/CLI_CONCEPT, "strukturierte Daten"). A graphical front end that talks to the console +// (mailbox --serve, socket --listen) reads its screens from here instead of parsing text: +// the same projections the SDL windows draw, serialised by the ui layer's *_json functions +// (src/ui), plus two small records the ui layer has no serialiser for (line-up, mailbox). +// Text mode prints the JSON after "state :"; with --json it is the line's "data". +// Read-only: no projection here draws random numbers or changes the game. + +#include +#include +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "cli/json.hpp" +#include "ui/advertising.hpp" +#include "ui/bank.hpp" +#include "ui/contracts.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" +#include "ui/mailbox_state.hpp" +#include "ui/stadium.hpp" +#include "ui/toto.hpp" +#include "ui/training.hpp" +#include "ui/training_camp.hpp" +#include "ui/transfer_market.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +const std::vector kStateViews = {"Desk", "Table", "Lineup", "Mailbox", "Bank", "Market", + "Advertising", "Contracts", "Stadium", "Toto", "Training", "Camp"}; + +// One squad row as the line-up screen knows it (DATEN-A and DATEN-B together): the +// attributes of m3d.hpp, the place (slot flags 0x8000 pitch / 0x4000 bench), the absence +// (w364 bits 16-19 duration, bit 20 ban) and the contract fields of the board row. +Json lineup_record(const ui::LineupState& l) { + Json::Array players; + for (const auto& p : l.players) { + if (p.player_id < 0) continue; + const auto& a = p.attributes; + const int duration = int(a.w364 >> 16 & 0xF); + Json::Array skills; + for (int i = 0; i < 7; ++i) skills.emplace_back(a.skill(Player::Skill(i))); + const auto le32 = [&](size_t at) { + return std::int64_t(uint32_t(p.board[at]) | uint32_t(p.board[at + 1]) << 8 | uint32_t(p.board[at + 2]) << 16 | + uint32_t(p.board[at + 3]) << 24); + }; + players.emplace_back(Json::Object{ + {"row", p.row}, + {"id", p.player_id}, + {"name", utf8(p.name)}, + {"position", a.position()}, // 0 goalkeeper, 1 defender, 2 midfielder, 3 forward + {"condition", a.condition()}, + {"technique", a.technique()}, + {"form", a.form()}, + {"strength", a.strength()}, + {"age", a.age()}, + {"skills", Json(std::move(skills))}, // 0-3 each: teamplay, speed, shot, pass, tackling, free kick, corner + {"place", std::string((p.slot & 0x8000) ? "pitch" : (p.slot & 0x4000) ? "bench" : "out")}, + {"injury", duration != 0 && !(a.w364 & 0x100000) ? duration : 0}, + {"ban", duration != 0 && (a.w364 & 0x100000) ? duration : 0}, + {"games", int(a.w364 >> 26)}, + {"goals", int(a.w364 >> 2 & 63)}, + {"assists", int(a.w368 >> 18 & 63)}, + {"yellow_cards", int(a.w368 >> 14 & 15)}, + {"red_cards", int(a.w368 >> 24 & 7)}, + {"contract_months", p.board[0xc] == 255 ? Json(nullptr) : Json(int(p.board[0xc]))}, + {"months_at_club", int(p.board[0x11]) + 1}, + {"salary", le32(0x50)}, + }); + } + return Json(Json::Object{{"manager_slot", l.manager_slot}, {"players", Json(std::move(players))}}); +} + +Json mailbox_record(const ui::MailboxState& m) { + Json::Array messages; + int index = 0; + for (const auto& msg : m.messages) + messages.emplace_back(Json::Object{{"index", ++index}, {"date_counter", int(msg.date_counter)}, {"text", msg.text}}); + return Json(Json::Object{{"manager_slot", m.manager_slot}, {"messages", Json(std::move(messages))}}); +} + +} // namespace + +// --- Advice and Scoreboard (for agents that learn: docs/CLI_CONCEPT/16-playbook.md) ------- +// Advice names what needs a decision now, from the engine's own data; it judges nothing +// the player could not see on his screens, it only collects it. Scoreboard compares the +// human managers. Both read only. +void Console::register_advice_commands() { + add({"*", "Advice", {}, "situations that need a decision now: form, squad, contracts, advertising, money", false}, + [this](const Values& v) { + if (!career_) fail("E_NOT_IN_WINDOW", "Advice needs a running game"); + own_view_only(v.player, "Advice"); + const ui::DeskState d = desk(); + if (d.national_team) { + emit('i', "advice: you coach the national team now; the club's matters wait until it ends"); + return; + } + const GameState& g = session_->state(); + const int slot = d.manager_slot; + const int team = g.manager_teams.at(size_t(slot)); + int alerts = 0; + auto alert = [&](const std::string& topic, const std::string& text, Json values = nullptr) { + ++alerts; + Json::Object o{{"topic", topic}, {"text", text}}; + if (!std::holds_alternative(values.value)) o["values"] = std::move(values); + emit('i', "advice [" + topic + "] " + text, Json(std::move(o))); + }; + // form: the points of the last three matchdays and the place (three points a win) + const int league = team_league(team); + if (league >= 0 && league < kLeagueCount) { + const int rounds = int(int8_t(g.league_rounds.at(size_t(league)))); + const int pos = team - league_first_team(league); + const ui::LeagueTableState table = ui::league_table_from_game(g, slot, league); + int rank = 0, points = 0, games = 0; + for (const auto& r : table.rows) + if (r.runtime_team_id == team) rank = r.rank, points = r.points, games = r.games; + if (rounds >= 3) { + const LeagueTable recent = compute_league_table(g, league, rounds - 3, rounds, 3, 1); + const int recent_points = recent.points[size_t(pos)], recent_games = recent.games(pos); + if (recent_games >= 3 && recent_points <= 1) + alert("form", std::to_string(recent_points) + " points from the last " + std::to_string(recent_games) + + " league matches - line-up, tactics or training need a change", + Json(Json::Object{{"recent_points", recent_points}, {"recent_games", recent_games}})); + } + const int size = int(table.rows.size()); + if (games >= 8 && size > 0 && rank > size - 4) + alert("table", "place " + std::to_string(rank) + " of " + std::to_string(size) + " after " + + std::to_string(games) + " matches - relegation zone", + Json(Json::Object{{"rank", rank}, {"points", points}, {"games", games}})); + } + // tactics: the match engine keeps a human side's attitude (item 0) fixed for the whole + // match unless the assistant controls it; 0 is the most defensive. New careers + // start at 0, and human clubs then score far less than the computer clubs (the + // original does the same: its human Bayern scored 28 goals in a season). + { + const ui::TacticsState t = prep().tactics; + if (t.values[0] == 0 && t.assistant_attitude == 0) + alert("tactics", "attitude (tactic item 0) is 0, the most defensive, for whole matches - " + "SetTactic(0, 2) (computer clubs play 2 at home, 1 away) or SetAutomation(Tactics, true)", + Json(Json::Object{{"attitude", 0}, {"assistant", false}})); + } + // squad: size, goalkeepers, absences in the eleven, weak form of starters + const ui::LineupState l = prep().lineup; + int players = 0, keepers = 0, fit_keepers = 0; + std::vector absent, weak, expiring; + for (const auto& p : l.players) { + if (p.player_id < 0) continue; + const auto& a = p.attributes; + ++players; + const bool out = (a.w364 >> 16 & 0xF) != 0; + if (a.position() == 0) ++keepers, fit_keepers += out ? 0 : 1; + const bool starter = (p.slot & 0x8000) != 0; + if (starter && out) absent.push_back(utf8(p.name)); + if (starter && !out && a.form() < 45) weak.push_back(utf8(p.name) + " (form " + std::to_string(a.form()) + ")"); + if (p.board[0xc] != 255 && p.board[0xc] <= 2) + expiring.push_back(utf8(p.name) + " (" + std::to_string(p.board[0xc]) + " months)"); + } + auto list = [](const std::vector& v) { + std::string s; + for (const auto& x : v) s += (s.empty() ? "" : ", ") + x; + return s; + }; + if (players < 18) alert("squad", std::to_string(players) + " players - too few for injuries and bans (keep 20-24)"); + if (fit_keepers < 2) + alert("squad", std::to_string(fit_keepers) + " fit goalkeeper(s) of " + std::to_string(keepers) + " - buy or loan one"); + if (!absent.empty()) alert("lineup", "injured or banned in the starting eleven: " + list(absent)); + if (!weak.empty()) alert("lineup", "starters in weak form: " + list(weak)); + if (!expiring.empty()) alert("contracts", "contracts ending: " + list(expiring) + " - Open(Contracts), OpenNegotiation"); + // advertising: expired contracts (renewal pending) and free places + const ui::AdvertisingState a = ui::advertising_from_game(g, slot, revision_); + int expired = 0, free_places = 0; + for (int s = 0; s < 16; ++s) { + if (a.offers[size_t(s)].status == bmh::AdvertisingOfferStatus::unsupported_extension) ++expired; + else if (!(s < 14 ? a.boards.at(size_t(s)) : s == 14 ? a.shirt : a.television).active) ++free_places; + } + if (expired) alert("advertising", std::to_string(expired) + " contract(s) ran out - ListAdOffers on the place renews or frees it"); + if (free_places) + alert("advertising", std::to_string(free_places) + " free advertising place(s) - Open(Advertising), ListAdOffers, AcceptAdOffer"); + // money: overdrawn, or beyond the credit line + const auto p = prep(); + if (p.bank) { + const int64_t balance = p.bank->balance, credit = p.bank->credit_line; + if (balance < -credit) + alert("money", "the account (" + std::to_string(balance) + ") is beyond the credit line (" + std::to_string(credit) + + ") - sell, cut wages or take a credit"); + else if (balance < 0) + alert("money", "the account is overdrawn (" + std::to_string(balance) + "); interest is charged"); + } + if (alerts == 0) emit('i', "advice: nothing urgent"); + }); + + add({"*", "Scoreboard", {}, "all human managers: league, place, points, balance, strength of the best eleven", false}, + [this](const Values&) { + if (!career_) fail("E_NOT_IN_WINDOW", "Scoreboard needs a running game"); + const GameState& g = session_->state(); + std::vector> rows; + for (size_t m = 0; m < g.manager_teams.size(); ++m) { + const int team = g.manager_teams[m]; + if (team < 0 || squad_range(team).count == 0) { + rows.push_back({std::to_string(m + 1), "(national team)", "-", "-", "-", "-", "-", "-"}); + continue; + } + const int league = team_league(team); + std::string league_name = "-", rank = "-", points = "-", games = "-"; + if (league >= 0 && league < kLeagueCount) { + const ui::LeagueTableState t = ui::league_table_from_game(g, int(m), league); + league_name = t.league_name; + for (const auto& r : t.rows) + if (r.runtime_team_id == team) + rank = std::to_string(r.rank), points = std::to_string(r.points), games = std::to_string(r.games); + } + const size_t rec = m * 0xb0c; + const int32_t balance = int32_t(uint32_t(g.manager_records.at(rec + 0x314)) | uint32_t(g.manager_records.at(rec + 0x315)) << 8 | + uint32_t(g.manager_records.at(rec + 0x316)) << 16 | uint32_t(g.manager_records.at(rec + 0x317)) << 24); + // the strength of the best eleven (displayed strength, as the squad lists show it) + std::vector strengths; + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; ++s) { + const int id = g.squad_slots.at(s) & 0x0fff; + if (id != 0x0fff && size_t(id) < g.players.size()) strengths.push_back(g.players[size_t(id)].strength()); + } + std::sort(strengths.rbegin(), strengths.rend()); + int sum = 0, n = 0; + for (; n < 11 && n < int(strengths.size()); ++n) sum += strengths[size_t(n)]; + rows.push_back({std::to_string(m + 1), utf8(g.club_name(team)), league_name, rank, points, games, std::to_string(balance), + n ? std::to_string(sum / n) : "-"}); + } + emit_table({"Manager", "Club", "League", "Place", "Points", "Games", "Balance", "Best11"}, rows); + }); +} + +void Console::register_state_commands() { + add({"*", "State", {choice("view", kStateViews)}, "the full projection of a view as structured (JSON) data", false}, + [this](const Values& v) { + if (!career_) fail("E_NOT_IN_WINDOW", "State needs a running game"); + own_view_only(v.player, "State"); + const std::string view = kStateViews[size_t(v.choice("view"))]; + const int slot = active_slot(); + Json data; + switch (v.choice("view")) { + case 0: + data = parse_json(ui::desk_json(desk())); + data.object()->insert_or_assign("engine_attached", true); // (ui::desk_json marks it false) + break; + case 1: { + const ui::DeskState d = desk(); + data = parse_json(ui::league_table_json(ui::league_table_from_game(session_->state(), slot, d.league >= 0 ? d.league : 0))); + break; + } + case 2: data = lineup_record(prep().lineup); break; + case 3: data = mailbox_record(ui::mailbox_state_from_game(session_->state(), slot, revision_)); break; + case 4: { + const auto p = prep(); + if (!p.bank) fail("E_MODE_LOCKED", "no bank here (national team?)"); + data = parse_json(ui::bank_state_json(*p.bank)); + break; + } + case 5: { + const auto p = prep(); + if (!p.transfer_market) fail("E_MODE_LOCKED", "no transfer market here (national team?)"); + data = parse_json(ui::transfer_market_state_json(*p.transfer_market)); + break; + } + case 6: data = parse_json(ui::advertising_state_json(ui::advertising_from_game(session_->state(), slot, revision_))); break; + case 7: data = parse_json(ui::contracts_state_json(ui::contracts_from_game(session_->state(), slot, revision_))); break; + case 8: { + const auto p = prep(); + if (!p.stadium) fail("E_MODE_LOCKED", "no stadium view (national team?)"); + data = parse_json(ui::stadium_state_json(*p.stadium)); + break; + } + case 9: { + const auto p = prep(); + if (!p.toto) fail("E_MODE_LOCKED", "no Toto in this game"); + data = parse_json(ui::toto_state_json(*p.toto)); + break; + } + case 10: { + const auto p = prep(); + if (!p.training) fail("E_MODE_LOCKED", "there is no training in mode I"); + data = parse_json(ui::training_json(*p.training)); + break; + } + default: { + const auto p = prep(); + if (!p.training_camp) fail("E_MODE_LOCKED", "no training camp here"); + data = parse_json(ui::training_camp_json(*p.training_camp)); + break; + } + } + // text mode: the record after the label; --json: the same record as the line's data + if (options_.json) emit('i', "state " + view, std::move(data)); + else emit('i', "state " + view + ": " + dump_json(data)); + }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_tables.cpp b/src/cli/console/windows_tables.cpp new file mode 100644 index 0000000..89394d0 --- /dev/null +++ b/src/cli/console/windows_tables.cpp @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The league table and the fixtures window (docs/CLI_CONCEPT/05-information.md). +// +// LeagueTable reads the pure projection ui::league_table_from_game. Fixtures goes through the +// engine like the SDL app (CareerSession::open_league_pairings / dispatch_league_pairings): +// the original draws random numbers when the window opens and when it closes +// (pairings_runtime_draw, stir_random), so a console that only printed the schedule would +// leave the game on a different random sequence than the original. + +#include "app/window_actions.hpp" +#include + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/schedule.hpp" +#include "ui/desk_state.hpp" +#include "ui/desktop.hpp" +#include "ui/league_table.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +void Console::register_table_commands() { + closers_["Fixtures"] = [this] { fixtures_action(LeaguePairingsAction::close); }; + // ListLeagues is global (commands.csv "*"): the nine leagues with their number, as + // LeagueTable/Fixtures take them; during the manager selection the five start leagues. + add({"*", "ListLeagues", {}, "leagues with number and size", false}, [this](const Values&) { + std::vector> rows; + if (career_) { + for (int league = 0; league < kLeagueCount; ++league) { + const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), active_slot(), league); + rows.push_back({std::to_string(league), t.league_name, std::to_string(t.rows.size())}); + } + } else if (picker_) { + for (int league = 0; league < 5; ++league) + rows.push_back({std::to_string(league), utf8(picker_->group_label(league)), + std::to_string(picker_->group_last(league) - picker_->group_first(league) + 1)}); + } else { + fail("E_RULE", "the leagues are known after NewGame(...)"); + } + emit_table({"League", "Name", "Clubs"}, rows); + }); + // --- LeagueTable ---------------------------------------------------------------------- + add({"LeagueTable", "ShowTable", {integer("league", 0, kLeagueCount - 1, true)}, "the table (without league: the one shown)", false}, + [this](const Values& v) { + if (v.has("league")) table_league_ = int(v.integer("league")); + show_league_table(); + }); + add({"LeagueTable", "SetLeague", {integer("league", 0, kLeagueCount - 1)}, "show another league", false}, [this](const Values& v) { + table_league_ = int(v.integer("league")); + show_league_table(); + }); + add({"LeagueTable", "OpenFixtures", {}, "the fixtures of this league", false}, [this](const Values&) { open_fixtures(); }); + for (const char* name : {"ToggleEurope", "SetView", "SetCriteria", "SetRange", "SetPointsMode", "ComputerTip", "OpenStrengths"}) { + add({"LeagueTable", name, {}, "not in the console yet", false}, [name](const Values&) { + fail("E_ENGINE_GAP", std::string(name) + " of the league table is not in the console yet"); + }); + } + + // --- Fixtures ------------------------------------------------------------------------- + add({"Fixtures", "ShowFixtures", {integer("league", 0, kLeagueCount - 1, true), integer("matchday", 1, 38, true)}, + "the page shown (optionally another league / matchday first)", false}, + [this](const Values& v) { + if (v.has("league")) fixtures_action(LeaguePairingsAction::select_league, int(v.integer("league"))); + if (v.has("matchday")) { + const int wanted = int(v.integer("matchday")) - 1; + for (int step = 0; step < 40 && pairings_ && pairings_->identity.round != wanted; ++step) + fixtures_action(LeaguePairingsAction::next); + if (pairings_ && pairings_->identity.round != wanted) fail("E_BAD_ARGUMENT", "the league has no such matchday"); + } + if (!v.has("league") && !v.has("matchday")) show_fixtures(); + }); + add({"Fixtures", "SetLeague", {integer("league", 0, kLeagueCount - 1)}, "another league", false}, + [this](const Values& v) { fixtures_action(LeaguePairingsAction::select_league, int(v.integer("league"))); }); + add({"Fixtures", "SetMatchday", {integer("matchday", 1, 38)}, "go to a matchday", false}, [this](const Values& v) { + const int wanted = int(v.integer("matchday")) - 1; + // page through without printing every page on the way: only the target is shown + quiet_fixtures_ = true; + try { + for (int step = 0; step < 40 && pairings_ && pairings_->identity.round != wanted; ++step) + fixtures_action(LeaguePairingsAction::next); + } catch (...) { + quiet_fixtures_ = false; + throw; + } + quiet_fixtures_ = false; + if (pairings_ && pairings_->identity.round != wanted) fail("E_BAD_ARGUMENT", "the league has no such matchday"); + if (pairings_) show_fixtures(); + }); + add({"Fixtures", "NextMatchday", {}, "the next matchday (arrow)", false}, + [this](const Values&) { fixtures_action(LeaguePairingsAction::next); }); + add({"Fixtures", "PreviousMatchday", {}, "the previous matchday (arrow)", false}, + [this](const Values&) { fixtures_action(LeaguePairingsAction::previous); }); + add({"Fixtures", "ShowPostponed", {}, "the postponed games", false}, + [this](const Values&) { fixtures_action(LeaguePairingsAction::postponed_list); }); + add({"Fixtures", "ComputerTip", {}, "the computer's forecast for this page", false}, + [this](const Values&) { fixtures_action(LeaguePairingsAction::computer_tip); }); + add({"Fixtures", "OpenTable", {}, "the league table", false}, [this](const Values&) { + // the table window is a pure projection; leaving the fixtures closes them first + const int league = pairings_ ? pairings_->identity.league : -1; + fixtures_action(LeaguePairingsAction::close); + open_window("LeagueTable"); + table_league_ = league; + show_league_table(); + }); + for (const char* name : {"FindGame", "GamesOf", "Page", "OpenStrengths"}) { + add({"Fixtures", name, {}, "not in the console yet", false}, [name](const Values&) { + fail("E_ENGINE_GAP", std::string(name) + " of the fixtures is not in the console yet"); + }); + } +} + +void Console::show_league_table() { + const ui::DeskState d = desk(); + const int league = table_league_ >= 0 ? table_league_ : (d.league >= 0 ? d.league : 0); + table_league_ = league; + const ui::LeagueTableState table = ui::league_table_from_game(session_->state(), d.manager_slot, league); + emit('i', table.league_name + ", " + std::to_string(table.rounds_played) + " matchdays played"); + std::vector> rows; + for (const auto& r : table.rows) { + std::string name = r.name; + for (size_t m = 0; m < d.manager_teams.size(); ++m) + if (d.manager_teams[m] == r.runtime_team_id) name += " [human:" + std::to_string(m + 1) + "]"; + rows.push_back({std::to_string(r.rank), name, std::to_string(r.games), std::to_string(r.wins), std::to_string(r.draws), + std::to_string(r.losses), std::to_string(r.goals_for) + ":" + std::to_string(r.goals_against), + std::to_string(r.goals_for - r.goals_against), std::to_string(r.points)}); + } + emit_table({"Rank", "Club", "G", "W", "D", "L", "Goals", "Diff", "Pts"}, rows); +} + +void Console::open_fixtures() { + const ui::DeskState d = desk(); + std::string error; + std::optional page; + try { + page = app::LeagueFamilyActions(*session_).open_pairings(d, revision_, error); + } catch (const std::exception& e) { + fail("E_INTERNAL", std::string("fixtures: ") + e.what()); + } + if (!page) fail("E_RULE", std::string("fixtures cannot open") + (d.national_team ? " while you coach the national team" : "") + ": " + error); + pairings_ = std::move(page); + open_window("Fixtures"); + show_fixtures(); +} + +void Console::show_fixtures() { + if (!pairings_) fail("E_INTERNAL", "no fixtures page"); + const auto& p = *pairings_; + // the original pads its title parts for the screen layout + auto trim = [](std::string s) { + while (!s.empty() && s.front() == ' ') s.erase(0, 1); + while (!s.empty() && s.back() == ' ') s.pop_back(); + return s; + }; + std::string title = trim(utf8(p.title)); + for (const std::string& part : {trim(utf8(p.subtitle)), trim(utf8(p.date))}) + if (!part.empty()) title += ", " + part; + emit('i', title); + std::vector> rows; + for (const auto& r : p.rows) { + std::string result = utf8(r.result); + // the original note already names the leg ("2:2 Hinspiel", message LeaguePairings_FormatError_TextPointer13) + if (!r.first_leg.empty()) result += " (" + utf8(r.first_leg) + ")"; + if (!r.scheduled_date.empty()) + result += " " + utf8(r.scheduled_ordinal) + utf8(r.scheduled_date); + rows.push_back({utf8(r.names[0]), utf8(r.names[1]), result.empty() ? "-" : result}); + } + emit_table({"Home", "Away", "Result"}, rows); +} + +// One action in the fixtures window, applied by the engine on a staged copy; a rejected +// action leaves state and random generators as they were (as src/app/controller.cpp does). +void Console::fixtures_action(LeaguePairingsAction kind, int value) { + if (!pairings_) fail("E_INTERNAL", "the fixtures window is not open"); + std::string error; + std::optional applied; + try { + applied = app::LeagueFamilyActions(*session_).pairings(pairings_->identity, kind, value, revision_, error); + } catch (const std::exception& e) { + fail("E_RULE", std::string("fixtures: ") + e.what()); + } + if (!applied) fail("E_RULE", "fixtures: " + error); + if (applied->closed) { + pairings_.reset(); + close_window(); + emit('+', "fixtures closed"); + return; + } + pairings_ = std::move(applied->page); + if (!quiet_fixtures_) show_fixtures(); +} + +} // namespace bmh::cli::console diff --git a/src/cli/console/windows_transfer.cpp b/src/cli/console/windows_transfer.cpp new file mode 100644 index 0000000..72c9127 --- /dev/null +++ b/src/cli/console/windows_transfer.cpp @@ -0,0 +1,488 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The transfer market of docs/CLI_CONCEPT/06-verein.md 5 (menu 17): the market list, listing an +// own player for sale or loan, and the offer editor Transfer.Negotiate for a purchase or a loan. +// +// The engine calls are the SDL app's (src/app/controller.cpp serve_transfer_action / +// serve_transfer_offer): CareerSession::dispatch_transfer_market, open_transfer_offer and +// dispatch_transfer_offer through app::TransferActions. Request binding and rollback +// belong to that shared boundary, including aborted questions and acknowledgements. The +// original's notices (agreement, refusal) arrive through the sale hook and are printed as +// i lines after the call. + +#include + +#include "app/window_actions.hpp" + +#include "cli/console/console.hpp" +#include "cli/console/detail.hpp" +#include "game/desk_actions.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/poach.hpp" +#include "game/schedule.hpp" +#include "ui/club_info.hpp" +#include "ui/desk_state.hpp" +#include "ui/league_table.hpp" +#include "ui/outgoing_transfer.hpp" +#include "ui/transfer_market.hpp" + +namespace bmh::cli::console { + +using namespace detail; + +namespace { + +// The editor of a market player is closed when his four bid places are taken by other clubs +// (OpenTransferEditor: editor_slot finds no free or own place; the original takes at most four bids). +// Agents read the old "this offer cannot be changed" as a fault (learning session B2-004/005). +constexpr const char* kNoBidSlot = + "four other clubs have bid for this player already - there is no room for another offer " + "(at most four bids per player); try another player or wait until he has decided"; + +constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU +const std::vector kPositionKeys = {"TOR", "ABW", "MIT", "STU"}; +// the ten editor fields in the order of OutgoingTransferField +const std::vector kOfferFields = {"Fee", "Salary", "Years", "BonusGoal", "BonusPoints", "BonusAppearance", + "BonusChampion", "Bonus2to5", "Bonus6to10", "BonusAvoidRelegation"}; + +} // namespace + +void Console::register_transfer_commands() { + auto market = [this] { + const auto p = prep(); + if (!p.transfer_market) fail("E_MODE_LOCKED", "no transfer market here (national team?)"); + return *p.transfer_market; + }; + // the original's notices during a transfer call, printed after it + auto notices = std::make_shared>(); + // The yes/no questions of a poaching offer (PresentManagerDialog: the selling manager, the DFB + // fee) come from inside the engine call. The console answers them from `answers`; an + // unanswered one is recorded in `pending` and stops the call (nothing is committed), the + // player is asked and the same call runs again with the answers so far. + struct Questions { + std::vector answers; + size_t next = 0; + std::optional> pending; // manager, text + }; + auto questions = std::make_shared(); + auto hooks = [notices, questions] { + HumanBuyerSaleHooks h; + h.notice = [notices](const GameState&, const HumanBuyerSaleNotice& n) { notices->push_back(utf8(n.original_message)); }; + h.confirm = [questions](const GameState&, int manager, const std::string& text) -> bool { + if (questions->next < questions->answers.size()) return questions->answers[questions->next++]; + questions->pending = std::make_pair(manager, utf8(text)); + throw std::runtime_error("question to player " + std::to_string(manager + 1)); + }; + return h; + }; + auto flush_notices = [this, notices] { + for (const auto& n : *notices) emit('i', n); + notices->clear(); + }; + auto filter = std::make_shared>(std::array{true, true, true, true}); + auto show_market = [this, market, filter](int page) { + const ui::TransferMarketState m = market(); + std::vector items; + for (const auto& item : m.items) + if (item.position >= 0 && item.position < 4 && (*filter)[size_t(item.position)]) items.push_back(&item); + constexpr size_t kPage = 20; + const size_t pages = std::max(1, (items.size() + kPage - 1) / kPage); + if (page < 1 || size_t(page) > pages) fail("E_BAD_ARGUMENT", "the market has " + std::to_string(pages) + " pages"); + std::vector> rows; + for (size_t i = (size_t(page) - 1) * kPage; i < items.size() && i < size_t(page) * kPage; ++i) { + const auto& it = *items[i]; + std::string mark = it.own_listing ? "[own]" : it.own_bid_pending ? "[your bid]" : ""; + rows.push_back({"id:" + std::to_string(it.player), utf8(it.name), text(kPositionNames + it.position), std::to_string(it.age), + std::to_string(it.strength), utf8(it.seller_name), money(it.asking_fee), std::to_string(it.offers), mark}); + } + emit_table({"Id", "Player", "Pos", "Age", "Str", "Club", "Fee", "Offers", ""}, rows); + emit('i', "page " + std::to_string(page) + "/" + std::to_string(pages) + ", balance " + money(m.balance) + ", credit line " + + money(m.credit_line)); + }; + openers_[17] = [this, show_market] { + open_window("Transfer"); + show_market(1); + }; + add({"Transfer", "ShowMarket", {integer("page", 1, 100, true)}, "the offered players (20 per page)", false}, + [show_market](const Values& v) { show_market(int(v.integer("page", 1))); }); + Param positions = detail::text("positions"); + positions.display = "positions:list(TOR,ABW,MIT,STU)|All"; + add({"Transfer", "SetMarketFilter", {positions}, "ALLE / TOR / ABW / MIT / STU", false}, [this, filter, show_market](const Values& v) { + std::string list = v.text("positions"); + if (lower(list) == "all") { + filter->fill(true); + } else { + // a single position (TOR) counts as the list [TOR] + if (list.size() >= 2 && list.front() == '[' && list.back() == ']') list = list.substr(1, list.size() - 2); + for (char& c : list) c = char(std::toupper(static_cast(c))); + filter->fill(false); + size_t start = 0; + while (start <= list.size()) { + const size_t comma = list.find(',', start); + std::string item = list.substr(start, comma == std::string::npos ? std::string::npos : comma - start); + item.erase(0, item.find_first_not_of(' ')); + item.erase(item.find_last_not_of(' ') + 1); + const auto it = std::find(kPositionKeys.begin(), kPositionKeys.end(), item); + if (it == kPositionKeys.end()) fail("E_BAD_ARGUMENT", "unknown position " + item); + (*filter)[size_t(it - kPositionKeys.begin())] = true; + if (comma == std::string::npos) break; + start = comma + 1; + } + } + show_market(1); + }); + + // own squad rows by id:/row:/name, market players by id:/name + auto squad_item = [market](const std::string& reference) { + const ui::TransferMarketState m = market(); + std::vector refs; + for (const auto& s : m.squad) refs.push_back({s.row, s.player, utf8(s.name)}); + return m.squad[resolve_player(reference, refs)]; + }; + auto market_item = [market](const std::string& reference) { + const ui::TransferMarketState m = market(); + std::vector refs; + for (const auto& it : m.items) refs.push_back({it.list_entry, it.player, utf8(it.name)}); + return m.items[resolve_player(reference, refs)]; + }; + auto list_player = [this, market, squad_item, hooks, flush_notices](const std::string& reference, bool loan) { + const ui::TransferMarketState m = market(); + const ui::TransferMarketSquadItem item = squad_item(reference); + if (item.already_listed) fail("E_RULE", utf8(item.name) + " is already on the list"); + const auto r = app::TransferActions::listing(m, item, loan); + std::string error; + std::optional outcome; + try { + outcome = app::TransferActions(*session_).market(r, hooks(), revision_, error); + } catch (const std::exception& e) { + fail("E_INTERNAL", std::string("transfer: ") + e.what()); + } + if (!outcome) { + require_engine(false, "transfer", error); + } + flush_notices(); + emit('+', utf8(item.name) + (loan + ? " steht auf der Transferliste; der Entleiher wählt 12 oder 24 Monate im Angebot" + : " is on the transfer list")); + }; + Param player = detail::text("player"); + player.display = "player:Player"; + add({"Transfer", "SellPlayer", {player}, "VER-KAUFEN: put an own player on the list", true}, + [list_player](const Values& v) { list_player(v.text("player"), false); }); + add({"Transfer", "LoanOutPlayer", {player, integer("months", 12, 24, true)}, "VER-LEIHEN: offer an own player for loan", true}, + [list_player](const Values& v) { + if (v.integer("months", 24) != 12 && v.integer("months", 24) != 24) + fail("E_BAD_ARGUMENT", "Leihangebote verwenden 12 oder 24 Monate"); + list_player(v.text("player"), true); + }); + + // --- Transfer.Negotiate: the offer editor (06-verein 5.2) ----------------------------- + auto show_offer = [this] { + if (!offer_editor_) fail("E_INTERNAL", "no offer editor"); + const auto& e = *offer_editor_; + const auto& p = e.panel; + emit('i', utf8(p.player_name) + (p.seller_name.empty() ? std::string() : " (" + utf8(p.seller_name) + ")") + ", age " + std::to_string(p.age) + ", strength " + + std::to_string(p.strength) + (e.quote_loan ? ", loan" : "")); + std::vector> rows = { + {"demand", money(p.asking_fee), money(p.asking_monthly_salary), "-"}, + {"quote", money(p.quoted_fee), money(p.quoted_monthly_salary), std::to_string(p.quoted_years)}, + {"offer", money(e.fee), money(e.monthly_salary), std::to_string(e.duration_years)}}; + emit_table({"", "Fee", "Monthly salary", "Years"}, rows); + std::vector> bonuses; + for (size_t i = 0; i < 7; ++i) bonuses.push_back({kOfferFields[3 + i], std::to_string(e.bonuses[i] * (i >= 3 ? 5 : 1))}); + emit_table({"Bonus", "Percent"}, bonuses); + if (!e.editable) emit('i', kNoBidSlot); + }; + auto offer_request = [this](ui::OutgoingTransferRequestKind kind, ui::OutgoingTransferField field, uint32_t value) { + return app::TransferActions::editor(*offer_editor_, kind, field, value); + }; + auto dispatch_offer = [this, hooks, flush_notices](const ui::OutgoingTransferRequest& r, + const app::TransferOfferTeamInfoPresenter& team_info = {}, + const app::TransferOfferPlayerInfoPresenter& player_info = {}) { + std::string error; + std::optional result; + try { + result = loan_return_offer_active() + ? dispatch_loan_return_offer(r, hooks(), error, team_info, player_info) + : app::TransferActions(*session_).offer(r, hooks(), revision_, error, team_info, player_info); + } catch (const std::exception& e) { + fail("E_INTERNAL", std::string("transfer offer: ") + e.what()); + } + if (!result) { + require_engine(false, "transfer offer", error); + } + flush_notices(); + return *result; + }; + auto open_offer = [this, market, market_item, show_offer, dispatch_offer]( + const std::string& reference, bool loan, int months = 24) { + const ui::TransferMarketState m = market(); + if (loan && months != 12 && months != 24) + fail("E_BAD_ARGUMENT", "Leihangebote verwenden 12 oder 24 Monate"); + if (loan && months == 12 && m.source_market_mode != 3) + fail("E_RULE", "Die Laufzeit kann nur im Original-Verhandlungsmodus III geändert werden"); + const ui::TransferMarketItem item = market_item(reference); + if (item.own_listing) fail("E_RULE", "that is your own player"); + const auto r = app::TransferActions::opening(m, item, loan); + std::string error; + std::optional result; + try { + result = app::TransferActions(*session_).open_offer(r, revision_, error); + } catch (const std::exception& e) { + fail("E_INTERNAL", std::string("transfer offer: ") + e.what()); + } + if (!result) { + require_engine(false, "transfer offer", error); + } + offer_editor_ = result->editor; + offer_submitted_ = false; + open_window("Transfer.Negotiate"); + if (loan && offer_editor_->editable && offer_editor_->duration_years != months / 12) { + auto updated = *offer_editor_; + updated.duration_years = uint8_t(months / 12); + const auto action = app::TransferActions::editor(updated, + ui::OutgoingTransferRequestKind::quote_change, + ui::OutgoingTransferField::duration_years, uint32_t(months / 12)); + offer_editor_ = dispatch_offer(action).editor; + } + show_offer(); + }; + add({"Transfer", "BuyPlayer", {player}, "VER-KAUFEN on a market player: the offer editor", true}, + [open_offer](const Values& v) { open_offer(v.text("player"), false); }); + add({"Transfer", "HirePlayer", {player, integer("months", 12, 24, true)}, "VER-LEIHEN on a market player: the loan offer", true}, + [open_offer](const Values& v) { open_offer(v.text("player"), true, int(v.integer("months", 24))); }); + add({"Transfer.Negotiate", "ShowNegotiation", {}, "demand, quote and your offer", false}, [show_offer](const Values&) { show_offer(); }); + auto set_field = [this, offer_request, dispatch_offer, show_offer](int field, uint32_t value) { + if (!offer_editor_) fail("E_INTERNAL", "no offer editor"); + if (!offer_editor_->editable) fail("E_RULE", kNoBidSlot); + // a refused value must not stay in the editor: every later request posts the whole row + // and the engine would reject it as differing from its single field event + const auto before = *offer_editor_; + auto& e = *offer_editor_; + // the screen stores the edited value, then asks for a fresh quote (LAB_0001bad7); + // bonuses 4-7 are entered in steps of five and stored divided by five + const auto f = static_cast(field); + if (field == 0) e.fee = value; + else if (field == 1) e.monthly_salary = value; + else if (field == 2) e.duration_years = uint8_t(value); + else e.bonuses[size_t(field - 3)] = uint8_t(field >= 6 ? value / 5 : value); + try { + auto result = dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::quote_change, f, value)); + offer_editor_ = result.editor; + } catch (...) { + offer_editor_ = before; + throw; + } + }; + Param field = choice("field", kOfferFields); + add({"Transfer.Negotiate", "SetOfferField", {field, integer("value", 0, 100000000)}, "change one field (a fresh quote follows)", true}, + [set_field, show_offer](const Values& v) { + set_field(v.choice("field"), uint32_t(v.integer("value"))); + show_offer(); + }); + add({"Transfer.Negotiate", "SetOffer", + {integer("fee", 0, 100000000), integer("salary", 0, 10000000), integer("years", 1, 4), integer("bonusGoal", 0, 255), + integer("bonusPoints", 0, 255), integer("bonusAppearance", 0, 255), integer("bonusChampion", 0, 1275), + integer("bonus2to5", 0, 1275), integer("bonus6to10", 0, 1275), integer("bonusAvoidRelegation", 0, 1275)}, + "all ten fields", true}, + [set_field, show_offer](const Values& v) { + const char* names[10] = {"fee", "salary", "years", "bonusGoal", "bonusPoints", "bonusAppearance", "bonusChampion", + "bonus2to5", "bonus6to10", "bonusAvoidRelegation"}; + for (int i = 0; i < 10; ++i) set_field(i, uint32_t(v.integer(names[i]))); + show_offer(); + }); + // ANGEBOT; reruns itself when a poaching question was answered (see Questions) + auto submit = std::make_shared>(); + *submit = [this, offer_request, dispatch_offer, questions, notices, self = std::weak_ptr>(submit)] { + if (!offer_editor_) fail("E_INTERNAL", "no offer editor"); + if (!offer_editor_->editable) fail("E_RULE", kNoBidSlot); + questions->next = 0; + questions->pending.reset(); + std::optional answered; + try { + answered = dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::submit, ui::OutgoingTransferField::fee, + offer_editor_->fee)); + } catch (...) { + if (!questions->pending) throw; + notices->clear(); // the call was rolled back; its notices come again + const auto [manager, text] = *questions->pending; + const int previous = player_; + player_ = manager + 1; + ask(text, {"Yes", "No"}, "No", [this, questions, self, previous](const std::string& answer) { + player_ = previous; + questions->answers.push_back(answer == "Yes"); + if (const auto again = self.lock()) (*again)(); + }); + return; + } + questions->answers.clear(); + const auto& result = *answered; + // after a low offer the original keeps the editor open for a better one (the engine's + // owner stays); only a closed owner ends Transfer.Negotiate + if (result.editor.closed) { + offer_editor_.reset(); + close_window(); + } else { + offer_editor_ = result.editor; + } + const char* status = "submitted"; + switch (result.action.status) { + case TransferActionStatus::accepted: status = "accepted: the player moves to your club"; break; + case TransferActionStatus::pending: + status = "pending: the player decides in one of the next weeks"; + offer_submitted_ = true; + break; + case TransferActionStatus::rejected: status = "rejected"; break; + default: break; + } + emit('+', std::string("offer ") + status); + finish_loan_return_offer(); + }; + add({"Transfer.Negotiate", "SubmitOffer", {}, "ANGEBOT: hand in the offer", true}, [submit](const Values&) { (*submit)(); }); + closers_["Transfer.Negotiate"] = [this, offer_request, dispatch_offer] { + // closing the editor (right button) ends the negotiation screen only: a bid already + // handed in stays on the list until the player decides (Handbuch S. 60) + if (offer_editor_) dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::cancel, ui::OutgoingTransferField::fee, offer_editor_->fee)); + offer_editor_.reset(); + close_window(); + emit('+', offer_submitted_ ? "negotiation closed; your offer stands until the player decides" : "offer cancelled"); + offer_submitted_ = false; + finish_loan_return_offer(); + }; + // TEAM-INFO and SPIELER-INFO of the offer editor (OpenTransferEditor): modal screens the engine + // opens inside the editor event; the console prints them and closes them at once (the + // presenters return true), after which the editor is projected again. + add({"Transfer.Negotiate", "ShowTeamInfo", {}, "TEAM-INFO: your club's squad, as the editor shows it", false}, + [this, offer_request, dispatch_offer](const Values&) { + if (!offer_editor_) fail("E_INTERNAL", "no offer editor"); + auto presenter = [this](app::ClubModalServices& services, int club, const Image&) { + const ClubInfoEntry entry = services.enter_club(club); + const ui::ClubInfoProjection t = ui::club_info_from_game(services.state(), club, entry, exe_, texts_); + emit('i', utf8(t.original_club_name)); + std::vector> rows; + for (const auto& p : t.players) { + if (p.player_id < 0) continue; + const auto& a = p.attributes; + rows.push_back({"id:" + std::to_string(p.player_id), utf8(p.original_name), text(kPositionNames + a.position()), + std::to_string(a.age()), std::to_string(a.strength())}); + } + emit_table({"Id", "Player", "Pos", "Age", "Str"}, rows); + return true; + }; + const auto result = dispatch_offer( + offer_request(ui::OutgoingTransferRequestKind::team_info, ui::OutgoingTransferField::fee, offer_editor_->fee), presenter); + offer_editor_ = result.editor; + }); + add({"Transfer.Negotiate", "ShowPlayerInfo", {}, "SPIELER-INFO: the player's card with his market value", false}, + [this, offer_request, dispatch_offer](const Values&) { + if (!offer_editor_) fail("E_INTERNAL", "no offer editor"); + auto presenter = [this](app::ClubModalServices& services, const ClubPlayerDetailSelection& selection, const Image&) { + const ClubPlayerDetailRedraw card = services.redraw_player(selection); + const GameState& g = services.state(); + const Player& p = g.players.at(size_t(selection.player_id)); + emit_table({"Player", "Value"}, + {{"name", utf8(g.player_name(selection.player_id))}, + {"position", text(kPositionNames + p.position())}, + {"age", std::to_string(p.age())}, + {"condition", std::to_string(p.condition())}, + {"technique", std::to_string(p.technique())}, + {"form", std::to_string(p.form())}, + {"strength", std::to_string(p.strength())}, + {"marketValue", card.market_value ? money(*card.market_value) : "-"}}); + return true; + }; + const auto result = dispatch_offer( + offer_request(ui::OutgoingTransferRequestKind::player_info, ui::OutgoingTransferField::fee, offer_editor_->fee), {}, + presenter); + offer_editor_ = result.editor; + }); + + // --- Transfer.Poach: ABWERBEN (06-verein 5.6, src/game/poach.hpp) ---------------------- + add({"Transfer", "OpenPoach", {}, "ABWERBEN: pick a player of another club (Transfer.Poach)", false}, [this, market](const Values&) { + market(); + open_window("Transfer.Poach"); + emit('+', "poach: ListPoachClubs([league]), ListClubPlayers(club), PoachPlayer(player); " + + std::to_string(poach_attempts_left(session_->state(), active_slot())) + " attempts left this season"); + }); + add({"Transfer.Poach", "ListPoachClubs", {integer("league", 0, kLeagueCount - 1, true)}, "the clubs of a league (default: own)", false}, + [this](const Values& v) { + const ui::DeskState d = desk(); + const int league = v.has("league") ? int(v.integer("league")) : std::max(0, d.league); + const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), d.manager_slot, league); + std::vector> rows; + for (const auto& r : t.rows) + if (r.runtime_team_id != d.runtime_club) rows.push_back({"club:" + std::to_string(r.runtime_team_id), r.name}); + emit('i', t.league_name); + emit_table({"Club", "Name"}, rows); + }); + // the squad of a club (runtime id, as ListPoachClubs prints it) + auto club_squad = [this](const std::string& reference) { + std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference; + Arg a; + a.text = number; + const auto id = to_int(a); + if (!id || *id < 0 || *id >= 138) fail("E_BAD_ARGUMENT", "club is club: (ListPoachClubs)"); + return int(*id); + }; + Param club = detail::text("club"); + club.display = "club:Club"; + add({"Transfer.Poach", "ListClubPlayers", {club}, "the players of the club", false}, [this, club_squad](const Values& v) { + const int team = club_squad(v.text("club")); + const GameState& g = session_->state(); + const SquadRange range = squad_range(team); + std::vector> rows; + for (size_t s = range.first; s < range.first + range.count; ++s) { + const int p = g.squad_slots.at(s) & 0xfff; + if (p == 0xfff) continue; + const Player& pl = g.players.at(size_t(p)); + rows.push_back({"id:" + std::to_string(p), utf8(g.player_name(p)), text(kPositionNames + pl.position()), std::to_string(pl.age()), + std::to_string(pl.strength(true))}); + } + emit('i', utf8(g.club_name(team))); + emit_table({"Id", "Player", "Pos", "Age", "Str"}, rows); + }); + add({"Transfer.Poach", "PoachPlayer", {player}, "the offer to a player of another club (decided at once)", true}, + [this, show_offer](const Values& v) { + // id: of ListClubPlayers: his slot in a club squad + const std::string reference = v.text("player"); + Arg a; + a.text = lower(reference).rfind("id:", 0) == 0 ? reference.substr(3) : reference; + const auto id = to_int(a); + if (!id) fail("E_BAD_ARGUMENT", "player is id: (ListClubPlayers)"); + const GameState& g = session_->state(); + int slot = -1; + for (size_t s = 0; s < 0xb70 && slot < 0; ++s) + if ((g.squad_slots.at(s) & 0xfff) == *id) slot = int(s); + if (slot < 0) fail("E_BAD_ARGUMENT", "no club player id:" + std::to_string(*id)); + std::string error; + std::optional result; + try { + result = app::TransferActions(*session_).poach(active_slot(), slot, revision_, error); + } catch (const std::exception& e) { + fail("E_INTERNAL", std::string("poach: ") + e.what()); + } + if (!result) { + require_engine(false, "poach", error); + } + for (const auto& m : result->start.messages) emit('i', utf8(m)); + switch (result->start.status) { + case PoachStatus::ready: break; + case PoachStatus::invalid: fail("E_RULE", "not a player of another club"); + case PoachStatus::attempts_used: fail("E_RULE", "five poaching attempts this season"); + case PoachStatus::transfer_ban: fail("E_RULE", "transfer ban"); + default: fail("E_RULE", "the player cannot be poached"); + } + offer_editor_ = result->editor->editor; + offer_submitted_ = false; + open_window("Transfer.Negotiate"); + emit('+', "asking " + std::to_string(result->start.asking_percent) + " % of his value; SubmitOffer decides at once"); + show_offer(); + }); + + // the rest of the market (06-verein 5): later steps of stage 3 or engine gaps + for (const char* name : {"SetSquadView", "SetSquadSheet", "SetMarketVisible", "ShowPlayer", "OpenOffers", "OpenSearch", + "ShowTransferNews", "ShowTeamInfo"}) + add({"Transfer", name, {}, "not in the console yet", false}, + [name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " is not in the console yet"); }); +} + +} // namespace bmh::cli::console diff --git a/src/cli/json.cpp b/src/cli/json.cpp new file mode 100644 index 0000000..c179b67 --- /dev/null +++ b/src/cli/json.cpp @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "cli/json.hpp" + +#include +#include + +namespace bmh::cli { +namespace { + +void append_utf8(std::string& out, std::uint32_t cp) { + if (cp <= 0x7f) out += char(cp); + else if (cp <= 0x7ff) { + out += char(0xc0 | (cp >> 6)); out += char(0x80 | (cp & 0x3f)); + } else if (cp <= 0xffff) { + out += char(0xe0 | (cp >> 12)); out += char(0x80 | ((cp >> 6) & 0x3f)); out += char(0x80 | (cp & 0x3f)); + } else { + out += char(0xf0 | (cp >> 18)); out += char(0x80 | ((cp >> 12) & 0x3f)); + out += char(0x80 | ((cp >> 6) & 0x3f)); out += char(0x80 | (cp & 0x3f)); + } +} + +class Parser { +public: + explicit Parser(std::string_view source) : source_(source) {} + Json parse() { + skip_space(); + Json result = parse_value(); + skip_space(); + if (at_ != source_.size()) fail("trailing data"); + return result; + } +private: + std::string_view source_; + std::size_t at_ = 0; + [[noreturn]] void fail(std::string_view message) const { + throw JsonError(std::string(message) + " at byte " + std::to_string(at_)); + } + void skip_space() { + while (at_ < source_.size() && (source_[at_] == ' ' || source_[at_] == '\t' || source_[at_] == '\r' || source_[at_] == '\n')) ++at_; + } + bool take(char c) { + if (at_ < source_.size() && source_[at_] == c) { ++at_; return true; } + return false; + } + Json parse_value() { + if (at_ >= source_.size()) fail("expected value"); + switch (source_[at_]) { + case '{': return parse_object(); + case '[': return parse_array(); + case '"': return Json(parse_string()); + case 't': literal("true"); return Json(true); + case 'f': literal("false"); return Json(false); + case 'n': literal("null"); return Json(nullptr); + default: return Json(parse_integer()); + } + } + void literal(std::string_view word) { + if (source_.substr(at_, word.size()) != word) fail("invalid literal"); + at_ += word.size(); + } + int hex_digit(char c) const { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + } + std::uint32_t hex4() { + if (source_.size() - at_ < 4) fail("short unicode escape"); + std::uint32_t value = 0; + for (int i = 0; i < 4; ++i) { + const int digit = hex_digit(source_[at_++]); + if (digit < 0) fail("invalid unicode escape"); + value = (value << 4) | std::uint32_t(digit); + } + return value; + } + std::string parse_string() { + if (!take('"')) fail("expected string"); + std::string out; + while (at_ < source_.size()) { + const unsigned char c = static_cast(source_[at_++]); + if (c == '"') return out; + if (c < 0x20) fail("control character in string"); + if (c != '\\') { out += char(c); continue; } + if (at_ == source_.size()) fail("short escape"); + const char escaped = source_[at_++]; + switch (escaped) { + case '"': out += '"'; break; + case '\\': out += '\\'; break; + case '/': out += '/'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'n': out += '\n'; break; + case 'r': out += '\r'; break; + case 't': out += '\t'; break; + case 'u': { + std::uint32_t cp = hex4(); + if (cp >= 0xd800 && cp <= 0xdbff) { + if (source_.size() - at_ < 6 || source_[at_] != '\\' || source_[at_ + 1] != 'u') fail("missing low surrogate"); + at_ += 2; + const std::uint32_t low = hex4(); + if (low < 0xdc00 || low > 0xdfff) fail("invalid low surrogate"); + cp = 0x10000 + ((cp - 0xd800) << 10) + (low - 0xdc00); + } else if (cp >= 0xdc00 && cp <= 0xdfff) fail("unexpected low surrogate"); + append_utf8(out, cp); + break; + } + default: fail("invalid string escape"); + } + } + fail("unterminated string"); + } + std::int64_t parse_integer() { + const std::size_t start = at_; + take('-'); + if (at_ == source_.size()) fail("invalid integer"); + if (source_[at_] == '0') ++at_; + else { + if (source_[at_] < '1' || source_[at_] > '9') fail("expected integer"); + while (at_ < source_.size() && source_[at_] >= '0' && source_[at_] <= '9') ++at_; + } + if (at_ < source_.size() && (source_[at_] == '.' || source_[at_] == 'e' || source_[at_] == 'E')) fail("only integer numbers are supported"); + std::int64_t value{}; + const auto result = std::from_chars(source_.data() + start, source_.data() + at_, value); + if (result.ec != std::errc{} || result.ptr != source_.data() + at_) fail("integer out of range"); + return value; + } + Json parse_array() { + take('['); skip_space(); Json::Array values; + if (take(']')) return values; + for (;;) { + skip_space(); values.push_back(parse_value()); skip_space(); + if (take(']')) return values; + if (!take(',')) fail("expected comma in array"); + } + } + Json parse_object() { + take('{'); skip_space(); Json::Object values; + if (take('}')) return values; + for (;;) { + skip_space(); + if (at_ >= source_.size() || source_[at_] != '"') fail("expected object key"); + std::string key = parse_string(); skip_space(); + if (!take(':')) fail("expected colon"); + skip_space(); + if (!values.emplace(std::move(key), parse_value()).second) fail("duplicate object key"); + skip_space(); + if (take('}')) return values; + if (!take(',')) fail("expected comma in object"); + } + } +}; + +void quote(std::string& out, std::string_view value) { + static constexpr char hex[] = "0123456789abcdef"; + out += '"'; + for (unsigned char c : value) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { out += "\\u00"; out += hex[c >> 4]; out += hex[c & 15]; } + else out += char(c); + } + } + out += '"'; +} + +void dump(std::string& out, const Json& json) { + if (std::holds_alternative(json.value)) out += "null"; + else if (const auto* b = json.boolean()) out += *b ? "true" : "false"; + else if (const auto* n = json.integer()) out += std::to_string(*n); + else if (const auto* s = json.string()) quote(out, *s); + else if (const auto* a = json.array()) { + out += '['; + bool first = true; + for (const auto& item : *a) { if (!first) out += ','; first = false; dump(out, item); } + out += ']'; + } else { + out += '{'; bool first = true; + for (const auto& [key, item] : *json.object()) { + if (!first) out += ','; first = false; quote(out, key); out += ':'; dump(out, item); + } + out += '}'; + } +} + +} // namespace + +Json parse_json(std::string_view source) { return Parser(source).parse(); } +std::string dump_json(const Json& value) { std::string out; dump(out, value); return out; } + +} // namespace bmh::cli diff --git a/src/cli/json.hpp b/src/cli/json.hpp new file mode 100644 index 0000000..149f65b --- /dev/null +++ b/src/cli/json.hpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace bmh::cli { + +struct Json { + using Array = std::vector; + using Object = std::map>; + using Value = std::variant; + Value value = nullptr; + + Json() = default; + Json(std::nullptr_t) : value(nullptr) {} + Json(bool v) : value(v) {} + Json(std::int64_t v) : value(v) {} + Json(int v) : value(std::int64_t(v)) {} + Json(std::string v) : value(std::move(v)) {} + Json(const char* v) : value(std::string(v)) {} + Json(Array v) : value(std::move(v)) {} + Json(Object v) : value(std::move(v)) {} + + const Object* object() const { return std::get_if(&value); } + Object* object() { return std::get_if(&value); } + const Array* array() const { return std::get_if(&value); } + const std::string* string() const { return std::get_if(&value); } + const std::int64_t* integer() const { return std::get_if(&value); } + const bool* boolean() const { return std::get_if(&value); } +}; + +class JsonError final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +Json parse_json(std::string_view source); +std::string dump_json(const Json& value); + +} // namespace bmh::cli diff --git a/src/cli/main.cpp b/src/cli/main.cpp new file mode 100644 index 0000000..a1dfbac --- /dev/null +++ b/src/cli/main.cpp @@ -0,0 +1,769 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "cli/protocol.hpp" +#include "cli/console/console.hpp" +#include "cli/seat_hub.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "launch/archive.hpp" +#include "launch/game_data.hpp" +#include "version.hpp" + +namespace { +using namespace bmh::cli; +using Object = Json::Object; + +struct Arguments { + std::filesystem::path data, log, replay; + std::filesystem::path saves; // --saves: save directory of the console (default --data) + std::uint32_t seed = 1; + bool seed_set = false, json = false, help = false; + bool console = false; // --console: the console language of docs/CLI_CONCEPT + bool echo = false; // --echo: repeat each input line as "< line" (golden transcript format) + bool instant = false; // --time instant: matchdays run through (default stepped, 07-spieltag 3.2) + // --serve : the console session answers blocks dropped into a directory (agents); + // --send : hand one block to such a session and print its answer + std::filesystem::path serve, send; + int timeout_seconds = 300; // --timeout: how long --send waits for the answer + // --keep-going: a console replay reports differing blocks and goes on (re-checking a + // QA session after console texts changed) + bool keep_going = false; + int seats = 0; // --seats N: with --serve, one mailbox per human manager (several agents) + int listen_port = 0; // --listen : the console on 127.0.0.1: (front ends, stage 2.5) + // --resume : a --seats game starts by playing the blocks of an earlier session log + // again (seed, time mode and saves from its header) and goes on from there + std::filesystem::path resume; +}; + +std::uint32_t parse_seed(std::string_view value) { + int base = 10; + if (value.size() > 2 && value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) { base = 16; value.remove_prefix(2); } + std::uint32_t seed{}; + const auto result = std::from_chars(value.data(), value.data() + value.size(), seed, base); + if (result.ec != std::errc{} || result.ptr != value.data() + value.size()) throw std::runtime_error("invalid --seed"); + return seed; +} + +Arguments parse_args(int argc, char** argv) { + Arguments args; + const std::vector argv8 = bmh::launch::utf8_arguments(argc, argv); // (names beyond the code page) + for (size_t i = 1; i < argv8.size(); ++i) { + const std::string_view arg(argv8[i]); + auto next = [&](std::string_view name) -> std::string { + if (i + 1 >= argv8.size()) throw std::runtime_error("missing value for " + std::string(name)); + return argv8[++i]; + }; + if (arg == "--version") { + std::printf("OpenBMH console %s\n", bmh::kOpenBmhVersion); + std::exit(0); + } + if (arg == "--help" || arg == "-h") args.help = true; + else if (arg == "--data") args.data = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--seed") { args.seed = parse_seed(next(arg)); args.seed_set = true; } + else if (arg == "--text") args.json = false; + else if (arg == "--json") args.json = true; + else if (arg == "--log") args.log = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--replay") args.replay = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--console") args.console = true; + else if (arg == "--saves") args.saves = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--echo") args.echo = true; + else if (arg == "--keep-going") args.keep_going = true; + else if (arg == "--resume") args.resume = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--listen") { + args.listen_port = std::stoi(next(arg)); + if (args.listen_port < 1 || args.listen_port > 65535) throw std::runtime_error("--listen is a port 1-65535"); + } + else if (arg == "--seats") { + args.seats = std::stoi(next(arg)); + if (args.seats < 1 || args.seats > 4) throw std::runtime_error("--seats is 1-4"); + } + else if (arg == "--serve") args.serve = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--send") args.send = bmh::launch::path_from_utf8(next(arg)); + else if (arg == "--timeout") args.timeout_seconds = std::stoi(next(arg)); + else if (arg == "--time") { + const std::string mode = next(arg); + if (mode != "stepped" && mode != "instant") throw std::runtime_error("--time is stepped or instant"); + args.instant = mode == "instant"; + } + else throw std::runtime_error("unknown argument: " + std::string(arg)); + } + return args; +} + +void print_usage() { + std::cout << "openbmh_cli --data [--seed ] [--text|--json] [--log ]\n" + "openbmh_cli --replay [--data ] [--text|--json]\n" + "openbmh_cli --console --data [--saves ] [--seed ] [--text|--json] [--echo]\n" + " [--log|--replay [--keep-going]] [--serve | --listen ] [--seats N]\n" + " --listen: the console on 127.0.0.1:, line protocol (SEAT k with --seats; a block ends\n" + " with go., the answer with a line \".\"); --json gives structured lines, State(view) projections.\n" + " --seats N: one mailbox /seat per manager; a request \"WaitTurn\" waits for k's turn.\n" + " --resume : with --seats, first play an earlier session log again, then go on.\n" + "openbmh_cli --send [--timeout ] (the block on stdin)\n" + " --serve: the session answers blocks dropped into (request-N.txt -> response-N.txt);\n" + " --send hands one block to it and prints the answer - for agents that work in steps.\n" + " console language (docs/CLI_CONCEPT): command lines, executed by a line \"go.\";\n" + " ListOptions shows what is possible, Help the reference, Quit ends.\n" + "Commands: help, new, load, save, status, desk, kickoff, camp.*, bank.*, stadium.*, toto.submit, quit\n" + "Text: new [strength], load/save , kickoff, status, desk, quit\n"; +} + +std::string command_line_response(const Json& response) { + if (const Json* help = response.object() ? [&]() -> const Json* { + const auto it = response.object()->find("help"); return it == response.object()->end() ? nullptr : &it->second; + }() : nullptr) { + std::string result = "Commands (JSON: one object per line):\n"; + if (const auto* obj = help->object()) { + if (const auto it = obj->find("commands"); it != obj->end()) { + if (const auto* list = it->second.array()) for (const auto& command : *list) { + const auto c = command.object()->find("cmd"); + const auto p = command.object()->find("params"); + if (c != command.object()->end() && p != command.object()->end()) + result += " " + *c->second.string() + " — " + *p->second.string() + "\n"; + } + } + if (const auto it = obj->find("not_available"); it != obj->end()) { + result += "Unavailable until CareerSession adapters exist:"; + if (const auto* list = it->second.array()) for (const auto& value : *list) result += " " + *value.string(); + result += "\n"; + } + } + return result; + } + return text_response(response); +} + +Json protocol_error(std::string detail, std::uint64_t revision) { + return Json(Object{{"ok", false}, {"error", "invalid_request"}, {"detail", std::move(detail)}, + {"revision", static_cast(revision)}}); +} + +int run_replay(Arguments args) { + std::ifstream input(args.replay); + if (!input) throw std::runtime_error("cannot_read_replay_log"); + std::string line; + if (!std::getline(input, line)) throw std::runtime_error("empty_replay_log"); + const Json header = parse_json(line); + if (!header.object()) throw std::runtime_error("invalid_replay_header"); + const auto type = header.object()->find("type"); + const auto data = header.object()->find("data"); + const auto seed = header.object()->find("seed"); + if (type == header.object()->end() || !type->second.string() || *type->second.string() != "openbmh_cli_log" || + data == header.object()->end() || !data->second.string() || seed == header.object()->end() || !seed->second.integer()) + throw std::runtime_error("invalid_replay_header"); + const auto protocol_version = header.object()->find("protocol"); + if (protocol_version == header.object()->end() || !protocol_version->second.integer() || *protocol_version->second.integer() != 1) + throw std::runtime_error("unsupported_replay_protocol"); + if (args.data.empty()) args.data = bmh::launch::path_from_utf8(*data->second.string()); + if (args.seed_set && args.seed != static_cast(*seed->second.integer())) + throw std::runtime_error("replay_seed_mismatch"); + args.seed = static_cast(*seed->second.integer()); + bmh::cli::Protocol protocol(args.data, args.seed); + std::size_t index = 0; + while (std::getline(input, line)) { + if (line.empty()) continue; + ++index; + const Json record = parse_json(line); + if (!record.object()) throw std::runtime_error("invalid_replay_record:" + std::to_string(index)); + const auto req = record.object()->find("request"), expected = record.object()->find("response"); + if (req == record.object()->end() || expected == record.object()->end()) + throw std::runtime_error("invalid_replay_record:" + std::to_string(index)); + const Json actual = protocol.handle(req->second, true); + if (dump_json(actual) != dump_json(expected->second)) + throw std::runtime_error("replay_mismatch_at_record:" + std::to_string(index)); + std::cout << (args.json ? dump_json(actual) : command_line_response(actual)) << '\n'; + const auto quit = actual.object()->find("quit"); + if (quit != actual.object()->end() && quit->second.boolean() && *quit->second.boolean()) break; + } + return 0; +} + +// --- console mode (docs/CLI_CONCEPT) ------------------------------------------------------ +// Log format (JSONL): a header {"type":"openbmh_console_log","data","seed","json","time"}, then one +// entry per executed block {"input":[lines],"output":[lines]}; the first entry is the start +// output with no input. --replay feeds the inputs again (plus "go.") and stops at the first +// block whose output differs - the console draws no random numbers, so a replay is exact. + +Json string_array(const std::vector& lines) { + Json::Array a; + for (const auto& l : lines) a.emplace_back(l); + return Json(std::move(a)); +} + +std::vector strings_of(const Json& value) { + std::vector result; + if (const auto* a = value.array()) + for (const auto& v : *a) + if (const auto* s = v.string()) result.push_back(*s); + return result; +} + +bmh::cli::console::Options console_options(const Arguments& args) { + bmh::cli::console::Options o; + o.data = args.data; + o.save_directory = args.saves; + o.seed = args.seed; + o.json = args.json; + o.time = args.instant ? bmh::cli::console::TimeMode::instant : bmh::cli::console::TimeMode::stepped; + return o; +} + +int run_console_replay(Arguments args) { + std::ifstream input(args.replay); + if (!input) throw std::runtime_error("cannot_read_replay_log"); + std::string line; + if (!std::getline(input, line)) throw std::runtime_error("empty_replay_log"); + const Json header = parse_json(line); + const auto* h = header.object(); + if (!h || !h->count("type") || !h->at("type").string() || *h->at("type").string() != "openbmh_console_log") + throw std::runtime_error("invalid_replay_header"); + if (args.data.empty()) args.data = bmh::launch::path_from_utf8(*h->at("data").string()); + if (h->count("saves") && h->at("saves").string() && args.saves.empty()) args.saves = bmh::launch::path_from_utf8(*h->at("saves").string()); + args.seed = static_cast(*h->at("seed").integer()); + args.json = h->count("json") && h->at("json").boolean() && *h->at("json").boolean(); + // the time mode changes how far Kickoff runs; logs before the "time" field need --time + if (h->count("time") && h->at("time").string()) args.instant = *h->at("time").string() == "instant"; + + bmh::cli::console::Console console(console_options(args), [](const std::string& out) { std::cout << out << '\n'; }); + console.start(); + std::size_t index = 0, mismatches = 0; + while (std::getline(input, line)) { + if (line.empty()) continue; + const Json record = parse_json(line); + if (!record.object() || !record.object()->count("output")) throw std::runtime_error("invalid_replay_record:" + std::to_string(index)); + const auto expected = strings_of(record.object()->at("output")); + if (index > 0) { // entry 0 is the start output + for (const auto& in : strings_of(record.object()->at("input"))) console.feed(in); + console.feed("go."); + } + if (console.last_output() != expected) { + if (!args.keep_going) throw std::runtime_error("replay_mismatch_at_block:" + std::to_string(index)); + std::cerr << "openbmh_cli: block " << index << " differs\n"; + ++mismatches; + } + ++index; + } + std::cerr << "openbmh_cli: replay " << (mismatches ? "done" : "ok") << ", " << index << " blocks, " << mismatches + << " differ\n"; + return mismatches ? 1 : 0; +} + +int run_console(const Arguments& args) { + if (args.data.empty()) throw std::runtime_error("--data is required"); + std::ofstream log; + if (!args.log.empty()) { + log.open(args.log, std::ios::binary | std::ios::trunc); + if (!log) throw std::runtime_error("cannot_open_log"); + Object header{{"type", "openbmh_console_log"}, {"version", 1}, + {"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())}, + {"seed", static_cast(args.seed)}, {"json", args.json}, + {"time", std::string(args.instant ? "instant" : "stepped")}}; + if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal()); + log << dump_json(Json(std::move(header))) << '\n'; + } + auto write_entry = [&](const bmh::cli::console::Console& c) { + if (!log.is_open()) return; + log << dump_json(Json(Object{{"input", string_array(c.last_block())}, {"output", string_array(c.last_output())}})) << '\n'; + log.flush(); + if (!log) throw std::runtime_error("log_write_failed"); + }; + bmh::cli::console::Console console(console_options(args), [](const std::string& out) { std::cout << out << '\n' << std::flush; }); + console.start(); + write_entry(console); + std::string line; + while (!console.ended() && std::getline(std::cin, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (args.echo) std::cout << "< " << line << '\n'; + const bool executes = bmh::cli::console::classify_line(line) == bmh::cli::console::LineKind::go; + console.feed(line); + if (executes) write_entry(console); + } + return 0; +} + +// --- the directory mailbox for agents (--serve / --send) --------------------------------- +// A session started with --serve keeps running; each block is a file request-N.txt (N = 1, +// 2, ...) whose lines are fed to the console (a final "go." is added when missing); the +// output lines go to response-N.txt, written under a temporary name and renamed, so a +// reader never sees half a file. response-0.txt holds the start output. The session ends +// with Quit or a file named "stop". --send writes the next request and waits for its +// response. Plain files work the same on Windows, Linux and macOS and need no port. + +std::filesystem::path mailbox_file(const std::filesystem::path& dir, const char* kind, long n) { + return dir / (std::string(kind) + "-" + std::to_string(n) + ".txt"); +} + +void write_atomic(const std::filesystem::path& file, const std::vector& lines) { + const std::filesystem::path temp = file.string() + ".tmp"; + { + std::ofstream out(temp, std::ios::binary | std::ios::trunc); + for (const auto& l : lines) out << l << "\n"; + if (!out) throw std::runtime_error("cannot write " + temp.string()); + } + std::filesystem::rename(temp, file); +} + +int run_console_serve(const Arguments& args) { + if (args.data.empty()) throw std::runtime_error("--data is required"); + std::filesystem::create_directories(args.serve); + std::ofstream log; + if (!args.log.empty()) { + log.open(args.log, std::ios::binary | std::ios::trunc); + if (!log) throw std::runtime_error("cannot_open_log"); + Object header{{"type", "openbmh_console_log"}, {"version", 1}, + {"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())}, + {"seed", static_cast(args.seed)}, {"json", args.json}, + {"time", std::string(args.instant ? "instant" : "stepped")}}; + if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal()); + log << dump_json(Json(std::move(header))) << '\n'; + } + std::vector out; + bmh::cli::console::Console console(console_options(args), [&out](const std::string& line) { out.push_back(line); }); + console.start(); + if (log.is_open()) + log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}})) << '\n' << std::flush; + write_atomic(mailbox_file(args.serve, "response", 0), out); + for (long n = 1; !console.ended();) { + std::error_code ec; + if (std::filesystem::exists(args.serve / "stop", ec)) break; + const auto request = mailbox_file(args.serve, "request", n); + if (!std::filesystem::exists(request, ec)) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + continue; + } + std::vector lines; + { + std::ifstream in(request, std::ios::binary); + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + lines.push_back(line); + } + } + std::filesystem::remove(request, ec); + while (!lines.empty() && lines.back().find_first_not_of(" \t") == std::string::npos) lines.pop_back(); + if (lines.empty() || bmh::cli::console::classify_line(lines.back()) != bmh::cli::console::LineKind::go) lines.push_back("go."); + out.clear(); + for (const auto& l : lines) { + const bool executes = bmh::cli::console::classify_line(l) == bmh::cli::console::LineKind::go; + console.feed(l); + if (executes && log.is_open()) + log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}})) << '\n' << std::flush; + if (console.ended()) break; + } + write_atomic(mailbox_file(args.serve, "response", n), out); + ++n; + } + return 0; +} + +// --- several agents in one game (--serve --seats N) --------------------------------- +// Every human manager k gets a mailbox /seat that works like the single one +// (request-N.txt -> response-N.txt, response-0.txt = start output). What a seat may do and +// what it sees (its own manager only, the meanwhile part, WaitTurn) is the seat hub's +// (src/cli/seat_hub.hpp), shared with --listen. The log holds the blocks as executed (with +// @k), so --replay plays the game again. + +namespace { + +std::vector read_request(const std::filesystem::path& file) { + std::vector lines; + { + std::ifstream in(file, std::ios::binary); + for (std::string line; std::getline(in, line);) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + lines.push_back(line); + } + } + std::error_code ec; + std::filesystem::remove(file, ec); + while (!lines.empty() && lines.back().find_first_not_of(" \t") == std::string::npos) lines.pop_back(); + return lines; +} + +std::string trimmed(const std::string& s) { + const size_t a = s.find_first_not_of(" \t"); + if (a == std::string::npos) return {}; + return s.substr(a, s.find_last_not_of(" \t") - a + 1); +} + +} // namespace + +// The session log of a hub game: the header, then every executed block (as --log). +std::function hub_log(std::ofstream& log, const Arguments& args) { + if (!args.log.empty()) { + log.open(args.log, std::ios::binary | std::ios::trunc); + if (!log) throw std::runtime_error("cannot_open_log"); + Object header{{"type", "openbmh_console_log"}, {"version", 1}, + {"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())}, + {"seed", static_cast(args.seed)}, {"json", args.json}, + {"time", std::string(args.instant ? "instant" : "stepped")}, {"seats", args.seats}}; + if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal()); + log << dump_json(Json(std::move(header))) << '\n'; + } + return [&log](const bmh::cli::console::Console& console) { + if (log.is_open()) + log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}})) + << '\n' << std::flush; + }; +} + +// --serve --seats N: the seat hub (src/cli/seat_hub.hpp) behind one mailbox per seat. +int run_console_seats(Arguments args) { + // --resume: the earlier log's header decides seed, time mode and saves (as --replay) + std::ifstream resume; + if (!args.resume.empty()) { + resume.open(args.resume, std::ios::binary); + std::string line; + if (!resume || !std::getline(resume, line)) throw std::runtime_error("cannot_read_resume_log"); + const Json header = parse_json(line); + const auto* h = header.object(); + if (!h || !h->count("type") || !h->at("type").string() || *h->at("type").string() != "openbmh_console_log") + throw std::runtime_error("invalid_resume_header"); + args.seed = static_cast(*h->at("seed").integer()); + if (h->count("time") && h->at("time").string()) args.instant = *h->at("time").string() == "instant"; + if (h->count("saves") && h->at("saves").string() && args.saves.empty()) args.saves = bmh::launch::path_from_utf8(*h->at("saves").string()); + if (args.resume == args.log) throw std::runtime_error("--resume and --log must be different files"); + } + if (args.data.empty()) throw std::runtime_error("--data is required"); + std::ofstream log; + bmh::cli::SeatHub hub(console_options(args), args.seats, hub_log(log, args)); + if (resume.is_open()) { + std::size_t index = 0, differ = 0; + for (std::string line; std::getline(resume, line);) { + if (line.empty()) continue; + const Json record = parse_json(line); + if (!record.object() || !record.object()->count("output")) throw std::runtime_error("invalid_resume_record"); + if (index++ == 0) continue; // the start output + if (!hub.replay(strings_of(record.object()->at("input")), strings_of(record.object()->at("output")))) ++differ; + } + std::cerr << "openbmh_cli: resumed " << index << " blocks, " << differ << " differ\n"; + } + struct Seat { + std::filesystem::path dir; + long next = 1; // the request number expected next + long waiting = 0; // a held WaitTurn request (its number), 0 = none + }; + std::vector seats(size_t(args.seats)); + for (size_t k = 0; k < seats.size(); ++k) { + seats[k].dir = args.serve / ("seat" + std::to_string(k + 1)); + std::filesystem::create_directories(seats[k].dir); + write_atomic(mailbox_file(seats[k].dir, "response", 0), hub.start_output()); + } + auto deliver = [&](int seat, long n, const std::vector& lines) { + write_atomic(mailbox_file(seats[size_t(seat - 1)].dir, "response", n), lines); + std::error_code gone; + std::filesystem::remove(mailbox_file(seats[size_t(seat - 1)].dir, "request", n), gone); // (a held WaitTurn) + }; + auto release = [&] { + for (auto& [seat, lines] : hub.release()) { + deliver(seat, seats[size_t(seat - 1)].waiting, lines); + seats[size_t(seat - 1)].waiting = 0; + } + }; + std::error_code ec; + while (!hub.ended() && !std::filesystem::exists(args.serve / "stop", ec)) { + bool worked = false; + for (size_t k = 0; k < seats.size() && !hub.ended(); ++k) { + Seat& seat = seats[k]; + if (seat.waiting) continue; // one request at a time per seat + const auto request = mailbox_file(seat.dir, "request", seat.next); + if (!std::filesystem::exists(request, ec)) continue; + worked = true; + const long n = seat.next++; + auto answer = hub.submit(int(k) + 1, read_request(request)); + if (answer) { + deliver(int(k) + 1, n, *answer); + } else { + // the request file stays until the answer: --send numbers the next request + // after the highest request or response it finds + write_atomic(request, {"WaitTurn"}); + seat.waiting = n; + } + release(); + } + if (!worked) std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + release(); // the session is over: every held WaitTurn gets its answer + return 0; +} + +// --- the socket access for front ends (--listen , stage 2.5) ----------------------- +// A TCP server on 127.0.0.1 (local connections only) in front of the seat hub. Line based, +// UTF-8, "\n" or "\r\n": +// - On connecting with --seats N the client names its manager: "SEAT "; without --seats it +// is seat 1 at once. The server answers with the start output (Window/Player lines). +// - Every block of command lines up to "go." is executed; the answer is its output lines and +// then a line holding only "." (output lines are never just "."). With --json each output +// line is one JSON object (class, window, player, text, data - see State(view)). +// - A block holding only "WaitTurn" is answered when the seat is on turn (SeatHub). +// - A seat is one connection at a time; a client that goes away loses a held WaitTurn. +// The session ends with Quit; the log (--log) replays it like any other. +#ifdef _WIN32 +using socket_t = SOCKET; +constexpr socket_t kNoSocket = INVALID_SOCKET; +void close_socket(socket_t s) { closesocket(s); } +#else +using socket_t = int; +constexpr socket_t kNoSocket = -1; +void close_socket(socket_t s) { close(s); } +#endif + +int run_console_listen(const Arguments& args) { + if (args.data.empty()) throw std::runtime_error("--data is required"); +#ifdef _WIN32 + WSADATA wsa; + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) throw std::runtime_error("cannot start Winsock"); +#endif + const int seat_count = args.seats > 0 ? args.seats : 1; + std::ofstream log; + Arguments hub_args = args; + hub_args.seats = seat_count; + bmh::cli::SeatHub hub(console_options(args), seat_count, hub_log(log, hub_args)); + + socket_t server = socket(AF_INET, SOCK_STREAM, 0); + if (server == kNoSocket) throw std::runtime_error("cannot open a socket"); + int yes = 1; + setsockopt(server, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&yes), sizeof yes); + sockaddr_in address{}; + address.sin_family = AF_INET; + address.sin_port = htons(static_cast(args.listen_port)); + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // local connections only + if (bind(server, reinterpret_cast(&address), sizeof address) != 0 || listen(server, 8) != 0) + throw std::runtime_error("cannot listen on 127.0.0.1:" + std::to_string(args.listen_port)); + std::cerr << "openbmh_cli: listening on 127.0.0.1:" << args.listen_port << " (" << seat_count << " seat" + << (seat_count > 1 ? "s" : "") << ")\n"; + + struct Client { + socket_t socket = kNoSocket; + std::string input; // received, not yet a full line + int seat = 0; // 0 = not seated yet + std::vector block; // command lines up to "go." + bool held = false; // a WaitTurn is held for it + }; + std::vector clients; + auto send_lines = [](Client& c, const std::vector& lines) { + std::string text; + for (const auto& l : lines) text += l + "\n"; + text += ".\n"; + size_t sent = 0; + while (sent < text.size()) { + const int n = int(send(c.socket, text.data() + sent, int(text.size() - sent), 0)); + if (n <= 0) return; + sent += size_t(n); + } + }; + auto seat_taken = [&](int seat) { + for (const auto& c : clients) if (c.seat == seat) return true; + return false; + }; + auto release = [&] { + for (auto& [seat, lines] : hub.release()) + for (auto& c : clients) + if (c.seat == seat && c.held) { + send_lines(c, lines); + c.held = false; + } + }; + auto on_line = [&](Client& c, std::string line) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (c.seat == 0) { + int seat = seat_count == 1 ? 1 : 0; + if (seat == 0 && line.rfind("SEAT ", 0) == 0) seat = std::atoi(line.c_str() + 5); + if (seat < 1 || seat > seat_count) { + send_lines(c, {"! E_BAD_ARGUMENT: first line SEAT <1-" + std::to_string(seat_count) + ">"}); + return; + } + if (seat_taken(seat)) { + send_lines(c, {"! E_BAD_ARGUMENT: seat " + std::to_string(seat) + " is connected already"}); + return; + } + c.seat = seat; + send_lines(c, hub.start_output()); + return; + } + if (c.held) { + send_lines(c, {"! E_BAD_ARGUMENT: a WaitTurn is pending for this seat"}); + return; + } + c.block.push_back(line); + if (bmh::cli::console::classify_line(line) != bmh::cli::console::LineKind::go) return; + auto answer = hub.submit(c.seat, std::move(c.block)); + c.block.clear(); + if (answer) send_lines(c, *answer); + else c.held = true; + release(); + }; + + while (!hub.ended()) { + fd_set readable; + FD_ZERO(&readable); + FD_SET(server, &readable); + socket_t top = server; + for (const auto& c : clients) { + FD_SET(c.socket, &readable); + if (c.socket > top) top = c.socket; + } + timeval wait{0, 100000}; + if (select(int(top + 1), &readable, nullptr, nullptr, &wait) < 0) break; + if (FD_ISSET(server, &readable)) { + const socket_t s = accept(server, nullptr, nullptr); + if (s != kNoSocket) { + clients.push_back(Client{s}); + if (seat_count == 1 && !seat_taken(1)) { // one seat: no SEAT line needed + clients.back().seat = 1; + send_lines(clients.back(), hub.start_output()); + } else if (seat_count == 1) { + send_lines(clients.back(), {"! E_BAD_ARGUMENT: seat 1 is connected already"}); + } + } + } + for (size_t i = 0; i < clients.size() && !hub.ended();) { + Client& c = clients[i]; + if (!FD_ISSET(c.socket, &readable)) { ++i; continue; } + char buffer[4096]; + const int n = int(recv(c.socket, buffer, sizeof buffer, 0)); + if (n <= 0) { // gone + if (c.held) hub.forget(c.seat); + close_socket(c.socket); + clients.erase(clients.begin() + std::ptrdiff_t(i)); + continue; + } + c.input.append(buffer, size_t(n)); + for (size_t nl; (nl = c.input.find('\n')) != std::string::npos;) { + std::string line = c.input.substr(0, nl); + c.input.erase(0, nl + 1); + on_line(c, std::move(line)); + } + ++i; + } + } + release(); // the session ended: held WaitTurns get their answer + for (auto& c : clients) close_socket(c.socket); + close_socket(server); +#ifdef _WIN32 + WSACleanup(); +#endif + return 0; +} + +int run_send(const Arguments& args) { + // the next number: one above the highest request or response there + long n = 0; + std::error_code ec; + for (const auto& e : std::filesystem::directory_iterator(args.send, ec)) { + const std::string name = e.path().filename().string(); + for (const char* prefix : {"request-", "response-"}) { + const std::string p = prefix; + if (name.rfind(p, 0) == 0 && name.size() > p.size() + 4 && name.compare(name.size() - 4, 4, ".txt") == 0) + n = std::max(n, std::atol(name.substr(p.size(), name.size() - p.size() - 4).c_str())); + } + } + if (ec) throw std::runtime_error("no session directory: " + args.send.string()); + ++n; + std::vector lines; + for (std::string line; std::getline(std::cin, line);) lines.push_back(line); + write_atomic(mailbox_file(args.send, "request", n), lines); + const auto response = mailbox_file(args.send, "response", n); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(args.timeout_seconds); + while (!std::filesystem::exists(response, ec)) { + if (std::chrono::steady_clock::now() > deadline) { + std::cerr << "openbmh_cli: no answer from the session in " << args.timeout_seconds << " s\n"; + return 3; + } + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + std::ifstream in(response, std::ios::binary); + std::cout << in.rdbuf(); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + try { + Arguments args = parse_args(argc, argv); + if (args.help) { print_usage(); return 0; } + if (!args.send.empty()) return run_send(args); + // --data may also name BMH.EXE or a ZIP/7z archive with one game (src/launch); an + // archive is unpacked into the per-user cache and its copy is used + if (!args.data.empty()) { + const auto game = bmh::launch::resolve_game(args.data, bmh::launch::default_cache_directory()); + if (!game.error.empty() || !game.check.playable) + throw std::runtime_error("the game cannot be used:\n" + bmh::launch::describe(game)); + args.data = game.check.directory; + } + if (args.console) { + if (!args.log.empty() && !args.replay.empty()) throw std::runtime_error("--log and --replay cannot be combined"); + if (args.listen_port) return run_console_listen(args); + if (!args.serve.empty()) return args.seats > 0 ? run_console_seats(args) : run_console_serve(args); + return args.replay.empty() ? run_console(args) : run_console_replay(std::move(args)); + } + if (!args.replay.empty()) { + if (!args.log.empty()) throw std::runtime_error("--log and --replay cannot be combined"); + return run_replay(std::move(args)); + } + if (args.data.empty()) throw std::runtime_error("--data is required unless --replay supplies it"); + std::ofstream log; + if (!args.log.empty()) { + log.open(args.log, std::ios::binary | std::ios::trunc); + if (!log) throw std::runtime_error("cannot_open_log"); + const auto abs_data = bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal()); + log << dump_json(Json(Object{{"type", "openbmh_cli_log"}, {"protocol", 1}, + {"data", abs_data}, {"seed", static_cast(args.seed)}})) << '\n'; + } + Protocol protocol(args.data, args.seed); + std::string line; + while (std::getline(std::cin, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + Json request; + Json response; + try { + request = args.json ? parse_json(line) : text_request(line, &protocol); + response = protocol.handle(request); + } catch (const std::exception& error) { + request = Json(Object{{"cmd", "__protocol_error"}, {"detail", error.what()}}); + response = protocol_error(error.what(), protocol.revision()); + } + if (log.is_open()) { + log << dump_json(Json(Object{{"request", request}, {"response", response}})) << '\n'; + log.flush(); + if (!log) throw std::runtime_error("log_write_failed"); + } + std::cout << (args.json ? dump_json(response) : command_line_response(response)) << '\n'; + if (const auto* object = response.object()) { + const auto it = object->find("quit"); + if (it != object->end() && it->second.boolean() && *it->second.boolean()) break; + } + } + return 0; + } catch (const std::exception& error) { + std::cerr << "openbmh_cli: " << error.what() << '\n'; + return 2; + } +} diff --git a/src/cli/protocol.cpp b/src/cli/protocol.cpp new file mode 100644 index 0000000..a2fec6d --- /dev/null +++ b/src/cli/protocol.cpp @@ -0,0 +1,744 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "cli/protocol.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "app/career_session.hpp" +#include "formats/m3d.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "ui/bank.hpp" +#include "ui/desktop.hpp" +#include "ui/league_table.hpp" +#include "ui/manager.hpp" +#include "ui/mailbox_state.hpp" +#include "ui/stadium.hpp" +#include "ui/toto.hpp" +#include "ui/training.hpp" +#include "ui/training_camp.hpp" +#include "ui/tactics.hpp" + +namespace bmh::cli { +namespace { +using Object = Json::Object; +using Array = Json::Array; + +const Json* find(const Json& value, std::string_view key) { + const auto* object = value.object(); + if (!object) return nullptr; + const auto it = object->find(key); + return it == object->end() ? nullptr : &it->second; +} + +std::string string(const Json& value, std::string_view name) { + const auto* v = value.string(); + if (!v) throw JsonError("field_must_be_string:" + std::string(name)); + return *v; +} + +std::int64_t integer(const Json& value, std::string_view name) { + const auto* v = value.integer(); + if (!v) throw JsonError("field_must_be_integer:" + std::string(name)); + return *v; +} + +bool boolean(const Json& value, std::string_view name) { + const auto* v = value.boolean(); + if (!v) throw JsonError("field_must_be_boolean:" + std::string(name)); + return *v; +} + +const Json& required(const Json& value, std::string_view key) { + const auto* found = find(value, key); + if (!found) throw JsonError("missing_field:" + std::string(key)); + return *found; +} + +std::int64_t optional_integer(const Json& value, std::string_view key, std::int64_t fallback) { + const auto* found = find(value, key); + return found ? integer(*found, key) : fallback; +} + +std::string optional_string(const Json& value, std::string_view key, std::string fallback = {}) { + const auto* found = find(value, key); + return found ? string(*found, key) : std::move(fallback); +} + +bool optional_boolean(const Json& value, std::string_view key, bool fallback) { + const auto* found = find(value, key); + return found ? boolean(*found, key) : fallback; +} + +int bounded_int(std::int64_t value, std::string_view field, int low, int high) { + if (value < low || value > high) throw JsonError("out_of_range:" + std::string(field)); + return static_cast(value); +} + +std::uint64_t bounded_u64(std::int64_t value, std::string_view field) { + if (value < 0) throw JsonError("out_of_range:" + std::string(field)); + return static_cast(value); +} + +void check_keys(const Json& value, std::initializer_list allowed) { + const auto* object = value.object(); + if (!object) throw JsonError("request_must_be_object"); + for (const auto& [key, unused] : *object) { + (void)unused; + if (std::find(allowed.begin(), allowed.end(), key) == allowed.end()) + throw JsonError("unknown_field:" + key); + } +} + +void check_command_keys(const Json& value, std::string_view cmd) { + std::vector allowed; + if (cmd == "__protocol_error") allowed = {"cmd", "detail"}; + else if (cmd == "new") allowed = {"cmd", "options", "managers"}; + else if (cmd == "load") allowed = {"cmd", "path"}; + else if (cmd == "save") allowed = {"cmd", "manager", "revision", "path", "overwrite"}; + else if (cmd == "kickoff") allowed = {"cmd", "manager", "revision"}; + else if (cmd == "table") allowed = {"cmd", "manager", "league"}; + else if (cmd == "mail") allowed = {"cmd", "manager"}; + else if (cmd == "tactics.set") allowed = {"cmd", "manager", "revision", "index", "value"}; + else if (cmd == "training.initialize") allowed = {"cmd", "manager", "revision"}; + else if (cmd == "training.type" || cmd == "training.area" || cmd == "training.auto") + allowed = {"cmd", "manager", "revision", "index", "value"}; + else if (cmd == "training.intensity") allowed = {"cmd", "manager", "revision", "row", "value"}; + else if (cmd == "training.focus") allowed = {"cmd", "manager", "revision", "row"}; + else if (cmd == "camp.focus") allowed = {"cmd", "manager", "revision", "focus"}; + else if (cmd == "camp.book") allowed = {"cmd", "manager", "revision", "resort"}; + else if (cmd == "bank.deposit" || cmd == "bank.withdraw") allowed = {"cmd", "manager", "revision", "amount"}; + else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip") + allowed = {"cmd", "manager", "revision", "asset", "count"}; + else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell") + allowed = {"cmd", "manager", "revision", "asset", "count"}; + else if (cmd == "stadium.open") allowed = {"cmd", "manager", "revision"}; + else if (cmd == "stadium.offer") allowed = {"cmd", "manager", "revision", "object"}; + else if (cmd == "stadium.build" || cmd == "stadium.decline") + allowed = {"cmd", "manager", "revision", "object", "price"}; + else if (cmd == "toto.submit") allowed = {"cmd", "manager", "revision", "stake", "tips"}; + else allowed = {"cmd"}; + const auto* object = value.object(); + for (const auto& [key, unused] : *object) { + (void)unused; + if (std::find(allowed.begin(), allowed.end(), key) == allowed.end()) + throw JsonError("unknown_field_for_command:" + key); + } +} + +Json raw_json(std::string value) { return parse_json(value); } + +Json failed(std::string code, std::uint64_t revision, std::string detail = {}) { + Object out{{"ok", false}, {"error", std::move(code)}, {"revision", Json(static_cast(revision))}}; + if (!detail.empty()) out.emplace("detail", std::move(detail)); + return out; +} + +Json successful(std::uint64_t revision, Object extra = {}) { + extra.emplace("ok", true); + extra.emplace("revision", Json(static_cast(revision))); + return extra; +} + +Json state_response(const ui::DeskState& desk, std::string_view view, Json state) { + return Object{{"view", std::string(view)}, {"state", std::move(state)}}; +} + +Json tactics_state(const ui::TacticsState& state) { + Array values, depth, lane; + for (auto value : state.values) values.emplace_back(int(value)); + for (auto value : state.depth) depth.emplace_back(int(value)); + for (auto value : state.lane) lane.emplace_back(int(value)); + return Object{{"manager_slot", state.manager_slot}, {"runtime_club", state.runtime_club}, + {"revision", static_cast(state.revision)}, {"source", state.source}, + {"club_name", ui::original_to_utf8(state.club_name)}, + {"assistant_attitude", int(state.assistant_attitude)}, {"live_scene_option", state.live_scene_option}, + {"values", std::move(values)}, {"depth", std::move(depth)}, {"lane", std::move(lane)}}; +} + +// The desk projection as JSON. ui::desk_json marks it "engine_attached":false (the SDL flow +// sets the flag once a career is attached); every protocol desk comes from the engine. +Json desk_state_json(const ui::DeskState& desk) { + Json result = raw_json(ui::desk_json(desk)); + result.object()->insert_or_assign("engine_attached", true); + return result; +} + +Json training_state(const ui::TrainingState& state) { + Json result = raw_json(ui::training_json(state)); + result.object()->insert_or_assign("engine_attached", true); + return result; +} + +Json result_state(const app::CareerSession& session) { + const auto& results = session.completed_matchday_results(); + if (!results) return Object{{"valid", false}, {"groups", Array{}}}; + Array groups; + for (const auto& group : results->groups) { + Array matches; + for (const auto& match : group.matches) { + const char* status = "unknown"; + switch (match.status) { + case ui::MatchResultStatus::played: status = "played"; break; + case ui::MatchResultStatus::postponed: status = "postponed"; break; + case ui::MatchResultStatus::not_played: status = "not_played"; break; + case ui::MatchResultStatus::unknown: break; + } + Object entry{{"home", match.home}, {"away", match.away}, {"status", status}, + {"home_goals", match.home_goals ? Json(*match.home_goals) : Json(nullptr)}, + {"away_goals", match.away_goals ? Json(*match.away_goals) : Json(nullptr)}}; + // cup: "regular", "extra_time" or "penalties" (the score then includes the shoot-out) + if (group.cup) entry["decided"] = std::string(match.decided == 2 ? "penalties" : match.decided == 1 ? "extra_time" : "regular"); + matches.emplace_back(std::move(entry)); + } + Object g{{"competition", group.competition}, {"cup", group.cup}, {"matches", std::move(matches)}}; + if (group.league_id) g["league_id"] = *group.league_id; + if (group.cup_id) g["cup_id"] = *group.cup_id; + groups.emplace_back(std::move(g)); + } + return Object{{"valid", true}, {"date", static_cast(results->date)}, + {"date_label", results->date_label}, {"calendar_entry", int(results->calendar_entry)}, + // CurrentMatchday: a random number drawn per matchday (draw_matchday_number), not the + // matchday of a league (issue #6) - hence its own name + {"matchday_draw", int(results->matchday)}, {"groups", std::move(groups)}}; +} + +Json mailbox_state_json(const ui::MailboxState& state) { + Array messages; + for (const auto& message : state.messages) { + Array recipients; + for (int manager : message.recipient_managers) recipients.emplace_back(manager); + messages.emplace_back(Object{{"slot_snapshot_id", int(message.entry_index)}, + {"recipient_mask", static_cast(message.recipient_mask)}, + {"keep_mask", static_cast(message.kept_by_mask)}, + {"recipient_managers", std::move(recipients)}, + {"general_broadcast", message.general_broadcast}, + {"kept_for_manager", message.kept_for_manager}, + {"date_counter", int(message.date_counter)}, {"kind", "unclassified"}, {"text", message.text}}); + } + return Object{{"manager_slot", state.manager_slot}, {"messages", std::move(messages)}}; +} + +Json league_table_state(const app::CareerSession& session, int manager, int league) { + const auto table = bmh::compute_league_table(session.state(), league, 0, + bmh::league_matchdays(league), 7, 1); + std::array order{}; + for (int club = 0; club < table.size; ++club) order[club] = club; + std::sort(order.begin(), order.begin() + table.size, [&](int lhs, int rhs) { + return table.rank(lhs) < table.rank(rhs); + }); + Array rows; + const int first_team = bmh::league_first_team(league); + for (int index = 0; index < table.size; ++index) { + const int club = order[index]; + const int runtime_team = first_team + club; + const int games = table.games(club); + const int draws = games - table.wins[club] - table.defeats[club]; + rows.emplace_back(Object{{"rank", table.rank(club) + 1}, + {"club_identity_key", session.state().club_ids[runtime_team]}, {"runtime_team_id", runtime_team}, + {"name", ui::original_to_utf8(session.state().club_name(runtime_team))}, + {"games", games}, {"wins", table.wins[club]}, {"draws", draws}, + {"losses", table.defeats[club]}, {"goals_for", table.goals_for[club]}, + {"goals_against", table.goals_against[club]}, + {"goal_difference", int(table.goals_for[club]) - int(table.goals_against[club])}, + {"points", int(table.points[club])}, {"previous_rank", table.previous_rank(club) + 1}}); + } + return Object{{"manager_slot", manager}, {"league_id", league}, + // the original league name path of the table screen (issue #5: not TEXTD Prediction_TablePrediction_TextPointer + 4n, + // which starts one entry early with a referee text) + {"league_name", ui::league_table_from_game(session.state(), manager, league).league_name}, + {"points_mode", 1}, + {"rows", std::move(rows)}}; +} + +void put_envelope(const Json& request, int& manager, std::uint64_t& revision) { + manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3); + revision = bounded_u64(integer(required(request, "revision"), "revision"), "revision"); +} + +std::string command_name(const Json& request) { + return string(required(request, "cmd"), "cmd"); +} + +ui::DeskState current_desk(app::CareerSession& session, std::uint64_t revision) { + return session.desktop_projection(revision); +} + +Object completed_status(const app::CareerSession& session, std::uint64_t revision) { + const auto& state = session.state(); + return {{"phase", "career_complete"}, {"active", false}, + {"revision", static_cast(revision)}, + {"date", static_cast(state.date)}, {"season", state.season}, + {"duration", int(state.memory.u8(::bmh::layout::CareerDuration))}}; +} + +Json action_state(app::CareerSession& session, std::uint64_t revision, + std::string_view family, int manager) { + const auto prep = session.preparation_projection(revision); + if (family == "bank" && prep.bank) return state_response(prep.desktop, family, raw_json(ui::bank_state_json(*prep.bank))); + if (family == "camp" && prep.training_camp) return state_response(prep.desktop, family, raw_json(ui::training_camp_json(*prep.training_camp))); + if (family == "stadium" && prep.stadium) return state_response(prep.desktop, family, raw_json(ui::stadium_state_json(*prep.stadium))); + if (family == "toto" && prep.toto) return state_response(prep.desktop, family, raw_json(ui::toto_state_json(*prep.toto))); + (void)manager; + return state_response(prep.desktop, "desk", desk_state_json(prep.desktop)); +} + +ui::SetupOptions parse_options(const Json& value) { + check_keys(value, {"duration", "difficulty", "managers", "mode", "league", "world"}); + ui::SetupOptions options; + options.duration = bounded_int(optional_integer(value, "duration", options.duration), "duration", 0, 5); + options.difficulty = bounded_int(optional_integer(value, "difficulty", options.difficulty), "difficulty", 0, 9); + options.managers = bounded_int(optional_integer(value, "managers", 1), "managers", 1, 1); + options.mode = bounded_int(optional_integer(value, "mode", options.mode), "mode", 0, 3); + options.league = optional_boolean(value, "league", options.league); + options.world = optional_boolean(value, "world", options.world); + return options; +} + +ui::ManagerChoice parse_manager(const Json& value) { + check_keys(value, {"name", "master_club", "start_league", "strength", "portrait"}); + ui::ManagerChoice choice; + choice.slot = 0; + choice.name = ui::utf8_to_original(string(required(value, "name"), "name")); + if (choice.name.empty() || choice.name.size() > 0x19) throw JsonError("invalid_manager_name_length"); + choice.master_club = bounded_int(integer(required(value, "master_club"), "master_club"), "master_club", 0, 4095); + choice.start_league = bounded_int(optional_integer(value, "start_league", 0), "start_league", 0, 4); + choice.strength = bounded_int(optional_integer(value, "strength", 1), "strength", 0, 2); + choice.portrait = bounded_int(optional_integer(value, "portrait", 0), "portrait", 0, 11); + return choice; +} + +} // namespace + +Protocol::Protocol(std::filesystem::path data, std::uint32_t seed) + : data_(std::move(data)), seed_(seed) {} + +Protocol::~Protocol() = default; + +bool Protocol::active() const noexcept { return session_ && !session_->career_complete(); } + +Json Protocol::help() { + return Object{ + {"protocol", 1}, + {"commands", Array{ + Object{{"cmd", "new"}, {"params", "options:{duration,difficulty,mode,league,world,managers:1}; managers:[{name,master_club,start_league?,strength?,portrait?}]"}}, + Object{{"cmd", "load"}, {"params", "path"}}, + Object{{"cmd", "save"}, {"params", "manager,revision,path,overwrite?"}}, + Object{{"cmd", "status"}, {"params", "none"}}, + Object{{"cmd", "desk"}, {"params", "none"}}, + Object{{"cmd", "kickoff"}, {"params", "manager,revision"}}, + Object{{"cmd", "results|tactics"}, {"params", "none"}}, + Object{{"cmd", "mail"}, {"params", "manager:0..3 (required; read-only owned mailbox projection)"}}, + Object{{"cmd", "table"}, {"params", "manager,league:0..8 (read-only; current league text and game point rule)"}}, + Object{{"cmd", "tactics.set"}, {"params", "manager,revision,index:0..7,value (original table range)"}}, + Object{{"cmd", "training"}, {"params", "none (read-only current training projection)"}}, + Object{{"cmd", "training.initialize"}, {"params", "manager,revision"}}, + Object{{"cmd", "training.type"}, {"params", "manager,revision,index:0..3,value:1..3"}}, + Object{{"cmd", "training.area"}, {"params", "manager,revision,index:0..8,value:1..3"}}, + Object{{"cmd", "training.intensity"}, {"params", "manager,revision,row,value:1..3"}}, + Object{{"cmd", "training.focus"}, {"params", "manager,revision,row (cycle focus)"}}, + Object{{"cmd", "training.auto"}, {"params", "manager,revision,index:0..4,value:0|1"}}, + Object{{"cmd", "camp.focus"}, {"params", "manager,revision,focus:[4 values]"}}, + Object{{"cmd", "camp.book"}, {"params", "manager,revision,resort:0..7"}}, + Object{{"cmd", "bank.deposit|bank.withdraw"}, {"params", "manager,revision,amount"}}, + Object{{"cmd", "bank.shares.buy|bank.shares.sell|bank.tip"}, {"params", "manager,revision,asset,count?"}}, + Object{{"cmd", "bank.fund.buy|bank.fund.sell"}, {"params", "manager,revision,asset,count"}}, + Object{{"cmd", "stadium.open|stadium.offer|stadium.build"}, {"params", "manager,revision,object?,price?"}}, + Object{{"cmd", "toto.submit"}, {"params", "manager,revision,stake,tips:[11 values]"}}, + Object{{"cmd", "quit"}, {"params", "none"}}, + }}, + {"not_available", Array{"squad", "player", "calendar", "finances", "lineup.auto", "match.start", "match.step", "match.sub", "match.tactics", "match.finish"}}, + {"note", "Unavailable commands are rejected: CareerSession has no matching projection or dispatch API yet."} + }; +} + +Json Protocol::handle(const Json& request, bool replay) { + try { + check_keys(request, {"cmd", "detail", "manager", "revision", "league", "path", "overwrite", "options", "managers", "amount", "asset", "count", "focus", "resort", "object", "price", "stake", "tips", "index", "value", "row"}); + const std::string cmd = command_name(request); + check_command_keys(request, cmd); + if (cmd == "__protocol_error") + return failed("invalid_request", revision_, optional_string(request, "detail", "invalid protocol input")); + if (cmd == "help") return successful(revision_, {{"help", help()}}); + if (cmd == "quit") return successful(revision_, {{"quit", true}}); + if (cmd == "new") { + if (active()) return failed("career_already_active", revision_); + const auto options_value = find(request, "options") ? *find(request, "options") : Json(Object{}); + const auto options = parse_options(options_value); + const Json& managers_value = required(request, "managers"); + const auto* managers = managers_value.array(); + if (!managers || managers->size() != 1) return failed("stage1_requires_one_manager", revision_); + const auto choice = parse_manager(managers->front()); + const auto database = load_database(data_ / "M3D.MAN"); + if (choice.master_club >= int(database.club_names.size())) + return failed("invalid_master_club", revision_); + auto candidate = std::make_unique(data_, seed_); + std::string error; + if (!candidate->confirm_manager(options, choice, error)) return failed(error.empty() ? "manager_rejected" : error, revision_); + ui::CareerInitializationResult init; + if (!candidate->finish(init, error)) return failed(error.empty() ? "career_start_failed" : error, revision_); + revision_ = init.desktop.revision; + session_ = std::move(candidate); + return successful(revision_, {{"events", Array{Json(Object{{"event", "career_started"}, {"manager", 0}})}}, + {"state", desk_state_json(init.desktop)}}); + } + if (cmd == "load") { + const std::filesystem::path path(string(required(request, "path"), "path")); + auto candidate = std::make_unique(data_, seed_, path); + const std::uint64_t next_revision = revision_ + 1; + auto desk = candidate->desktop_projection(next_revision); + session_ = std::move(candidate); + revision_ = next_revision; + return successful(revision_, {{"events", Array{Json(Object{{"event", "career_loaded"}})}}, + {"state", desk_state_json(desk)}}); + } + // Source's terminal career has no following desk. Keep its owned state + // available for status; reject career commands before any projection, + // envelope parsing, file write or dispatch can occur. + if (session_ && session_->career_complete()) { + if (cmd == "status") + return successful(revision_, {{"status", completed_status(*session_, revision_)}}); + return failed("career_complete", revision_); + } + if (cmd == "status" || cmd == "desk") { + if (!session_) return failed("no_active_career", revision_); + const auto desk = current_desk(*session_, revision_); + Object status{{"manager", desk.manager_slot}, {"revision", static_cast(revision_)}, + {"day", desk.date.day}, {"month", desk.date.month}, {"year", desk.date.year}, + {"club", ui::original_to_utf8(desk.club_name)}, {"balance", desk.balance}, {"runtime_club", desk.runtime_club}, + {"source", desk.source}}; + return successful(revision_, {{"state", desk_state_json(desk)}, {"status", Json(std::move(status))}}); + } + if (cmd == "results" || cmd == "tactics") { + if (!session_) return failed("no_active_career", revision_); + return successful(revision_, {{"state", cmd == "results" ? result_state(*session_) : + tactics_state(session_->preparation_projection(revision_).tactics)}}); + } + if (cmd == "mail") { + if (!session_) return failed("no_active_career", revision_); + const int manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3); + if (size_t(manager) >= session_->state().manager_teams.size()) + return failed("invalid_manager_slot", revision_); + const auto state = ui::mailbox_state_from_game(session_->state(), manager); + return successful(revision_, {{"state", mailbox_state_json(state)}}); + } + if (cmd == "table") { + if (!session_) return failed("no_active_career", revision_); + const int manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3); + const auto raw_league = integer(required(request, "league"), "league"); + if (raw_league < 0 || raw_league >= bmh::kLeagueCount) + return failed("invalid_league", revision_); + const auto desk = current_desk(*session_, revision_); + if (manager != desk.manager_slot) return failed("stale_manager_or_revision", revision_); + return successful(revision_, {{"state", league_table_state(*session_, manager, int(raw_league))}}); + } + if (cmd == "training") { + if (!session_) return failed("no_active_career", revision_); + const auto prep = session_->preparation_projection(revision_); + if (!prep.training) return failed("training_projection_unavailable", revision_); + return successful(revision_, {{"state", training_state(*prep.training)}}); + } + if (cmd == "training.initialize" || cmd == "training.type" || cmd == "training.area" || + cmd == "training.intensity" || cmd == "training.focus" || cmd == "training.auto") { + if (!session_) return failed("no_active_career", revision_); + int manager = -1; + std::uint64_t request_revision = 0; + put_envelope(request, manager, request_revision); + const auto prep = session_->preparation_projection(revision_); + if (!prep.training) return failed("training_projection_unavailable", revision_); + const auto& current = *prep.training; + if (request_revision != revision_ || manager != current.manager_slot) + return failed("stale_manager_or_revision", revision_); + + ui::TrainingRequest action; + action.manager_slot = current.manager_slot; + action.runtime_club = current.runtime_club; + action.revision = request_revision; + action.desired_types = current.types; + action.desired_areas = current.areas; + action.desired_automation = current.automation; + if (cmd == "training.initialize") { + action.kind = ui::TrainingRequestKind::initialize; + action.desired_automation = 0x9f; + } else if (cmd == "training.type") { + action.kind = ui::TrainingRequestKind::set_type; + action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 3); + action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3); + action.desired_types[size_t(action.index)] = uint8_t(action.value); + action.desired_automation &= uint8_t(~2); + } else if (cmd == "training.area") { + action.kind = ui::TrainingRequestKind::set_area; + action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 8); + action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3); + action.desired_areas[size_t(action.index)] = uint8_t(action.value); + action.desired_automation &= uint8_t(~4); + } else if (cmd == "training.intensity" || cmd == "training.focus") { + action.kind = cmd == "training.intensity" ? ui::TrainingRequestKind::set_player_intensity : + ui::TrainingRequestKind::set_player_focus; + action.index = bounded_int(integer(required(request, "row"), "row"), "row", 0, current.squad_capacity - 1); + const auto player = std::find_if(current.players.begin(), current.players.end(), [&](const auto& p) { + return p.row == action.index; + }); + if (player == current.players.end()) return failed("training_row_unavailable", revision_); + action.player_id = player->player_id; + if (cmd == "training.intensity") { + action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3); + action.desired_automation &= uint8_t(~8); + } else action.value = (int(player->focus) + 1) % 8; + } else { + action.kind = ui::TrainingRequestKind::set_automation; + action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 4); + action.value = bounded_int(integer(required(request, "value"), "value"), "value", 0, 1); + const uint8_t mask = uint8_t(1u << action.index); + action.desired_automation = uint8_t((current.automation & ~mask) | + (action.value ? mask : 0)); + } + std::string error; + if (!session_->dispatch_training(action, revision_, error)) + return failed(error.empty() ? "action_rejected" : error, revision_, error); + const auto updated = session_->preparation_projection(revision_).training; + if (!updated) return failed("training_projection_unavailable", revision_); + return successful(revision_, {{"state", training_state(*updated)}, + {"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}}}); + } + if (cmd == "tactics.set") { + if (!session_) return failed("no_active_career", revision_); + ui::TacticsRequest action; + put_envelope(request, action.manager_slot, action.revision); + action.runtime_club = current_desk(*session_, revision_).runtime_club; + action.kind = ui::TacticsRequestKind::set_tactic; + action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 7); + action.desired_value = bounded_int(integer(required(request, "value"), "value"), "value", 0, 11); + if (action.index == 0) action.desired_assistant_attitude = 0; + std::string error; + if (!session_->dispatch_tactics(action, revision_, error)) + return failed("action_rejected", revision_, error); + return successful(revision_, {{"state", tactics_state(session_->preparation_projection(revision_).tactics)}, + {"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}}}); + } + if (cmd == "save") { + if (!session_) return failed("no_active_career", revision_); + int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision); + const auto desk = current_desk(*session_, revision_); + if (request_revision != revision_ || manager != desk.manager_slot) + return failed("stale_manager_or_revision", revision_); + const bool overwrite = replay || optional_boolean(request, "overwrite", false); + std::string error; + if (!session_->save_game(string(required(request, "path"), "path"), manager, overwrite, error)) + return failed(error.empty() ? "save_rejected" : error, revision_); + return successful(revision_, {{"events", Array{Json(Object{{"event", "career_saved"}})}}}); + } + if (cmd == "kickoff") { + if (!session_) return failed("no_active_career", revision_); + int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision); + ui::DeskRequest req; req.kind = ui::DeskRequestKind::advance_turn; req.manager_slot = manager; req.revision = request_revision; + std::string error; + const auto advanced = session_->dispatch_kickoff(req, revision_, error); + if (advanced.kind == TurnDeskKind::Failed || advanced.kind == TurnDeskKind::WaitingAtDesk) + return failed(error.empty() ? advanced.reason : error, revision_); + if (advanced.kind == TurnDeskKind::CareerComplete) { + return successful(revision_, {{"events", Array{Json(Object{ + {"event", "career_complete"}, {"date", static_cast(advanced.date)}, + {"season", session_->state().season}, {"duration", int(session_->state().memory.u8(::bmh::layout::CareerDuration))}})}}, + {"status", completed_status(*session_, revision_)}}); + } + Array events; + for (const auto& event : advanced.audio_events) { + std::string kind = event.kind == TurnAudioKind::kickoff_whistle ? "kickoff_whistle" : + event.kind == TurnAudioKind::goal ? "goal" : "full_time_whistle"; + Object item{{"event", "audio"}, {"session_id", static_cast(event.session_id)}, + {"event_id", static_cast(event.event_id)}, {"kind", std::move(kind)}}; + if (event.original_id) item.emplace("original_id", int(*event.original_id)); + events.emplace_back(std::move(item)); + } + events.emplace_back(Object{{"event", "desk"}, {"manager", advanced.manager_slot}, + {"date", static_cast(advanced.date)}, + {"kind", advanced.kind == TurnDeskKind::SeasonEndDesk ? "season_end" : "next_desk"}}); + const auto desk = current_desk(*session_, revision_); + return successful(revision_, {{"events", Json(std::move(events))}, {"state", desk_state_json(desk)}, + {"results", result_state(*session_)}}); + } + + if (cmd.rfind("camp.", 0) == 0 || cmd.rfind("bank.", 0) == 0 || + cmd.rfind("stadium.", 0) == 0 || cmd == "toto.submit") { + if (!session_) return failed("no_active_career", revision_); + int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision); + const auto desk = current_desk(*session_, revision_); + const int runtime_club = desk.runtime_club; + std::string error; + bool accepted = false; + std::string family; + if (cmd == "camp.focus" || cmd == "camp.book") { + family = "camp"; + ui::TrainingCampRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision; + const auto prep = session_->preparation_projection(revision_); + if (!prep.training_camp) return failed("training_camp_projection_unavailable", revision_); + req.focus = prep.training_camp->focus; + if (cmd == "camp.focus") { + req.kind = ui::TrainingCampRequestKind::set_focus; + const Json& value = required(request, "focus"); const auto* values = value.array(); + if (!values || values->size() != 4) return failed("invalid_focus", revision_); + for (size_t i = 0; i < 4; ++i) req.focus[i] = static_cast(bounded_int(integer(values->at(i), "focus"), "focus", 0, 255)); + } else { + req.kind = ui::TrainingCampRequestKind::book; + req.resort = bounded_int(integer(required(request, "resort"), "resort"), "resort", 0, 7); + } + accepted = session_->dispatch_training_camp(req, revision_, error); + } else if (cmd.rfind("bank.", 0) == 0) { + family = "bank"; + ui::BankRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision; + if (cmd == "bank.deposit" || cmd == "bank.withdraw") { + req.kind = ui::BankRequestKind::move_to_deposit; + const auto amount = integer(required(request, "amount"), "amount"); + if (amount <= 0 || amount > std::numeric_limits::max()) return failed("invalid_amount", revision_); + req.amount = static_cast(cmd == "bank.deposit" ? amount : -amount); + } else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip") { + req.kind = cmd == "bank.shares.buy" ? ui::BankRequestKind::buy_shares : + cmd == "bank.shares.sell" ? ui::BankRequestKind::sell_shares : ui::BankRequestKind::stock_tip; + req.asset_index = bounded_int(integer(required(request, "asset"), "asset"), "asset", 0, 11); + req.count = bounded_int(optional_integer(request, "count", 0), "count", 0, 9999); + } else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell") { + req.kind = cmd == "bank.fund.buy" ? ui::BankRequestKind::buy_fund : ui::BankRequestKind::sell_fund; + req.asset_index = bounded_int(integer(required(request, "asset"), "asset"), "asset", 0, 5); + req.count = bounded_int(integer(required(request, "count"), "count"), "count", 1, 10); + } else return failed("unsupported_command", revision_); + accepted = session_->dispatch_bank(req, revision_, error); + } else if (cmd.rfind("stadium.", 0) == 0) { + family = "stadium"; + ui::StadiumRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision; + if (cmd == "stadium.open") req.kind = ui::StadiumRequestKind::open; + else if (cmd == "stadium.offer") { req.kind = ui::StadiumRequestKind::quote_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); } + else if (cmd == "stadium.build") { req.kind = ui::StadiumRequestKind::build_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); req.price = bounded_int(integer(required(request, "price"), "price"), "price", 1, std::numeric_limits::max()); } + else if (cmd == "stadium.decline") { req.kind = ui::StadiumRequestKind::decline_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); req.price = bounded_int(integer(required(request, "price"), "price"), "price", 1, std::numeric_limits::max()); } + else return failed("unsupported_command", revision_); + accepted = session_->dispatch_stadium(req, revision_, error); + } else if (cmd == "toto.submit") { + family = "toto"; + ui::TotoRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision; + req.stake = bounded_int(integer(required(request, "stake"), "stake"), "stake", 0, std::numeric_limits::max()); + const Json& value = required(request, "tips"); const auto* tips = value.array(); + if (!tips || tips->size() != req.tips.size()) return failed("invalid_tips", revision_); + for (size_t i = 0; i < req.tips.size(); ++i) req.tips[i] = static_cast(bounded_int(integer(tips->at(i), "tips"), "tips", 0, 2)); + req.kind = ui::TotoRequestKind::submit; + accepted = session_->dispatch_toto(req, revision_, error); + } + if (!accepted) return failed(error.empty() ? "action_rejected" : error, revision_); + return successful(revision_, {{"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}}, + {"state", action_state(*session_, revision_, family, manager).object()->at("state")}}); + } + if (cmd == "squad" || cmd == "player" || cmd == "calendar" || cmd == "finances" || + cmd == "lineup.auto" || cmd.rfind("match.", 0) == 0) + return failed("career_session_api_unavailable", revision_, "This command has no CareerSession projection/dispatch adapter in E10 stage 1."); + return failed("unsupported_command", revision_); + } catch (const JsonError& e) { + return failed("invalid_request", revision_, e.what()); + } catch (const std::exception& e) { + return failed("operation_failed", revision_, e.what()); + } +} + +Json text_request(std::string_view line, const Protocol* protocol) { + std::istringstream input{std::string(line)}; + std::string cmd; + input >> cmd; + if (cmd.empty()) throw JsonError("empty_command"); + Object req{{"cmd", cmd}}; + std::string path, name; + auto envelope = [&] { + if (!protocol || !protocol->active()) throw JsonError("no_active_career"); + req.emplace("manager", 0); + req.emplace("revision", static_cast(protocol->revision())); + }; + if (cmd == "new") { + int master = -1, strength = 1; + if (!(input >> master >> std::quoted(name))) throw JsonError("usage:new [strength]"); + if (input >> strength) { /* optional */ } + req.emplace("options", Json(Object{{"managers", 1}})); + req.emplace("managers", Json(Array{Json(Object{{"master_club", master}, {"name", name}, {"strength", strength}})})); + } else if (cmd == "load" || cmd == "save") { + if (!(input >> std::quoted(path))) throw JsonError("usage:" + cmd + " "); + req.emplace("path", path); + if (cmd == "save") envelope(); + } else if (cmd == "kickoff") envelope(); + else if (cmd == "tactics.set") { + int index = -1, value = -1; + if (!(input >> index >> value)) throw JsonError("usage:tactics.set "); + req.emplace("index", index); req.emplace("value", value); envelope(); + } + else if (cmd == "training") { + } else if (cmd == "training.initialize") envelope(); + else if (cmd == "training.type" || cmd == "training.area" || cmd == "training.auto") { + int index = -1, value = -1; + if (!(input >> index >> value)) throw JsonError("usage:" + cmd + " "); + req.emplace("index", index); req.emplace("value", value); envelope(); + } else if (cmd == "training.intensity") { + int row = -1, value = -1; + if (!(input >> row >> value)) throw JsonError("usage:training.intensity "); + req.emplace("row", row); req.emplace("value", value); envelope(); + } else if (cmd == "training.focus") { + int row = -1; + if (!(input >> row)) throw JsonError("usage:training.focus "); + req.emplace("row", row); envelope(); + } else if (cmd == "table") { + int manager = -1, league = -1; + if (!(input >> manager >> league)) throw JsonError("usage:table "); + if (!protocol || !protocol->active()) throw JsonError("no_active_career"); + req.emplace("manager", manager); + req.emplace("league", league); + } else if (cmd == "mail") { + int manager = -1; + if (!(input >> manager)) throw JsonError("usage:mail "); + if (!protocol || !protocol->active()) throw JsonError("no_active_career"); + req.emplace("manager", manager); + } + else if (cmd == "bank.deposit" || cmd == "bank.withdraw") { + std::int64_t amount; + if (!(input >> amount)) throw JsonError("usage:" + cmd + " "); + req.emplace("amount", amount); envelope(); + } else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip") { + int asset = -1, count = 0; + if (!(input >> asset)) throw JsonError("usage:" + cmd + " [count]"); + if (cmd != "bank.tip" && !(input >> count)) throw JsonError("usage:" + cmd + " "); + req.emplace("asset", asset); req.emplace("count", count); envelope(); + } else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell") { + int asset = -1, count = 0; + if (!(input >> asset >> count)) throw JsonError("usage:" + cmd + " "); + req.emplace("asset", asset); req.emplace("count", count); envelope(); + } else if (cmd == "camp.book") { + int resort = -1; if (!(input >> resort)) throw JsonError("usage:camp.book "); + req.emplace("resort", resort); envelope(); + } else if (cmd == "help" || cmd == "status" || cmd == "desk" || cmd == "quit" || cmd == "tactics" || cmd == "results") { + } else throw JsonError("unsupported_text_command:" + cmd); + std::string extra; + if (input >> extra) throw JsonError("too_many_arguments"); + return req; +} + +std::string text_response(const Json& response) { + const auto* ok = find(response, "ok"); + const auto* ok_value = ok ? ok->boolean() : nullptr; + if (ok_value && !*ok_value) { + std::string out = "ERROR " + optional_string(response, "error", "unknown_error"); + if (const auto* detail = find(response, "detail"); detail && detail->string()) out += ": " + *detail->string(); + return out; + } + std::string out = "OK revision " + std::to_string(optional_integer(response, "revision", 0)); + if (const auto* status = find(response, "status"); status && status->object()) { + if (optional_string(*status, "phase", "") == "career_complete") + return out + " | career complete | date " + std::to_string(optional_integer(*status, "date", 0)); + out += " | " + optional_string(*status, "club", "club ?"); + out += " | date " + std::to_string(optional_integer(*status, "day", 0)) + "." + + std::to_string(optional_integer(*status, "month", 0)) + "." + std::to_string(optional_integer(*status, "year", 0)); + out += " | balance " + std::to_string(optional_integer(*status, "balance", 0)); + } else if (const auto* state = find(response, "state")) out += " | " + dump_json(*state); + return out; +} + +} // namespace bmh::cli diff --git a/src/cli/protocol.hpp b/src/cli/protocol.hpp new file mode 100644 index 0000000..d02b6d3 --- /dev/null +++ b/src/cli/protocol.hpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "cli/json.hpp" + +#include +#include +#include + +namespace bmh::app { class CareerSession; } +namespace bmh::cli { + +class Protocol { +public: + Protocol(std::filesystem::path data, std::uint32_t seed); + ~Protocol(); + Json handle(const Json& request, bool replay = false); + bool active() const noexcept; + std::uint64_t revision() const noexcept { return revision_; } + static Json help(); + +private: + std::filesystem::path data_; + std::uint32_t seed_; + std::uint64_t revision_ = 0; + std::unique_ptr session_; +}; + +Json text_request(std::string_view line, const Protocol* protocol); +std::string text_response(const Json& response); + +} // namespace bmh::cli diff --git a/src/cli/seat_hub.cpp b/src/cli/seat_hub.cpp new file mode 100644 index 0000000..5343d1a --- /dev/null +++ b/src/cli/seat_hub.cpp @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "cli/seat_hub.hpp" + +#include +#include +#include + +#include "cli/console/parser.hpp" +#include "cli/json.hpp" + +namespace bmh::cli { + +namespace { + +std::string trimmed(const std::string& s) { + const size_t a = s.find_first_not_of(" \t"); + if (a == std::string::npos) return {}; + return s.substr(a, s.find_last_not_of(" \t") - a + 1); +} + +bool is_wait_turn(const std::string& command) { + const std::string key = console::canonical(command); + return key == "waitturn" || key == "waitturn()"; +} + +const char* json_class(char cls) { // as Console::emit names them + switch (cls) { + case '#': return "status"; + case '!': return "error"; + default: return "info"; + } +} + +} // namespace + +SeatHub::SeatHub(console::Options options, int seats, std::function on_block) + : options_(options), + console_(options, [](const std::string&) {}), + seats_(size_t(seats < 1 ? 1 : seats)), + on_block_(std::move(on_block)), + asked_(4) { + console_.set_line_observer([this](const console::Console::LineInfo& line) { lines_.push_back(line); }); + console_.start(); + for (const auto& l : lines_) start_.push_back(l.line); + lines_.clear(); + if (on_block_) on_block_(console_); +} + +std::string SeatHub::format(char cls, const std::string& text) const { + if (!options_.json) return std::string(1, cls) + " " + text; + return dump_json(Json(Json::Object{{"class", json_class(cls)}, {"text", text}})); +} + +// A line concerns a seat when it belongs to its manager or to all; chat lines name their +// addressee ("[P1 -> P2] ...", "[P1 -> All] ..."). +bool SeatHub::concerns(const console::Console::LineInfo& line, int seat) const { + if (line.cls == 'c') { + const size_t arrow = line.text.find(" -> "); + const size_t end = line.text.find(']', arrow == std::string::npos ? 0 : arrow); + if (arrow == std::string::npos || end == std::string::npos) return true; + const std::string target = line.text.substr(arrow + 4, end - arrow - 4); + return target == "All" || target == "P" + std::to_string(seat); + } + return line.player == 0 || line.player == seat; +} + +bool SeatHub::on_turn(int seat) const { + if (console_.ended()) return true; + if (const int q = console_.question_player()) return q == seat; + return console_.active_player() == seat || console_.active_player() == 0; +} + +std::vector SeatHub::answer(Seat& seat, std::vector own) { + std::vector response; + if (!seat.feed.empty()) { + response.push_back(format('i', "--- meanwhile ---")); + response.insert(response.end(), seat.feed.begin(), seat.feed.end()); + response.push_back(format('i', "--- end of meanwhile ---")); + } + response.insert(response.end(), own.begin(), own.end()); + seat.feed.clear(); + return response; +} + +std::optional> SeatHub::submit(int seat, std::vector lines) { + using console::classify_line; + using console::LineKind; + if (seat < 1 || seat > int(seats_.size())) return std::vector{format('!', "E_BAD_ARGUMENT: no seat " + std::to_string(seat))}; + Seat& me = seats_[size_t(seat - 1)]; + while (!lines.empty() && trimmed(lines.back()).empty()) lines.pop_back(); + std::vector commands; + for (const auto& l : lines) + if (classify_line(l) == LineKind::command) commands.push_back(trimmed(l)); + const bool multi = seats_.size() > 1; + + if (commands.size() == 1 && is_wait_turn(commands[0])) { + me.waiting = true; + if (!multi) { // one client: always its turn + auto now = release(); + if (!now.empty()) return now.front().second; + } + return std::nullopt; + } + for (const auto& c : commands) + if (is_wait_turn(c)) + return answer(me, {format('!', "E_BAD_ARGUMENT: WaitTurn must be a block of its own (nothing else in it)")}); + + // A live match runs for everybody (player All): the clock moves only when every seat has + // sent its Run or Step - after its own interventions (tactics, substitutions, moves). The + // earliest stop asked for is taken (Step(n) before Run(Halftime) before Run); every seat + // then gets the output. Without this the first Run would play the day to the end and the + // other managers would miss their half time. + // A block that ends with the Run (interventions first, then "Run") runs its other lines + // now and holds only the Run - otherwise its Run would play past the barrier (learning + // session run 1: the other seats then waited for a match day that was over). + if (multi && console_.window() == "Match" && !commands.empty()) { + // Only the last command of a block may move the clock: a Run/Step in the middle + // ("Step(3)", "SetTactic(..)", "Run(Halftime)", "ShowMatchStats") would run past the + // barrier for everybody (learning session run 2, block 715). + for (size_t i = 0; i + 1 < commands.size(); ++i) { + std::string m = commands[i]; + if (!m.empty() && m[0] == '@') m = trimmed(m.substr(m.find_first_not_of("@0123456789"))); + const std::string key = console::canonical(m.substr(0, m.find('('))); + if (key == "run" || key == "step") + return answer(me, {format('!', "E_BAD_ARGUMENT: in a live match only the last command of a block may be " + "Run or Step (the clock waits for every manager) - nothing was executed")}); + } + std::string c = commands.back(); + if (!c.empty() && c[0] == '@') c = trimmed(c.substr(c.find_first_not_of("@0123456789"))); + const std::string name = console::canonical(c.substr(0, c.find('('))); + if ((name == "run" || name == "step") && !me.run.empty()) + return answer(me, {format('!', "E_BAD_ARGUMENT: your " + me.run + " is already waiting for the other managers")}); + if ((name == "run" || name == "step") && commands.size() > 1) { + std::vector before; + for (const auto& l : lines) { + if (classify_line(l) == LineKind::command && trimmed(l) == commands.back()) break; + before.push_back(l); + } + before.push_back("go."); + // (the earlier lines are checked as any block: an @n of another seat is refused) + auto first = submit(seat, before); + if (first) me.held = std::move(*first); + if (console_.window() != "Match") { // (cannot happen: interventions do not end the day) + std::vector out = std::move(me.held); + me.held.clear(); + out.push_back(format('i', "the match day is over - " + c + " was not needed")); + return out; + } + commands = {commands.back()}; + } + if (name == "run" || name == "step") { + me.run = c; + for (const auto& s : seats_) + if (s.run.empty()) return std::nullopt; // wait for the others + int step = 0; + bool halftime = false; + for (const auto& s : seats_) { + const std::string key = console::canonical(s.run); + if (key.rfind("step", 0) == 0) { + const size_t open = s.run.find('('); + const int n = open == std::string::npos ? 1 : std::max(1, std::atoi(s.run.c_str() + open + 1)); + step = step == 0 ? n : std::min(step, n); + } + if (key.find("halftime") != std::string::npos) halftime = true; + } + const std::string chosen = step ? "Step(" + std::to_string(step) + ")" : halftime ? "Run(Halftime)" : "Run"; + std::vector own = run_block(seat, {"@" + std::to_string(seat) + " " + chosen, "go."}); + for (size_t j = 0; j < seats_.size(); ++j) { + Seat& s = seats_[j]; + s.run.clear(); + std::vector mine = std::move(s.held); + s.held.clear(); + if (int(j) + 1 == seat) mine.insert(mine.end(), own.begin(), own.end()); + ready_.emplace_back(int(j) + 1, answer(s, std::move(mine))); + } + return std::nullopt; // every seat's answer comes out of release() + } + } + // every command line acts for this seat's manager (one seat: the active player, as at the + // console) + if (multi) { + std::string refused; + for (auto& l : lines) { + if (classify_line(l) != LineKind::command) continue; + const std::string t = trimmed(l); + if (t.front() == '@') { + size_t i = 1; + while (i < t.size() && std::isdigit(static_cast(t[i]))) ++i; + if (t.substr(1, i - 1) != std::to_string(seat)) refused = t; + l = t; + } else { + l = "@" + std::to_string(seat) + " " + t; + } + } + if (!refused.empty()) + return answer(me, {format('!', "E_NOT_YOUR_TURN: you are player " + std::to_string(seat) + " (" + refused + ")")}); + } + if (lines.empty() || classify_line(lines.back()) != LineKind::go) lines.push_back("go."); + + return answer(me, run_block(seat, std::move(lines))); +} + +// Executes one block for a seat and splits its output (see submit). +std::vector SeatHub::run_block(int seat, std::vector lines) { + using console::classify_line; + using console::LineKind; + const bool multi = seats_.size() > 1; + std::vector own; + const bool sender_on_turn = !multi || on_turn(seat); // (also true for the answer to his question) + for (const auto& l : lines) { + lines_.clear(); + const bool executes = classify_line(l) == LineKind::go; + console_.feed(l); + if (executes && on_block_) on_block_(console_); + // Errors and listings ('!', '>') and the sender's own chat answer the sender only; + // another manager's lines (his desk after the turn passed) go to that seat only. A seat + // that was not on turn can change nothing for the others: it gets all of its output, + // the others only its chat. + for (const auto& line : lines_) { + if (line.cls == '?' && line.player >= 1 && line.player <= 4) asked_[size_t(line.player - 1)] = line.line; + if (!multi) { + own.push_back(line.line); + continue; + } + const bool chat = line.cls == 'c'; + const bool reply = line.cls == '!' || line.cls == '>' || + (chat && line.text.rfind("[P" + std::to_string(seat) + " ", 0) == 0); + if (!sender_on_turn || reply || line.cls == '#' || concerns(line, seat)) own.push_back(line.line); + if (reply && !chat) continue; + if (!sender_on_turn && !chat) continue; + for (size_t j = 0; j < seats_.size(); ++j) + if (int(j) + 1 != seat && concerns(line, int(j) + 1)) seats_[j].feed.push_back(line.line); + } + if (console_.ended()) break; + } + lines_.clear(); + return own; +} + +void SeatHub::drop_stale_runs() { + if (console_.window() == "Match" && !console_.ended()) return; + for (size_t j = 0; j < seats_.size(); ++j) { + Seat& s = seats_[j]; + if (s.run.empty()) continue; + std::vector mine = std::move(s.held); + s.held.clear(); + mine.push_back(format('i', "the match day is over - your " + s.run + " was not needed")); + s.run.clear(); + ready_.emplace_back(int(j) + 1, answer(s, std::move(mine))); + } +} + +std::vector>> SeatHub::release() { + drop_stale_runs(); + std::vector>> out; + // the answers of a live-match Run every seat agreed on come first + out.swap(ready_); + for (size_t k = 0; k < seats_.size(); ++k) { + Seat& seat = seats_[k]; + const int number = int(k) + 1; + if (!seat.waiting || !(seats_.size() == 1 || on_turn(number))) continue; + const int active = console_.active_player(); + std::vector status{format('#', "Window: " + console_.window()), + format('#', "Player: " + (active ? std::to_string(active) : std::string("All")))}; + if (console_.ended()) status.push_back(format('#', "Session ended")); + // a question for this seat may have been asked in its own last answer: repeat it, so a + // client does not mistake the turn for a free one (GoBack would decline it) + if (console_.question_player() == number && !asked_[k].empty()) status.push_back(asked_[k]); + out.emplace_back(number, answer(seat, std::move(status))); + seat.waiting = false; + } + return out; +} + +bool SeatHub::replay(const std::vector& block, const std::vector& expected) { + for (const auto& l : block) console_.feed(l); + console_.feed("go."); + if (on_block_) on_block_(console_); + lines_.clear(); + return console_.last_output() == expected; +} + +void SeatHub::forget(int seat) { + if (seat >= 1 && seat <= int(seats_.size())) seats_[size_t(seat - 1)].waiting = false; +} + +} // namespace bmh::cli diff --git a/src/cli/seat_hub.hpp b/src/cli/seat_hub.hpp new file mode 100644 index 0000000..f5f1d63 --- /dev/null +++ b/src/cli/seat_hub.hpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// SeatHub: one console game shared by several clients (agents, a graphical front end), each +// client one human manager ("seat"). The transports - the mailbox directories of --serve and +// the TCP connections of --listen (src/cli/main.cpp) - only move blocks of lines; the hub +// decides what each seat may do and sees: +// - A seat's command lines run as "@k ": a client acts only as its own manager (a line +// with another @n is refused). Whoever is not on turn may only use the commands of every +// window (Status, Help, Chat, Answer, State ...); the console says E_NOT_YOUR_TURN. +// - An answer starts with what happened in the other seats' blocks since this seat's last +// answer and concerns it - lines of player All or k, chat to all or to Pk - between two +// "--- meanwhile ---" info lines. Errors and listings stay with their sender; another +// manager's desk lines go to that manager only. +// - A block that holds only "WaitTurn" is held until manager k is on turn, a question for +// him is open, a live match runs (player All) or the session ends; its answer is the +// meanwhile part, the window and player status and an open question for him again. +// Lines are routed by Console::LineInfo (class, player, text), so the text and the JSON +// format (--json) behave the same. With one seat the hub is a plain pass-through. +// - During a live match (stepped time, window Match, player All) a Run or Step is held until +// every seat has sent one; the earliest stop is played and every seat gets the output. +// A block that ends with Run/Step (e.g. "Substitute(..)" then "Run") runs its other lines +// at once and holds the Run. Should the match day end while runs are held (it cannot, as +// every Run goes through the barrier, but a held seat must never wait for ever), the held +// seats are answered with what their lines did and a note. + +#include +#include +#include +#include +#include + +#include "cli/console/console.hpp" + +namespace bmh::cli { + +class SeatHub { +public: + // `seats`: number of clients (1-4). `on_block`: called after every executed block (the + // console's last_block / last_output), for the session log. + SeatHub(console::Options options, int seats, std::function on_block); + + // The start output (Window/Player lines), for each newly connected seat. + const std::vector& start_output() const { return start_; } + int seats() const { return int(seats_.size()); } + bool ended() const { return console_.ended(); } + + // One block from seat `seat` (1-based). Returns its answer, or nothing when the block is a + // WaitTurn that is held; release() hands such answers out later. + std::optional> submit(int seat, std::vector lines); + // Held WaitTurns that can be answered now (after a block of another seat, or at the end). + std::vector>> release(); + // A held WaitTurn of a seat whose client went away is dropped. + void forget(int seat); + // Feeds one executed block of an earlier session log again (--resume): the console draws + // no random numbers, so the game reaches the same state. Returns false when the output + // differs from `expected`. + bool replay(const std::vector& block, const std::vector& expected); + +private: + struct Seat { + bool waiting = false; // a WaitTurn is held + std::vector feed; // other seats' lines that concern this seat + std::string run; // its Run/Step during a live match, held until all have sent one + std::vector held; // the output of the lines before that Run in its block + }; + void drop_stale_runs(); // held runs of a match day that is over are answered + std::string format(char cls, const std::string& text) const; // a line of the hub itself + bool concerns(const console::Console::LineInfo& line, int seat) const; + bool on_turn(int seat) const; + std::vector answer(Seat& seat, std::vector own); + std::vector run_block(int seat, std::vector lines); + + console::Options options_; + console::Console console_; + std::vector seats_; + std::vector start_; + std::function on_block_; + // the lines of the block being executed, with their meaning + std::vector lines_; + std::vector asked_; // the last question line per player (index player-1) + std::vector>> ready_; // answers of an agreed live-match Run +}; + +} // namespace bmh::cli diff --git a/src/formats/binary.cpp b/src/formats/binary.cpp new file mode 100644 index 0000000..81f5054 --- /dev/null +++ b/src/formats/binary.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/binary.hpp" + +#include +#include + +namespace bmh { + +Bytes read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + if (!in) throw FormatError("cannot open " + path.string()); + return Bytes(std::istreambuf_iterator(in), {}); +} + +std::string iso646de_to_utf8(const char* s, size_t max_len) { + std::string out; + for (size_t i = 0; i < max_len && s[i] != '\0'; i++) { + switch (s[i]) { + case '[': out += "Ä"; break; + case '\\': out += "Ö"; break; + case ']': out += "Ü"; break; + case '{': out += "ä"; break; + case '|': out += "ö"; break; + case '}': out += "ü"; break; + case '~': out += "ß"; break; + default: out += s[i]; + } + } + return out; +} + +} // namespace bmh diff --git a/src/formats/binary.hpp b/src/formats/binary.hpp new file mode 100644 index 0000000..b1042fa --- /dev/null +++ b/src/formats/binary.hpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Little helpers for reading the original little-endian data files. +#include +#include +#include +#include +#include + +namespace bmh { + +using Bytes = std::vector; + +struct FormatError : std::runtime_error { + using std::runtime_error::runtime_error; +}; + +Bytes read_file(const std::filesystem::path& path); + +inline uint16_t le16(const Bytes& b, size_t o) { return uint16_t(b.at(o) | b.at(o + 1) << 8); } +inline uint32_t le32(const Bytes& b, size_t o) { return uint32_t(le16(b, o)) | uint32_t(le16(b, o + 2)) << 16; } + +// Strings in the game use ISO 646-DE: [ \ ] { | } ~ are Ä Ö Ü ä ö ü ß +std::string iso646de_to_utf8(const char* s, size_t max_len = std::string::npos); + +} // namespace bmh diff --git a/src/formats/executable_layout.hpp b/src/formats/executable_layout.hpp new file mode 100644 index 0000000..6ec1934 --- /dev/null +++ b/src/formats/executable_layout.hpp @@ -0,0 +1,1967 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +// Typed offsets and field locations for the executable data adapters. +// Keep each literal's spelling and integer suffix when regenerating this file. +namespace bmh::layout { +inline constexpr auto Achievements_Fill_ExecutableField = 0xae090; +inline constexpr auto Achievements_Fill_ExecutableField2 = 0xae094; +inline constexpr auto Achievements_Fill_RuntimeField = 0xa2229; +inline constexpr auto Achievements_Fill_RuntimeField2 = 0xa3c70; +inline constexpr auto Achievements_Fill_RuntimeField3 = 0xa3c71; +inline constexpr auto Achievements_Fill_RuntimeField4 = 0xa3c7a; +inline constexpr auto Achievements_Fill_RuntimeField4Unsigned = 0xa3c7aU; +inline constexpr auto Achievements_Fill_RuntimeField5 = 0xa3c7b; +inline constexpr auto Achievements_Fill_RuntimeField5Unsigned = 0xa3c7bU; +inline constexpr auto Achievements_Fill_RuntimeField6 = 0xa3c7c; +inline constexpr auto Achievements_Fill_RuntimeField6Unsigned = 0xa3c7cU; +inline constexpr auto Achievements_Fill_TextPointer = 0xaf09c; +inline constexpr auto Achievements_FormatError_ExecutableField = 0xa10f4; +inline constexpr auto Achievements_FormatError_RuntimeField = 0xa10f6; +inline constexpr auto Achievements_FormatError_RuntimeField2 = 0xa245b; +inline constexpr auto Achievements_FormatError_TextPointer = 0xa10f7; +inline constexpr auto Achievements_FormatError_TextPointer2 = 0xae098; +inline constexpr auto Achievements_FormatError_TextPointer3 = 0xae6c8; +inline constexpr auto Achievements_FormatError_TextPointer4 = 0xaf08c; +inline constexpr auto Achievements_FormatError_TextPointer5 = 0xaf090; +inline constexpr auto Achievements_FormatError_TextPointer6 = 0xaf098; +inline constexpr auto Achievements_FormatError_TextPointer7 = 0xaf0a0; +inline constexpr auto ActiveManager = 0xafb59; +inline constexpr auto ActiveSelectors = 0xa25b0; +inline constexpr auto AdGroupId = 0xa2218; +inline constexpr auto AdditionalLeagueStrengthRanges = 0xa2c27; +inline constexpr auto AdditionalStadiumPrices = 0xa3751; +inline constexpr auto Advertising_Button_RuntimeField = 0xa435e; +inline constexpr auto Advertising_Click_RuntimeField = 0xa43ea; +inline constexpr auto Advertising_Click_RuntimeField2 = 0xa441a; +inline constexpr auto Advertising_Click_RuntimeField3 = 0xa4904; +inline constexpr auto Advertising_Click_RuntimeField4 = 0xa492c; +inline constexpr auto Advertising_Click_RuntimeField5 = 0xa4954; +inline constexpr auto Advertising_Click_RuntimeField6 = 0xa497c; +inline constexpr auto Advertising_FormatError_ExecutableField = 0xa157e; +inline constexpr auto Advertising_FormatError_ExecutableField2 = 0xa1581; +inline constexpr auto Advertising_FormatError_ExecutableField3 = 0xae2a8; +inline constexpr auto Advertising_FormatError_RuntimeField = 0xa48fc; +inline constexpr auto Advertising_FormatError_RuntimeField2 = 0xa48fe; +inline constexpr auto Advertising_FormatError_RuntimeField3 = 0xa4900; +inline constexpr auto Advertising_FormatError_RuntimeField4 = 0xa4902; +inline constexpr auto Advertising_FormatError_TextPointer = 0xa157c; +inline constexpr auto Advertising_FormatError_TextPointer10 = 0xae26c; +inline constexpr auto Advertising_FormatError_TextPointer11 = 0xae270; +inline constexpr auto Advertising_FormatError_TextPointer12 = 0xae274; +inline constexpr auto Advertising_FormatError_TextPointer13 = 0xae278; +inline constexpr auto Advertising_FormatError_TextPointer14 = 0xae27c; +inline constexpr auto Advertising_FormatError_TextPointer15 = 0xae280; +inline constexpr auto Advertising_FormatError_TextPointer16 = 0xae284; +inline constexpr auto Advertising_FormatError_TextPointer17 = 0xaea98; +inline constexpr auto Advertising_FormatError_TextPointer18 = 0xaeb14; +inline constexpr auto Advertising_FormatError_TextPointer19 = 0xaeec0; +inline constexpr auto Advertising_FormatError_TextPointer2 = 0xae048; +inline constexpr auto Advertising_FormatError_TextPointer20 = 0xaeec4; +inline constexpr auto Advertising_FormatError_TextPointer21 = 0xaeec8; +inline constexpr auto Advertising_FormatError_TextPointer3 = 0xae04c; +inline constexpr auto Advertising_FormatError_TextPointer4 = 0xae050; +inline constexpr auto Advertising_FormatError_TextPointer5 = 0xae054; +inline constexpr auto Advertising_FormatError_TextPointer6 = 0xae25c; +inline constexpr auto Advertising_FormatError_TextPointer7 = 0xae260; +inline constexpr auto Advertising_FormatError_TextPointer8 = 0xae264; +inline constexpr auto Advertising_FormatError_TextPointer9 = 0xae268; +inline constexpr auto Advertising_OriginalShareAdjustment_RuntimeField = 0xac7c4; +inline constexpr auto Advertising_PatternRect_RuntimeField = 0xa3357; +inline constexpr auto Advertising_Render_RuntimeField = 0xa4920; +inline constexpr auto Advertising_Render_RuntimeField2 = 0xa4948; +inline constexpr auto Advertising_Render_RuntimeField3 = 0xa4970; +inline constexpr auto Advertising_Render_RuntimeField4 = 0xa4998; +inline constexpr auto Advertising_Render_RuntimeField5 = 0xa49a4; +inline constexpr auto Advertising_Render_RuntimeField6 = 0xa49a9; +inline constexpr auto Advertising_String_ExecutableField = 0xa1585; +inline constexpr auto Advertising_Text_RuntimeField = 0xa388a; +inline constexpr auto Advertising_Text_RuntimeField2 = 0xa3b93; +inline constexpr auto Advertising_Text_RuntimeField2Unsigned = 0xa3b93u; +inline constexpr auto Advertising_Text_RuntimeFieldUnsigned = 0xa388au; +inline constexpr auto AlltimeTable_AlltimeTableFromGame_RuntimeField = 0xa396a; +inline constexpr auto AlltimeTable_Layout_ExecutableField = 0xa3963; +inline constexpr auto AlltimeTable_Render_ExecutableField = 0xa1030; +inline constexpr auto AlltimeTable_Render_ExecutableField2 = 0xa1033; +inline constexpr auto AlltimeTable_Render_ExecutableField3 = 0xa1036; +inline constexpr auto AlltimeTable_Render_ExecutableField4 = 0xa1038; +inline constexpr auto AlltimeTable_Render_ExecutableField5 = 0xa103a; +inline constexpr auto AlltimeTable_Render_ExecutableField6 = 0xa103d; +inline constexpr auto AlltimeTable_Render_ExecutableField7 = 0xa1042; +inline constexpr auto AlltimeTable_Render_ExecutableField8 = 0xa1044; +inline constexpr auto AlltimeTable_TeamColor_RuntimeField = 0xa509f; +inline constexpr auto AlternateEventRoll = 0xa3649; +inline constexpr auto Analytics_FormatError_ExecutableField = 0xa21d0; +inline constexpr auto Analytics_FormatError_RuntimeField = 0xa39a4; +inline constexpr auto Analytics_FormatError_RuntimeField2 = 0xa39b6; +inline constexpr auto Analytics_FormatError_RuntimeField3 = 0xa39d8; +inline constexpr auto Analytics_FormatError_RuntimeField4 = 0xa3a20; +inline constexpr auto Analytics_Render_RuntimeField = 0xa39aa; +inline constexpr auto Analytics_Render_RuntimeField2 = 0xa39ae; +inline constexpr auto Analytics_Render_RuntimeField3 = 0xa39c8; +inline constexpr auto Analytics_SourceAssetMaskE_RuntimeField = 0xbd710; +inline constexpr auto Analytics_SourceAssetMaskE_RuntimeFieldUnsigned = 0xbd710u; +inline constexpr auto Audio_MatchSoundEnabled_RuntimeField = 0xa24fb; +inline constexpr auto Audio_OriginalAudioAssets_RuntimeField = 0xa5545; +inline constexpr auto Audio_OriginalAudioAssets_RuntimeField2 = 0xa9c41; +inline constexpr auto Audio_OriginalAudioOptions_ExecutableField = 0xa24fc; +inline constexpr auto Audio_OriginalAudioOptions_ExecutableField2 = 0xa24fd; +inline constexpr auto AutomaticTakersLabel = 0x80ce3; +inline constexpr auto BalancePlan_BalanceFromGame_ExecutableField = 0xaec1c; +inline constexpr auto BalancePlan_BalanceFromGame_RuntimeField = 0xafb6b; +inline constexpr auto BalancePlan_BalanceFromGame_RuntimeField2 = 0xbd102; +inline constexpr auto BalancePlan_BalanceFromGame_TextPointer = 0xaec20; +inline constexpr auto BalancePlan_BalanceFromGame_TextPointer2 = 0xaec24; +inline constexpr auto BalancePlan_DrawButtons_TextPointer = 0xade30; +inline constexpr auto BalancePlan_DrawButtons_TextPointer2 = 0xaec0c; +inline constexpr auto BalancePlan_DrawRows_RuntimeField = 0xa485a; +inline constexpr auto BalancePlan_DrawRows_RuntimeField2 = 0xa485b; +inline constexpr auto BalancePlan_DrawRows_TextPointer = 0xa1521; +inline constexpr auto BalancePlan_DrawRows_TextPointer2 = 0xa485c; +inline constexpr auto BalancePlan_DrawRows_TextPointer3 = 0xade10; +inline constexpr auto BalancePlan_DrawRows_TextPointer4 = 0xade18; +inline constexpr auto BalancePlan_DrawRows_TextPointer5 = 0xaea44; +inline constexpr auto BalancePlan_DrawRows_TextPointer6 = 0xaec10; +inline constexpr auto BalancePlan_DrawRows_TextPointer7 = 0xaec14; +inline constexpr auto BalancePlan_DrawRows_TextPointer8 = 0xaec18; +inline constexpr auto BalancePlan_Fill_TextPointer = 0xaec08; +inline constexpr auto BankCredit_BankCreditContext_RuntimeField = 0xa1434; +inline constexpr auto BankCredit_BankCreditContext_RuntimeField2 = 0xa1438; +inline constexpr auto BankCredit_BankCreditContext_RuntimeField3 = 0xa44f6; +inline constexpr auto Bank_DrawCreditFeeConfirmation_ExecutableField = 0xaf220; +inline constexpr auto Bank_DrawCreditFeeConfirmation_ExecutableField2 = 0xaf224; +inline constexpr auto Bank_DrawPropertyCard_TextPointer = 0xa1414; +inline constexpr auto Bank_DrawPropertyCard_TextPointer2 = 0xaf1d0; +inline constexpr auto Bank_DrawPropertyCard_TextPointer3 = 0xaf1d4; +inline constexpr auto Bank_FinishCredit_RuntimeField = 0xa447d; +inline constexpr auto Bank_FinishCredit_RuntimeField2 = 0xa448d; +inline constexpr auto Bank_FinishCredit_RuntimeField3 = 0xa44a1; +inline constexpr auto Bank_FinishCredit_RuntimeField4 = 0xa44a9; +inline constexpr auto Bank_FinishCredit_RuntimeField5 = 0xa44be; +inline constexpr auto Bank_FinishCredit_RuntimeField6 = 0xa44c2; +inline constexpr auto Bank_FormatError_ExecutableField = 0xa140f; +inline constexpr auto Bank_FormatError_ExecutableField2 = 0xae308; +inline constexpr auto Bank_FormatError_ExecutableField3 = 0xaf1fc; +inline constexpr auto Bank_FormatError_RuntimeField = 0xa44b1; +inline constexpr auto Bank_FormatError_RuntimeField10 = 0xa44e7; +inline constexpr auto Bank_FormatError_RuntimeField11 = 0xa44ea; +inline constexpr auto Bank_FormatError_RuntimeField12 = 0xa44ed; +inline constexpr auto Bank_FormatError_RuntimeField13 = 0xa44f0; +inline constexpr auto Bank_FormatError_RuntimeField14 = 0xa44f3; +inline constexpr auto Bank_FormatError_RuntimeField15 = 0xa4527; +inline constexpr auto Bank_FormatError_RuntimeField16 = 0xa452b; +inline constexpr auto Bank_FormatError_RuntimeField17 = 0xa452f; +inline constexpr auto Bank_FormatError_RuntimeField18 = 0xae0fc; +inline constexpr auto Bank_FormatError_RuntimeField19 = 0xae338; +inline constexpr auto Bank_FormatError_RuntimeField2 = 0xa44b2; +inline constexpr auto Bank_FormatError_RuntimeField3 = 0xa44d2; +inline constexpr auto Bank_FormatError_RuntimeField4 = 0xa44d5; +inline constexpr auto Bank_FormatError_RuntimeField5 = 0xa44d8; +inline constexpr auto Bank_FormatError_RuntimeField6 = 0xa44db; +inline constexpr auto Bank_FormatError_RuntimeField7 = 0xa44de; +inline constexpr auto Bank_FormatError_RuntimeField8 = 0xa44e1; +inline constexpr auto Bank_FormatError_RuntimeField9 = 0xa44e4; +inline constexpr auto Bank_FormatError_TextPointer = 0xaf1e4; +inline constexpr auto Bank_FormatError_TextPointer2 = 0xaf1e8; +inline constexpr auto Bank_FormatError_TextPointer3 = 0xaf1ec; +inline constexpr auto Bank_FormatError_TextPointer4 = 0xaf1f4; +inline constexpr auto Bank_FormatError_TextPointer5 = 0xaf1f8; +inline constexpr auto Bank_FormatError_TextPointer6 = 0xaf200; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField = 0xa1408; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField2 = 0xa1412; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField3 = 0xa1417; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField4 = 0xa1419; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField5 = 0xa160c; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField6 = 0xa160e; +inline constexpr auto Bank_OriginalToUtf8_ExecutableField7 = 0xa1610; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField = 0xa2188; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField2 = 0xa44b5; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField3 = 0xa44bc; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField4 = 0xa44cb; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField5 = 0xac7b4; +inline constexpr auto Bank_OriginalToUtf8_RuntimeField6 = 0xae34c; +inline constexpr auto Bank_OriginalToUtf8_TextPointer = 0xa1410; +inline constexpr auto Bank_OriginalToUtf8_TextPointer2 = 0xa141e; +inline constexpr auto Bank_OriginalToUtf8_TextPointer3 = 0xae368; +inline constexpr auto Bank_OriginalToUtf8_TextPointer4 = 0xae380; +inline constexpr auto Bank_OriginalToUtf8_TextPointer5 = 0xaf1f0; +inline constexpr auto Bank_OriginalToUtf8_TextPointer6 = 0xaf204; +inline constexpr auto Bank_OriginalToUtf8_TextPointer7 = 0xaf208; +inline constexpr auto Bank_OriginalToUtf8_TextPointer8 = 0xaf20c; +inline constexpr auto CalendarDay = 0xbb254; +inline constexpr auto CalendarFirstLeague = 0xa2c12; +inline constexpr auto CalendarLeagueCounts = 0xa2c0a; +inline constexpr auto CalendarState_CalendarFromGame_ExecutableField = 0xa24ea; +inline constexpr auto CalendarState_CalendarFromGame_ExecutableField2 = 0xa24f5; +inline constexpr auto CalendarState_FormatError_RuntimeField = 0xa258b; +inline constexpr auto CalendarState_FormatError_RuntimeField2 = 0xa2594; +inline constexpr auto CalendarState_FormatError_RuntimeField2Unsigned = 0xa2594u; +inline constexpr auto CalendarState_FormatError_RuntimeField3 = 0xafae6; +inline constexpr auto Calendar_Information_ExecutableField = 0xa114c; +inline constexpr auto Calendar_Information_TextPointer = 0xa114f; +inline constexpr auto Calendar_Information_TextPointer2 = 0xae6f8; +inline constexpr auto Calendar_Information_TextPointer3 = 0xaf0c8; +inline constexpr auto Calendar_Information_TextPointer4 = 0xaf0cc; +inline constexpr auto Calendar_Information_TextPointer5 = 0xaf0d0; +inline constexpr auto Calendar_Information_TextPointer6 = 0xaf0d4; +inline constexpr auto Calendar_Render_ExecutableField2Unsigned = 0xaf0c0U; +inline constexpr auto Calendar_Render_ExecutableField3Unsigned = 0xaf0c4U; +inline constexpr auto Calendar_Render_ExecutableFieldUnsigned = 0xaf0bcU; +inline constexpr auto Calendar_Render_TextPointer = 0xae0c0; +inline constexpr auto Calendar_Render_TextPointer2 = 0xae448; +inline constexpr auto CareerDuration = 0xbdb76; +inline constexpr auto CareerDurationUnsigned = 0xbdb76u; +inline constexpr auto CareerSession_AdvanceLeagueFamily_ExecutableField = 0xafb5b; +inline constexpr auto CareerSession_AdvertisingSessionUnchanged_ExecutableField = 0xafb5e; +inline constexpr auto CareerSession_AnyOf_ExecutableField = 0xb5eb4; +inline constexpr auto CareerSession_AnyOf_ExecutableFieldUnsigned = 0xb5eb4u; +inline constexpr auto CareerSession_ApplyBalanceSourceStyle_ExecutableField = 0xbdac4; +inline constexpr auto CareerSession_BeginFriendlyOpponentTable_ExecutableField = 0xa4548; +inline constexpr auto CareerSession_BeginFriendlyOpponentTable_ExecutableField2 = 0xbb46e; +inline constexpr auto CareerSession_BeginFriendlyOpponentTable_RuntimeField = 0xa2bc4; +inline constexpr auto CareerSession_BeginFriendlyOpponentTable_RuntimeField2 = 0xafb5c; +inline constexpr auto CareerSession_CloseLeagueFamily_ExecutableField = 0xbb138; +inline constexpr auto CareerSession_CurrentLeagueTableDispatch_ExecutableField = 0xaec80; +inline constexpr auto CareerSession_CurrentLeagueTableDispatch_ExecutableField2 = 0xaec84; +inline constexpr auto CareerSession_DataDirectory_RuntimeField = 0xa2c3e; +inline constexpr auto CareerSession_DataDirectory_RuntimeField2 = 0xa2c42; +inline constexpr auto CareerSession_DataDirectory_RuntimeField3 = 0xa2c52; +inline constexpr auto CareerSession_DataDirectory_RuntimeField4 = 0xa2c66; +inline constexpr auto CareerSession_DispatchDesktopLayout_RuntimeField = 0xa250e; +inline constexpr auto CareerSession_DispatchDesktopLayout_RuntimeField2 = 0xa2517; +inline constexpr auto CareerSession_DispatchLeagueTableControl_RuntimeField = 0xa454d; +inline constexpr auto CareerSession_DispatchLeagueTableControl_RuntimeField2 = 0xbb834; +inline constexpr auto CareerSession_DispatchLineup_RuntimeField = 0xa2c30; +inline constexpr auto CareerSession_DispatchLiveSubstitution_ExecutableField = 0xa366c; +inline constexpr auto CareerSession_DispatchLiveTactic_RuntimeField = 0xa20eb; +inline constexpr auto CareerSession_DispatchLiveTactic_RuntimeField2 = 0xa20f3; +inline constexpr auto CareerSession_DispatchLiveTactic_RuntimeField3 = 0xa2504; +inline constexpr auto CareerSession_DispatchOtherGames_RuntimeField = 0xbb13c; +inline constexpr auto CareerSession_DispatchPoachUi_ExecutableField = 0xbbcde; +inline constexpr auto CareerSession_DispatchPoachUi_ExecutableFieldUnsigned = 0xbbcdeu; +inline constexpr auto CareerSession_DispatchPoachUi_TextPointer = 0xaf260; +inline constexpr auto CareerSession_DispatchPoachUi_TextPointer2 = 0xaf268; +inline constexpr auto CareerSession_DispatchPoachUi_TextPointer3 = 0xaf27c; +inline constexpr auto CareerSession_DispatchSettings_RuntimeField = 0xa2309; +inline constexpr auto CareerSession_DispatchSettings_TextPointer = 0xaeb50; +inline constexpr auto CareerSession_DispatchSettings_TextPointer2 = 0xaeb54; +inline constexpr auto CareerSession_DispatchStadium_RuntimeField = 0xa36d1; +inline constexpr auto CareerSession_DispatchStadium_RuntimeField2 = 0xa37e5; +inline constexpr auto CareerSession_DispatchStrengths_ExecutableField = 0xa253d; +inline constexpr auto CareerSession_DispatchStrengths_ExecutableField2 = 0xbbcd4; +inline constexpr auto CareerSession_DispatchStrengths_ExecutableField3 = 0xbbcd5; +inline constexpr auto CareerSession_DispatchStrengths_ExecutableField4 = 0xbbcd6; +inline constexpr auto CareerSession_DispatchStrengths_ExecutableField5 = 0xbbcd7; +inline constexpr auto CareerSession_DispatchToto_RuntimeField = 0xbdb95; +inline constexpr auto CareerSession_DispatchTransferOffer_ExecutableField = 0xbbcdd; +inline constexpr auto CareerSession_DispatchTransferOffer_ExecutableField2 = 0xbbce1; +inline constexpr auto CareerSession_DispatchTransferOffer_ExecutableField2Unsigned = 0xbbce1u; +inline constexpr auto CareerSession_DispatchTransferOffer_ExecutableFieldUnsigned = 0xbbcddu; +inline constexpr auto CareerSession_FormatError_ExecutableField = 0xb5f7c; +inline constexpr auto CareerSession_FormatError_ExecutableField2 = 0xbbcc0; +inline constexpr auto CareerSession_FormatError_ExecutableField3 = 0xbd900; +inline constexpr auto CareerSession_FormatError_ExecutableField4 = 0xbd901; +inline constexpr auto CareerSession_FormatError_ExecutableField5 = 0xbdac5; +inline constexpr auto CareerSession_FormatError_ExecutableField6 = 0xbdac6; +inline constexpr auto CareerSession_FormatError_ExecutableField7 = 0xbdac7; +inline constexpr auto CareerSession_FormatError_ExecutableField8 = 0xbdb8b; +inline constexpr auto CareerSession_FormatError_RuntimeField = 0xa24fe; +inline constexpr auto CareerSession_FormatError_RuntimeField2 = 0xa2546; +inline constexpr auto CareerSession_FormatError_RuntimeField3 = 0xa25b4; +inline constexpr auto CareerSession_FormatError_RuntimeField4 = 0xa2c1b; +inline constexpr auto CareerSession_FormatError_RuntimeField5 = 0xa3fd4; +inline constexpr auto CareerSession_FormatError_RuntimeField6 = 0xa5057; +inline constexpr auto CareerSession_FormatError_RuntimeField7 = 0xa509d; +inline constexpr auto CareerSession_FormatError_RuntimeField8 = 0xbb83f; +inline constexpr auto CareerSession_FormatError_RuntimeField9 = 0xbd8ec; +inline constexpr auto CareerSession_FormatError_TextPointer = 0xa1466; +inline constexpr auto CareerSession_FormatError_TextPointer2 = 0xadf74; +inline constexpr auto CareerSession_FormatError_TextPointer3 = 0xaec88; +inline constexpr auto CareerSession_FormatError_TextPointer4 = 0xaec8c; +inline constexpr auto CareerSession_FormatError_TextPointer5 = 0xaeca4; +inline constexpr auto CareerSession_FormatError_TextPointer6 = 0xaef50; +inline constexpr auto CareerSession_FormatError_TextPointer7 = 0xaef54; +inline constexpr auto CareerSession_FormatError_TextPointer8 = 0xaef7c; +inline constexpr auto CareerSession_FormatError_TextPointer9 = 0xaef80; +inline constexpr auto CareerSession_FormatNumber_ExecutableField = 0xa1373; +inline constexpr auto CareerSession_FormatNumber_ExecutableField2 = 0xa1380; +inline constexpr auto CareerSession_FormatNumber_TextPointer = 0xa137e; +inline constexpr auto CareerSession_InitializeClubModalRuntime_ExecutableField = 0xa25c0; +inline constexpr auto CareerSession_InitializeClubModalRuntime_ExecutableFieldUnsigned = 0xa25c0u; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField = 0xa2be9; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField2 = 0xa2bf2; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField3 = 0xa2c00; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField4 = 0xa2c0b; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField5 = 0xa2c13; +inline constexpr auto CareerSession_InstallLeagueSizes_RuntimeField6 = 0xa2c34; +inline constexpr auto CareerSession_Int32T_TextPointer = 0xaeffc; +inline constexpr auto CareerSession_Int32T_TextPointer2 = 0xaf21c; +inline constexpr auto CareerSession_Int32T_TextPointer3 = 0xaf228; +inline constexpr auto CareerSession_Int32T_TextPointer4 = 0xaf22c; +inline constexpr auto CareerSession_Int32T_TextPointer5 = 0xaf230; +inline constexpr auto CareerSession_Invalid_RuntimeField = 0xa42f9; +inline constexpr auto CareerSession_Invalid_RuntimeField2 = 0xbbcd8; +inline constexpr auto CareerSession_LiveBoundaryFamilyScope_ExecutableField = 0xbdb84; +inline constexpr auto CareerSession_Name_TextPointer = 0xaf100; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField = 0xa24eb; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField2 = 0xbb46c; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField3 = 0xbb46d; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField4 = 0xbb836; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField5 = 0xbb837; +inline constexpr auto CareerSession_PairingsRuntimeDraw_ExecutableField6 = 0xbb841; +inline constexpr auto CareerSession_Reject_TextPointer = 0xaed10; +inline constexpr auto CareerSession_Reject_TextPointer2 = 0xaed14; +inline constexpr auto CareerSession_Reject_TextPointer3 = 0xaed18; +inline constexpr auto CareerSession_Reject_TextPointer4 = 0xaed1c; +inline constexpr auto CareerSession_Reject_TextPointer5 = 0xaed24; +inline constexpr auto CareerSession_Reject_TextPointer6 = 0xaed28; +inline constexpr auto CareerSession_Reject_TextPointer7 = 0xaed30; +inline constexpr auto CareerSession_Reject_TextPointer8 = 0xaed34; +inline constexpr auto CareerSession_Reject_TextPointer9 = 0xaed38; +inline constexpr auto CareerSession_RuntimeError_ExecutableField = 0xa28c2; +inline constexpr auto CareerSession_RuntimeError_ExecutableField2 = 0xa290a; +inline constexpr auto CareerSession_RuntimeError_ExecutableField3 = 0xa2982; +inline constexpr auto CareerSession_RuntimeError_RuntimeField = 0xa295a; +inline constexpr auto CareerSession_RuntimeError_RuntimeField2 = 0xa296a; +inline constexpr auto CareerSession_RuntimeError_RuntimeField3 = 0xa29c2; +inline constexpr auto CareerSession_RuntimeError_RuntimeField4 = 0xafb60; +inline constexpr auto CareerSession_Save_RuntimeField = 0xaf974; +inline constexpr auto CareerSession_SportschauSourceOptions_ExecutableField = 0xa5088; +inline constexpr auto Career_BuildStadium_RuntimeField = 0xa3771; +inline constexpr auto Career_BuildStadium_RuntimeField2 = 0xa37e6; +inline constexpr auto Career_BuildStadium_RuntimeField3 = 0xa37e7; +inline constexpr auto Career_BuildStadium_RuntimeField4 = 0xa50d0; +inline constexpr auto Career_CareerAddManager_ExecutableField = 0xa50d4; +inline constexpr auto Career_CareerAddManager_RuntimeField = 0xa252d; +inline constexpr auto Career_CareerAddManager_RuntimeField2 = 0xbd4bc; +inline constexpr auto Career_CareerManagersEnd_RuntimeField = 0xbb86c; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField = 0xa2c76; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField10 = 0xa2fbe; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField11 = 0xa2fda; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField12 = 0xa2fe6; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField13 = 0xa3002; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField14 = 0xa300e; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField15 = 0xa302a; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField16 = 0xa3036; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField17 = 0xa311a; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField18 = 0xa3126; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField19 = 0xb5e34; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField19Unsigned = 0xb5e34u; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField2 = 0xa2ec2; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField20 = 0xb5eac; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField21 = 0xb5ebc; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField22 = 0xb5efc; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField23 = 0xb5f8c; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField24 = 0xb609c; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField25 = 0xb6134; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField25Unsigned = 0xb6134u; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField26 = 0xb623c; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField27 = 0xb6278; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField28 = 0xbb144; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField29 = 0xbb16c; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField3 = 0xa2ece; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField30 = 0xbb190; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField31 = 0xbb464; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField4 = 0xa2ed2; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField5 = 0xa2eea; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField6 = 0xa2f8a; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField7 = 0xa2f96; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField8 = 0xa2f9a; +inline constexpr auto Career_CompetitionPointersEnglish_ExecutableField9 = 0xa2fb2; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField = 0x776a8; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField10 = 0xa3bb8; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField11 = 0xa3bb9; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField12 = 0xa3bca; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField13 = 0xb6034; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField14 = 0xbb180; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField14Unsigned = 0xbb180u; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField15 = 0xbb1d0; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField16 = 0xbb1e8; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField17 = 0xbb310; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField18 = 0xbb3a8; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField2 = 0xa2e7a; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField3 = 0xa2e9a; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField4 = 0xa2ea6; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField5 = 0xa2ef6; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField6 = 0xa2f3a; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField7 = 0xa2f46; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField8 = 0xa2f62; +inline constexpr auto Career_CompetitionPointersEnglish_RuntimeField9 = 0xa2f6e; +inline constexpr auto Career_CompetitionPointers_ExecutableField = 0xbb3dc; +inline constexpr auto Career_CompetitionPointers_RuntimeField = 0xa31e2; +inline constexpr auto Career_CompetitionPointers_RuntimeField2 = 0xa31ea; +inline constexpr auto Career_CompetitionPointers_RuntimeField3 = 0xa31ee; +inline constexpr auto Career_CompetitionPointers_RuntimeField4 = 0xa3bc0; +inline constexpr auto Career_CompetitionPointers_RuntimeField5 = 0xa3bc5; +inline constexpr auto Career_EuropeanClub_ExecutableField = 0xbb839; +inline constexpr auto Career_EuropeanClub_ExecutableField2 = 0xbb83a; +inline constexpr auto Career_EuropeanClub_ExecutableField2Unsigned = 0xbb83au; +inline constexpr auto Career_EuropeanClub_ExecutableField3 = 0xbb83e; +inline constexpr auto Career_EuropeanClub_ExecutableField3Unsigned = 0xbb83eu; +inline constexpr auto Career_EuropeanClub_ExecutableFieldUnsigned = 0xbb839u; +inline constexpr auto Career_GermanRoundTable_ExecutableField = 0x6ee40; +inline constexpr auto Career_GermanRoundTable_ExecutableField2 = 0x6eea0; +inline constexpr auto Career_GermanRoundTable_ExecutableField3 = 0x6eed4; +inline constexpr auto Career_GermanRoundTable_ExecutableField4 = 0x6f0bc; +inline constexpr auto Career_NewCareerMarketsAndMoods_ExecutableField = 0xaeaf8; +inline constexpr auto Career_NewCareerMarketsAndMoods_ExecutableField2 = 0xaeafc; +inline constexpr auto Career_NewCareerMarketsAndMoods_ExecutableField3 = 0xaeb00; +inline constexpr auto Career_NewCareerMarketsAndMoods_ExecutableField4 = 0xaeb04; +inline constexpr auto Career_NewCareerMarketsAndMoods_RuntimeField = 0xb1de4; +inline constexpr auto Career_NewCareerMarketsAndMoods_RuntimeField2 = 0xbb140; +inline constexpr auto Career_Put_ExecutableField3 = 0xbb4d3; +inline constexpr auto Career_RemoveJoinLoans_RuntimeField = 0xab908; +inline constexpr auto Career_RemoveJoinTransfers_RuntimeField = 0xbb7a4; +inline constexpr auto ChampionshipBonusText = 0xa1534; +inline constexpr auto ClubAuxiliaryBytes = 0xba3b8; +inline constexpr auto ClubAuxiliaryWords = 0xba3bc; +inline constexpr auto ClubBadgeSelectors = 0xba378; +inline constexpr auto ClubIdentities = 0xba388; +inline constexpr auto ClubInfo_FormatError_RuntimeField = 0xbb884; +inline constexpr auto ClubInfo_FormatError_RuntimeField2 = 0xbbcb0; +inline constexpr auto ClubInfo_Raw_ExecutableField = 0xa1160; +inline constexpr auto ClubInfo_Raw_ExecutableField2 = 0xa1173; +inline constexpr auto ClubInfo_Raw_RuntimeField = 0xa4bc1; +inline constexpr auto ClubInfo_Raw_RuntimeField2 = 0xa4bc3; +inline constexpr auto ClubInfo_Raw_RuntimeField3 = 0xa4f8e; +inline constexpr auto ClubInfo_Raw_TextPointer = 0xae138; +inline constexpr auto ClubInfo_Raw_TextPointer2 = 0xae13c; +inline constexpr auto ClubInfo_Raw_TextPointer3 = 0xae140; +inline constexpr auto ClubInfo_Render_ExecutableField = 0xa1165; +inline constexpr auto ClubInfo_Render_ExecutableField2 = 0xa1168; +inline constexpr auto ClubInfo_Render_ExecutableField3 = 0xa116b; +inline constexpr auto ClubInfo_Render_ExecutableField4 = 0xa116e; +inline constexpr auto ClubInfo_Render_ExecutableField5 = 0xa1170; +inline constexpr auto ClubInfo_Render_TextPointer = 0xa1163; +inline constexpr auto ClubInfo_Render_TextPointer2 = 0xae7d4; +inline constexpr auto ClubInfo_Render_TextPointer3 = 0xaf160; +inline constexpr auto ClubInfo_Render_TextPointer4 = 0xaf164; +inline constexpr auto ClubInfo_Render_TextPointer5 = 0xaf168; +inline constexpr auto ClubInfo_Render_TextPointer6 = 0xaf244; +inline constexpr auto ClubInfo_Render_TextPointer7 = 0xaf248; +inline constexpr auto ClubKitSelectors = 0xbb68b; +inline constexpr auto ClubKitSelectorsUnsigned = 0xbb68bu; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField = 0xa25bb; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField2 = 0xa25bf; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 = 0xa2c36; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4 = 0xa364a; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField = 0xa2c4e; +inline constexpr auto ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 = 0xa3c9b; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField = 0xa13d8; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField2 = 0xae008; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField3 = 0xae8c0; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField4 = 0xaecd4; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField5 = 0xaed54; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField6 = 0xaed58; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField7 = 0xaed84; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField8 = 0xaed88; +inline constexpr auto ClubPlayerDetail_Copy_ExecutableField9 = 0xaed98; +inline constexpr auto ClubPlayerDetail_Copy_RuntimeField = 0xa4328; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer = 0xa13dd; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer10 = 0xaed90; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer11 = 0xaed94; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer2 = 0xa13e2; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer3 = 0xadff0; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer4 = 0xae01c; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer5 = 0xae038; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer6 = 0xae890; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer7 = 0xaed50; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer8 = 0xaed80; +inline constexpr auto ClubPlayerDetail_Copy_TextPointer9 = 0xaed8c; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField = 0xa3c7d; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField2 = 0xa3c82; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField3 = 0xa3c87; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField4 = 0xa3c8c; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField5 = 0xa3c91; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField6 = 0xa3c96; +inline constexpr auto ClubPlayerDetail_DrawPortrait_RuntimeField7 = 0xa3ca0; +inline constexpr auto ClubPlayerDetail_InvalidArgument_RuntimeField = 0xabce8; +inline constexpr auto ClubPlayerDetail_InvalidArgument_RuntimeField2 = 0xaf43d; +inline constexpr auto ClubPlayerDetail_InvalidArgument_RuntimeField3 = 0xbbce2; +inline constexpr auto ClubPlayerDetail_RenderCard_ExecutableField = 0xaed40; +inline constexpr auto ClubPlayerDetail_RenderCard_ExecutableField2 = 0xaed44; +inline constexpr auto ClubPlayerDetail_RenderCard_ExecutableField3 = 0xaed48; +inline constexpr auto ClubPlayerDetail_RenderCard_ExecutableField4 = 0xaed4c; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer = 0xa13da; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer10 = 0xaed78; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer11 = 0xaed7c; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer2 = 0xae014; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer3 = 0xaed5c; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer4 = 0xaed60; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer5 = 0xaed64; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer6 = 0xaed68; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer7 = 0xaed6c; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer8 = 0xaed70; +inline constexpr auto ClubPlayerDetail_RenderCard_TextPointer9 = 0xaed74; +inline constexpr auto ClubPlayerDetail_RenderStatistics_ExecutableField = 0xaded8; +inline constexpr auto ClubPlayerDetail_RenderStatistics_ExecutableField2 = 0xadedc; +inline constexpr auto ClubPlayerDetail_RenderStatistics_ExecutableField3 = 0xaec54; +inline constexpr auto ClubSeasonRecords = 0xbb1ec; +inline constexpr auto ClubShortNameOffsets = 0xb5d24; +inline constexpr auto CoachActive = 0xa3770; +inline constexpr auto CompactDialogFrame = 0xa366e; +inline constexpr auto CompetitionCalendar = 0xa25e6; +inline constexpr auto CompetitionSelection = 0xaf440; +inline constexpr auto ComputerBettingLimits = 0xa455c; +inline constexpr auto ContractExpiryWarningText = 0xa12cd; +inline constexpr auto Contracts_Out_ExecutableField = 0xadfdc; +inline constexpr auto Contracts_Out_ExecutableField10 = 0xaecd0; +inline constexpr auto Contracts_Out_ExecutableField11 = 0xaecdc; +inline constexpr auto Contracts_Out_ExecutableField12 = 0xaece0; +inline constexpr auto Contracts_Out_ExecutableField13 = 0xaece4; +inline constexpr auto Contracts_Out_ExecutableField14 = 0xaecec; +inline constexpr auto Contracts_Out_ExecutableField15 = 0xaecf4; +inline constexpr auto Contracts_Out_ExecutableField16 = 0xaecf8; +inline constexpr auto Contracts_Out_ExecutableField17 = 0xaed08; +inline constexpr auto Contracts_Out_ExecutableField18 = 0xaed0c; +inline constexpr auto Contracts_Out_ExecutableField19 = 0xaed20; +inline constexpr auto Contracts_Out_ExecutableField2 = 0xadfe4; +inline constexpr auto Contracts_Out_ExecutableField3 = 0xadfe8; +inline constexpr auto Contracts_Out_ExecutableField4 = 0xae8a4; +inline constexpr auto Contracts_Out_ExecutableField5 = 0xaecbc; +inline constexpr auto Contracts_Out_ExecutableField6 = 0xaecc0; +inline constexpr auto Contracts_Out_ExecutableField7 = 0xaecc4; +inline constexpr auto Contracts_Out_ExecutableField8 = 0xaecc8; +inline constexpr auto Contracts_Out_ExecutableField9 = 0xaeccc; +inline constexpr auto Contracts_Out_TextPointer = 0xa13dc; +inline constexpr auto Contracts_Out_TextPointer2 = 0xa430d; +inline constexpr auto Contracts_Out_TextPointer3 = 0xaecd8; +inline constexpr auto Contracts_Out_TextPointer4 = 0xaece8; +inline constexpr auto Contracts_Out_TextPointer5 = 0xaecf0; +inline constexpr auto Contracts_Out_TextPointer6 = 0xaecfc; +inline constexpr auto Contracts_Out_TextPointer7 = 0xaed00; +inline constexpr auto Contracts_Out_TextPointer8 = 0xaed04; +inline constexpr auto Contracts_RenderRoster_ExecutableField = 0xa1161; +inline constexpr auto Contracts_RenderRoster_ExecutableField2 = 0xa1177; +inline constexpr auto Contracts_RenderRoster_ExecutableField3 = 0xa1179; +inline constexpr auto Contracts_RenderRoster_ExecutableField4 = 0xa117f; +inline constexpr auto Contracts_RenderRoster_TextPointer = 0xa21b8; +inline constexpr auto Contracts_RenderRoster_TextPointer2 = 0xaecb4; +inline constexpr auto Contracts_RenderRoster_TextPointer3 = 0xaf16c; +inline constexpr auto Contracts_RenderRoster_TextPointer4 = 0xaf170; +inline constexpr auto Controller_CalendarFromGame_TextPointer = 0xaf028; +inline constexpr auto Controller_ClubFriendlyState_TextPointer = 0xaf120; +inline constexpr auto Controller_FormatError_ExecutableField = 0xa0020; +inline constexpr auto Controller_FormatError_ExecutableField2 = 0xa24fa; +inline constexpr auto Controller_FormatError_RuntimeField = 0xa2506; +inline constexpr auto Controller_FormatError_RuntimeField2 = 0xa250f; +inline constexpr auto Controller_FormatError_RuntimeField2Unsigned = 0xa250fu; +inline constexpr auto Controller_FormatError_RuntimeField3 = 0xa252a; +inline constexpr auto Controller_FormatError_RuntimeField3Unsigned = 0xa252au; +inline constexpr auto Controller_FormatError_RuntimeFieldUnsigned = 0xa2506u; +inline constexpr auto Controller_FormatError_TextPointer = 0xaf094; +inline constexpr auto Controller_FormatError_TextPointer2 = 0xaf124; +inline constexpr auto Controller_FormatError_TextPointer3 = 0xaf128; +inline constexpr auto CornerTakerLabel = 0x80cdb; +inline constexpr auto Coupon = 0xaf834; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer = 0xa10f2; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer10 = 0xa145f; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer11 = 0xa1464; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer2 = 0xa1440; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer3 = 0xa1442; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer4 = 0xa1446; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer5 = 0xa1449; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer6 = 0xa144b; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer7 = 0xa1450; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer8 = 0xa1455; +inline constexpr auto CupDraw_DrawGroupOverview_TextPointer9 = 0xa1456; +inline constexpr auto CupDraw_FormatError_ExecutableField = 0xa1614; +inline constexpr auto CupDraw_FormatError_ExecutableField2 = 0xa1616; +inline constexpr auto CupDraw_FormatError_ExecutableField3 = 0xa50ac; +inline constexpr auto CupDraw_FormatError_ExecutableField4 = 0xae6dc; +inline constexpr auto CupDraw_FormatError_ExecutableField5 = 0xae704; +inline constexpr auto CupDraw_FormatError_ExecutableField6 = 0xae70c; +inline constexpr auto CupDraw_FormatError_RuntimeField = 0xa2547; +inline constexpr auto CupDraw_FormatError_RuntimeField2 = 0xb6ea8; +inline constexpr auto CupDraw_FormatError_RuntimeField3 = 0xb9ad8; +inline constexpr auto CupDraw_FormatError_TextPointer = 0xa1612; +inline constexpr auto CupDraw_FormatError_TextPointer2 = 0xa1619; +inline constexpr auto CupDraw_FormatError_TextPointer3 = 0xa161e; +inline constexpr auto CupDraw_FormatError_TextPointer4 = 0xae5d0; +inline constexpr auto CupDraw_FormatError_TextPointer5 = 0xaeb08; +inline constexpr auto CupDraw_FormatError_TextPointer6 = 0xaec9c; +inline constexpr auto CupDraw_GroupMarker_RuntimeField = 0xa3bb4; +inline constexpr auto CupTable = 0xa2c6a; +inline constexpr auto Cup_AdvanceCup_ExecutableField = 0xab638; +inline constexpr auto Cup_AdvanceCup_RuntimeField = 0xa2545; +inline constexpr auto Cup_AdvanceCup_RuntimeField2 = 0xa301c; +inline constexpr auto Cup_AdvanceCup_RuntimeField3 = 0xafb5a; +inline constexpr auto Cup_AdvanceCup_RuntimeField4 = 0xafb5f; +inline constexpr auto Cup_AdvanceCup_RuntimeField5 = 0xbb146; +inline constexpr auto Cup_AdvanceCup_RuntimeField6 = 0xbdb0e; +inline constexpr auto Cup_AdvanceCup_RuntimeField6Unsigned = 0xbdb0eu; +inline constexpr auto Cup_AdvanceCup_RuntimeField7 = 0xbdb12; +inline constexpr auto Cup_MastersQualification_RuntimeField = 0xbd41c; +inline constexpr auto Cup_MastersQualification_TextPointer = 0xaf07c; +inline constexpr auto Cup_NationalTournamentEnd_RuntimeField = 0xa2dcc; +inline constexpr auto Cup_NationalTournamentEnd_RuntimeField2 = 0xa2dce; +inline constexpr auto Cup_NationalTournamentEnd_RuntimeField3 = 0xa2df4; +inline constexpr auto Cup_NationalTournamentEnd_RuntimeField4 = 0xa2df6; +inline constexpr auto Cup_NationalTournamentEnd_RuntimeField5 = 0xbd390; +inline constexpr auto Cup_PrepareFriendlies_RuntimeField = 0xab68c; +inline constexpr auto Cup_PrepareFriendlies_RuntimeField2 = 0xaf3c2; +inline constexpr auto Cup_RemoveCompetition_RuntimeField = 0xa25b1; +inline constexpr auto Cup_RemoveCompetition_RuntimeField2 = 0xa25b7; +inline constexpr auto CurrencyDivisor = 0xa25bc; +inline constexpr auto CurrencyMultiplier = 0xa25b8; +inline constexpr auto CurrencySuffixText = 0xa1404; +inline constexpr auto CurrentMatchday = 0xbd8f4; +inline constexpr auto DaysIntoSeason = 0xbb468; +inline constexpr auto DeskActions_CheckAdvertisingRenewal_TextPointer = 0xae23c; +inline constexpr auto DeskActions_CheckAdvertisingRenewal_TextPointer2 = 0xae240; +inline constexpr auto DeskActions_CheckAdvertisingRenewal_TextPointer3 = 0xae244; +inline constexpr auto DeskActions_CheckAdvertisingRenewal_TextPointer4 = 0xae248; +inline constexpr auto DeskActions_CheckAdvertisingRenewal_TextPointer5 = 0xae24c; +inline constexpr auto DeskActions_ConfigureTrainingCampData_RuntimeField = 0xa23e1; +inline constexpr auto DeskActions_ConfigureTrainingCampData_RuntimeField2 = 0xa2401; +inline constexpr auto DeskActions_EditorFail_RuntimeField = 0xaf977; +inline constexpr auto DeskActions_EditorFail_RuntimeField2 = 0xbdb8c; +inline constexpr auto DeskActions_EditorProject_ExecutableField = 0xae8a0; +inline constexpr auto DeskActions_EditorProject_ExecutableField2 = 0xaf320; +inline constexpr auto DeskActions_EditorProject_RuntimeField = 0xaf31c; +inline constexpr auto DeskActions_NationalOpponentManager_RuntimeField = 0xb9ad9; +inline constexpr auto DeskActions_OpenTransferOfferEditorSource_RuntimeField = 0xbbcdb; +inline constexpr auto DeskActions_Reject_ExecutableField = 0xaeecc; +inline constexpr auto DeskActions_SubmitPoolsCoupon_RuntimeField = 0xbda70; +inline constexpr auto DeskActions_SubmitTransferBidImpl_ExecutableField = 0xaf304; +inline constexpr auto DeskActions_SubmitTransferBidImpl_RuntimeField = 0xbb46f; +inline constexpr auto DeskActions_SubmitTransferOfferEditorSource_ExecutableField = 0xaf300; +inline constexpr auto DeskActions_SubmitTransferOfferEditorSource_RuntimeField = 0xaf2f0; +inline constexpr auto DeskActions_SubmitTransferOfferEditorSource_TextPointer = 0xaf2ec; +inline constexpr auto DeskActions_Unsupported_ExecutableField = 0xaf2f4; +inline constexpr auto DeskActions_Unsupported_ExecutableField2 = 0xaf308; +inline constexpr auto DeskActions_Unsupported_ExecutableField3 = 0xaf318; +inline constexpr auto DeskActions_Unsupported_RuntimeField = 0xbbcc8; +inline constexpr auto DeskActions_Unsupported_RuntimeFieldUnsigned = 0xbbcc8u; +inline constexpr auto DeskActions_Unsupported_TextPointer = 0xaf2f8; +inline constexpr auto DeskActions_Unsupported_TextPointer2 = 0xaf2fc; +inline constexpr auto DeskActions_Unsupported_TextPointer3 = 0xaf30c; +inline constexpr auto DeskActions_Unsupported_TextPointer4 = 0xaf310; +inline constexpr auto DeskActions_Unsupported_TextPointer5 = 0xaf314; +inline constexpr auto DeskDrawers_Curve_ExecutableField = 0xa187e; +inline constexpr auto DeskDrawers_Curve_RuntimeField = 0xa2bfb; +inline constexpr auto DeskDrawers_HeadToHead_ExecutableField = 0xa0009; +inline constexpr auto DeskDrawers_Recent_ExecutableField = 0xa0006; +inline constexpr auto DeskDrawers_Recent_ExecutableField2 = 0xa0008; +inline constexpr auto DeskDrawers_Recent_TextPointer = 0xa0004; +inline constexpr auto DeskPosition = 0xbdb77; +inline constexpr auto DeskRecords_FillRect_ExecutableField = 0xa16a4; +inline constexpr auto DeskRecords_FillRect_ExecutableField2 = 0xa16a6; +inline constexpr auto DeskRecords_FillRect_ExecutableField3 = 0xa16aa; +inline constexpr auto DeskRecords_FillRect_ExecutableField4 = 0xaec00; +inline constexpr auto DeskRecords_FillRect_ExecutableField5 = 0xaec04; +inline constexpr auto DeskRecords_FillRect_TextPointer = 0xa169f; +inline constexpr auto DeskRecords_FillRect_TextPointer2 = 0xa16a7; +inline constexpr auto DeskRecords_FillRect_TextPointer3 = 0xa16b3; +inline constexpr auto DeskRecords_FillRect_TextPointer4 = 0xaebf4; +inline constexpr auto DeskRecords_FillRect_TextPointer5 = 0xaebf8; +inline constexpr auto DeskRecords_FillRect_TextPointer6 = 0xaebfc; +inline constexpr auto DeskRecords_Teams_RuntimeField = 0xbd90c; +inline constexpr auto DeskState_DeskDate_RuntimeField = 0xa24e9; +inline constexpr auto DeskState_DeskFromGame_TextPointer = 0xae744; +inline constexpr auto DeskState_FormatError_ExecutableField2Unsigned = 0xa18a3u; +inline constexpr auto DeskState_FormatError_ExecutableField3 = 0xae708; +inline constexpr auto DeskState_FormatError_ExecutableField4 = 0xae750; +inline constexpr auto DeskState_FormatError_ExecutableFieldUnsigned = 0xa1896u; +inline constexpr auto DeskState_FormatError_RuntimeField = 0xa18b0; +inline constexpr auto DeskState_FormatError_RuntimeField2 = 0xa2505; +inline constexpr auto DeskState_FormatError_RuntimeField3 = 0xa2520; +inline constexpr auto DeskState_FormatError_RuntimeField4 = 0xae7d0; +inline constexpr auto Desk_EnterDesk_RuntimeField = 0xa2558; +inline constexpr auto Desk_SaveGameDraws_TextPointer = 0xaefa4; +inline constexpr auto Desk_SaveGameDraws_TextPointer2 = 0xaf104; +inline constexpr auto Desk_SaveGameDraws_TextPointer3 = 0xaf108; +inline constexpr auto Desk_SaveGameDraws_TextPointer4 = 0xaf10c; +inline constexpr auto Desk_SaveGameDraws_TextPointer5 = 0xaf110; +inline constexpr auto Desk_SaveGameDraws_TextPointer6 = 0xaf114; +inline constexpr auto Desktop_Copy_TextPointer = 0xa5139; +inline constexpr auto Desktop_Copy_TextPointer2 = 0xa513a; +inline constexpr auto Desktop_Key_RuntimeField = 0xa4ed5; +inline constexpr auto Desktop_Render_RuntimeField = 0xa18bc; +inline constexpr auto Desktop_Render_RuntimeField2 = 0xa18be; +inline constexpr auto Desktop_Render_RuntimeField3 = 0xa18c0; +inline constexpr auto Desktop_Render_TextPointer = 0xae370; +inline constexpr auto Desktops = 0xaccd8; +inline constexpr auto DesktopsUnsigned = 0xaccd8u; +inline constexpr auto Difficulty = 0xa2426; +inline constexpr auto DifficultyUnsigned = 0xa2426u; +inline constexpr auto EditorList = 0xb1ddc; +inline constexpr auto EditorListUnsigned = 0xb1ddcu; +inline constexpr auto EmptyString = 0xc0ff0; +inline constexpr auto EnDataStart = 0x6b000; +inline constexpr auto EnglishAdditionalCupField = 0x7d618; +inline constexpr auto EnglishAdditionalCupResults = 0x7d5f8; +inline constexpr auto EnglishContractExpiryWarningText = 0x6d921; +inline constexpr auto EnglishFaCupField = 0x7c670; +inline constexpr auto EnglishFaCupProperField = 0x7c728; +inline constexpr auto EnglishFaCupQualifyingField = 0x7c698; +inline constexpr auto EnglishFaCupResults = 0x7c5ea; +inline constexpr auto EnglishFaCupStageResults = 0x7c632; +inline constexpr auto EnglishLayoutTranslation = 0x6bcac; +inline constexpr auto EnglishLayoutTranslation10 = 0x6be18; +inline constexpr auto EnglishLayoutTranslation100 = 0x6d869; +inline constexpr auto EnglishLayoutTranslation101 = 0x6d86e; +inline constexpr auto EnglishLayoutTranslation102 = 0x6d873; +inline constexpr auto EnglishLayoutTranslation103 = 0x6d874; +inline constexpr auto EnglishLayoutTranslation104 = 0x6d876; +inline constexpr auto EnglishLayoutTranslation105 = 0x6d87d; +inline constexpr auto EnglishLayoutTranslation106 = 0x6d882; +inline constexpr auto EnglishLayoutTranslation107 = 0x6d8b4; +inline constexpr auto EnglishLayoutTranslation108 = 0x6d8b6; +inline constexpr auto EnglishLayoutTranslation109 = 0x6d8b8; +inline constexpr auto EnglishLayoutTranslation11 = 0x6be2c; +inline constexpr auto EnglishLayoutTranslation110 = 0x6d8bb; +inline constexpr auto EnglishLayoutTranslation111 = 0x6d8c4; +inline constexpr auto EnglishLayoutTranslation112 = 0x6d8c6; +inline constexpr auto EnglishLayoutTranslation113 = 0x6d8ca; +inline constexpr auto EnglishLayoutTranslation114 = 0x6d8cc; +inline constexpr auto EnglishLayoutTranslation115 = 0x6d8d0; +inline constexpr auto EnglishLayoutTranslation116 = 0x6d8d4; +inline constexpr auto EnglishLayoutTranslation117 = 0x6d8d8; +inline constexpr auto EnglishLayoutTranslation118 = 0x6d8e1; +inline constexpr auto EnglishLayoutTranslation119 = 0x6d8e8; +inline constexpr auto EnglishLayoutTranslation12 = 0x6be3c; +inline constexpr auto EnglishLayoutTranslation120 = 0x6d8f6; +inline constexpr auto EnglishLayoutTranslation121 = 0x6d8f8; +inline constexpr auto EnglishLayoutTranslation122 = 0x6d907; +inline constexpr auto EnglishLayoutTranslation123 = 0x6d9e6; +inline constexpr auto EnglishLayoutTranslation124 = 0x6d9e8; +inline constexpr auto EnglishLayoutTranslation125 = 0x6d9ea; +inline constexpr auto EnglishLayoutTranslation126 = 0x6d9ec; +inline constexpr auto EnglishLayoutTranslation127 = 0x6d9ee; +inline constexpr auto EnglishLayoutTranslation128 = 0x6d9f0; +inline constexpr auto EnglishLayoutTranslation129 = 0x6d9f3; +inline constexpr auto EnglishLayoutTranslation13 = 0x6be44; +inline constexpr auto EnglishLayoutTranslation130 = 0x6d9f7; +inline constexpr auto EnglishLayoutTranslation131 = 0x6d9fc; +inline constexpr auto EnglishLayoutTranslation132 = 0x6da18; +inline constexpr auto EnglishLayoutTranslation133 = 0x6da24; +inline constexpr auto EnglishLayoutTranslation134 = 0x6da40; +inline constexpr auto EnglishLayoutTranslation135 = 0x6da4c; +inline constexpr auto EnglishLayoutTranslation136 = 0x6da68; +inline constexpr auto EnglishLayoutTranslation137 = 0x6da74; +inline constexpr auto EnglishLayoutTranslation138 = 0x6da90; +inline constexpr auto EnglishLayoutTranslation139 = 0x6da9c; +inline constexpr auto EnglishLayoutTranslation14 = 0x6be48; +inline constexpr auto EnglishLayoutTranslation140 = 0x6daa1; +inline constexpr auto EnglishLayoutTranslation141 = 0x6dab9; +inline constexpr auto EnglishLayoutTranslation142 = 0x6dabb; +inline constexpr auto EnglishLayoutTranslation143 = 0x6dd94; +inline constexpr auto EnglishLayoutTranslation144 = 0x6dd96; +inline constexpr auto EnglishLayoutTranslation145 = 0x6ddd8; +inline constexpr auto EnglishLayoutTranslation146 = 0x6dde0; +inline constexpr auto EnglishLayoutTranslation147 = 0x6dde4; +inline constexpr auto EnglishLayoutTranslation148 = 0x6dde5; +inline constexpr auto EnglishLayoutTranslation149 = 0x6df74; +inline constexpr auto EnglishLayoutTranslation15 = 0x6be4c; +inline constexpr auto EnglishLayoutTranslation150 = 0x6e05c; +inline constexpr auto EnglishLayoutTranslation151 = 0x6e064; +inline constexpr auto EnglishLayoutTranslation152 = 0x6e06c; +inline constexpr auto EnglishLayoutTranslation153 = 0x6e074; +inline constexpr auto EnglishLayoutTranslation154 = 0x6e07c; +inline constexpr auto EnglishLayoutTranslation155 = 0x6e084; +inline constexpr auto EnglishLayoutTranslation156 = 0x6e08c; +inline constexpr auto EnglishLayoutTranslation157 = 0x6e094; +inline constexpr auto EnglishLayoutTranslation158 = 0x6e0b8; +inline constexpr auto EnglishLayoutTranslation159 = 0x6e0bb; +inline constexpr auto EnglishLayoutTranslation16 = 0x6be4f; +inline constexpr auto EnglishLayoutTranslation160 = 0x6e0d8; +inline constexpr auto EnglishLayoutTranslation161 = 0x6e110; +inline constexpr auto EnglishLayoutTranslation162 = 0x6e11c; +inline constexpr auto EnglishLayoutTranslation163 = 0x6e228; +inline constexpr auto EnglishLayoutTranslation164 = 0x6e264; +inline constexpr auto EnglishLayoutTranslation165 = 0x6e265; +inline constexpr auto EnglishLayoutTranslation166 = 0x6e267; +inline constexpr auto EnglishLayoutTranslation167 = 0x6e269; +inline constexpr auto EnglishLayoutTranslation168 = 0x6e26c; +inline constexpr auto EnglishLayoutTranslation169 = 0x6e26f; +inline constexpr auto EnglishLayoutTranslation17 = 0x6be58; +inline constexpr auto EnglishLayoutTranslation170 = 0x6e272; +inline constexpr auto EnglishLayoutTranslation171 = 0x6e274; +inline constexpr auto EnglishLayoutTranslation172 = 0x6e277; +inline constexpr auto EnglishLayoutTranslation173 = 0x6e27b; +inline constexpr auto EnglishLayoutTranslation174 = 0x6e27d; +inline constexpr auto EnglishLayoutTranslation175 = 0x6e283; +inline constexpr auto EnglishLayoutTranslation176 = 0x6e294; +inline constexpr auto EnglishLayoutTranslation177 = 0x6e29c; +inline constexpr auto EnglishLayoutTranslation178 = 0x6e2a4; +inline constexpr auto EnglishLayoutTranslation179 = 0x6e2ac; +inline constexpr auto EnglishLayoutTranslation18 = 0x6be5c; +inline constexpr auto EnglishLayoutTranslation180 = 0x6e300; +inline constexpr auto EnglishLayoutTranslation181 = 0x6e304; +inline constexpr auto EnglishLayoutTranslation182 = 0x6e308; +inline constexpr auto EnglishLayoutTranslation183 = 0x6e374; +inline constexpr auto EnglishLayoutTranslation184 = 0x6e378; +inline constexpr auto EnglishLayoutTranslation185 = 0x6e380; +inline constexpr auto EnglishLayoutTranslation186 = 0x6e388; +inline constexpr auto EnglishLayoutTranslation187 = 0x6e390; +inline constexpr auto EnglishLayoutTranslation188 = 0x6e394; +inline constexpr auto EnglishLayoutTranslation189 = 0x6e398; +inline constexpr auto EnglishLayoutTranslation19 = 0x6be60; +inline constexpr auto EnglishLayoutTranslation190 = 0x6e39c; +inline constexpr auto EnglishLayoutTranslation191 = 0x6e3a0; +inline constexpr auto EnglishLayoutTranslation192 = 0x6e3a4; +inline constexpr auto EnglishLayoutTranslation193 = 0x6e3b0; +inline constexpr auto EnglishLayoutTranslation194 = 0x6e3b4; +inline constexpr auto EnglishLayoutTranslation195 = 0x6e3e4; +inline constexpr auto EnglishLayoutTranslation196 = 0x6e3fb; +inline constexpr auto EnglishLayoutTranslation197 = 0x6e434; +inline constexpr auto EnglishLayoutTranslation198 = 0x6e43c; +inline constexpr auto EnglishLayoutTranslation199 = 0x6e440; +inline constexpr auto EnglishLayoutTranslation2 = 0x6bcb0; +inline constexpr auto EnglishLayoutTranslation20 = 0x6bea0; +inline constexpr auto EnglishLayoutTranslation200 = 0x6e448; +inline constexpr auto EnglishLayoutTranslation201 = 0x6e450; +inline constexpr auto EnglishLayoutTranslation202 = 0x6e45c; +inline constexpr auto EnglishLayoutTranslation203 = 0x6e465; +inline constexpr auto EnglishLayoutTranslation204 = 0x6e484; +inline constexpr auto EnglishLayoutTranslation205 = 0x6e486; +inline constexpr auto EnglishLayoutTranslation206 = 0x6e48c; +inline constexpr auto EnglishLayoutTranslation207 = 0x6e49c; +inline constexpr auto EnglishLayoutTranslation208 = 0x6e4b0; +inline constexpr auto EnglishLayoutTranslation209 = 0x6e4b8; +inline constexpr auto EnglishLayoutTranslation21 = 0x6bea1; +inline constexpr auto EnglishLayoutTranslation210 = 0x6e4c0; +inline constexpr auto EnglishLayoutTranslation211 = 0x6e4c1; +inline constexpr auto EnglishLayoutTranslation212 = 0x6e4c4; +inline constexpr auto EnglishLayoutTranslation213 = 0x6e4cc; +inline constexpr auto EnglishLayoutTranslation214 = 0x6e4dc; +inline constexpr auto EnglishLayoutTranslation215 = 0x6e510; +inline constexpr auto EnglishLayoutTranslation216 = 0x6e513; +inline constexpr auto EnglishLayoutTranslation217 = 0x6e515; +inline constexpr auto EnglishLayoutTranslation218 = 0x6e51f; +inline constexpr auto EnglishLayoutTranslation219 = 0x6e535; +inline constexpr auto EnglishLayoutTranslation22 = 0x6bea2; +inline constexpr auto EnglishLayoutTranslation220 = 0x6e578; +inline constexpr auto EnglishLayoutTranslation221 = 0x6e5ac; +inline constexpr auto EnglishLayoutTranslation222 = 0x6e5b0; +inline constexpr auto EnglishLayoutTranslation223 = 0x6e5b4; +inline constexpr auto EnglishLayoutTranslation224 = 0x6e5e0; +inline constexpr auto EnglishLayoutTranslation225 = 0x6e62c; +inline constexpr auto EnglishLayoutTranslation226 = 0x6e62d; +inline constexpr auto EnglishLayoutTranslation227 = 0x6e634; +inline constexpr auto EnglishLayoutTranslation228 = 0x6e635; +inline constexpr auto EnglishLayoutTranslation229 = 0x6e640; +inline constexpr auto EnglishLayoutTranslation23 = 0x6bf14; +inline constexpr auto EnglishLayoutTranslation230 = 0x6e644; +inline constexpr auto EnglishLayoutTranslation231 = 0x6e64c; +inline constexpr auto EnglishLayoutTranslation232 = 0x6e654; +inline constexpr auto EnglishLayoutTranslation233 = 0x6e65c; +inline constexpr auto EnglishLayoutTranslation234 = 0x6e6b4; +inline constexpr auto EnglishLayoutTranslation235 = 0x6e6b5; +inline constexpr auto EnglishLayoutTranslation236 = 0x6e6fc; +inline constexpr auto EnglishLayoutTranslation237 = 0x6e703; +inline constexpr auto EnglishLayoutTranslation238 = 0x6e704; +inline constexpr auto EnglishLayoutTranslation239 = 0x6e70c; +inline constexpr auto EnglishLayoutTranslation24 = 0x6bf1c; +inline constexpr auto EnglishLayoutTranslation240 = 0x6e714; +inline constexpr auto EnglishLayoutTranslation241 = 0x6e71c; +inline constexpr auto EnglishLayoutTranslation242 = 0x6e723; +inline constexpr auto EnglishLayoutTranslation243 = 0x6e724; +inline constexpr auto EnglishLayoutTranslation244 = 0x6e72c; +inline constexpr auto EnglishLayoutTranslation245 = 0x6e72d; +inline constexpr auto EnglishLayoutTranslation246 = 0x6e758; +inline constexpr auto EnglishLayoutTranslation247 = 0x6e75c; +inline constexpr auto EnglishLayoutTranslation248 = 0x6e7a6; +inline constexpr auto EnglishLayoutTranslation249 = 0x6e7a8; +inline constexpr auto EnglishLayoutTranslation25 = 0x6bf24; +inline constexpr auto EnglishLayoutTranslation250 = 0x6e7ab; +inline constexpr auto EnglishLayoutTranslation251 = 0x6e810; +inline constexpr auto EnglishLayoutTranslation252 = 0x6e818; +inline constexpr auto EnglishLayoutTranslation253 = 0x6e81c; +inline constexpr auto EnglishLayoutTranslation254 = 0x6e848; +inline constexpr auto EnglishLayoutTranslation255 = 0x6f0ec; +inline constexpr auto EnglishLayoutTranslation256 = 0x6f2ae; +inline constexpr auto EnglishLayoutTranslation257 = 0x6f2d4; +inline constexpr auto EnglishLayoutTranslation258 = 0x6f2e0; +inline constexpr auto EnglishLayoutTranslation259 = 0x6f2fc; +inline constexpr auto EnglishLayoutTranslation26 = 0x6bf2c; +inline constexpr auto EnglishLayoutTranslation260 = 0x6f300; +inline constexpr auto EnglishLayoutTranslation261 = 0x6f30c; +inline constexpr auto EnglishLayoutTranslation262 = 0x6f315; +inline constexpr auto EnglishLayoutTranslation263 = 0x6f31c; +inline constexpr auto EnglishLayoutTranslation264 = 0x6f320; +inline constexpr auto EnglishLayoutTranslation265 = 0x6f32c; +inline constexpr auto EnglishLayoutTranslation266 = 0x6f330; +inline constexpr auto EnglishLayoutTranslation267 = 0x6f338; +inline constexpr auto EnglishLayoutTranslation268 = 0x6f341; +inline constexpr auto EnglishLayoutTranslation269 = 0x6f34e; +inline constexpr auto EnglishLayoutTranslation27 = 0x6bf34; +inline constexpr auto EnglishLayoutTranslation270 = 0x6f354; +inline constexpr auto EnglishLayoutTranslation271 = 0x6f356; +inline constexpr auto EnglishLayoutTranslation272 = 0x6f358; +inline constexpr auto EnglishLayoutTranslation273 = 0x6f35c; +inline constexpr auto EnglishLayoutTranslation274 = 0x6f35e; +inline constexpr auto EnglishLayoutTranslation275 = 0x6f360; +inline constexpr auto EnglishLayoutTranslation276 = 0x6f368; +inline constexpr auto EnglishLayoutTranslation277 = 0x6f36c; +inline constexpr auto EnglishLayoutTranslation278 = 0x6f37c; +inline constexpr auto EnglishLayoutTranslation279 = 0x6f390; +inline constexpr auto EnglishLayoutTranslation28 = 0x6bf94; +inline constexpr auto EnglishLayoutTranslation280 = 0x6f3b8; +inline constexpr auto EnglishLayoutTranslation281 = 0x6f990; +inline constexpr auto EnglishLayoutTranslation282 = 0x6fac4; +inline constexpr auto EnglishLayoutTranslation283 = 0x6fbc4; +inline constexpr auto EnglishLayoutTranslation284 = 0x6fdd4; +inline constexpr auto EnglishLayoutTranslation285 = 0x6fe0c; +inline constexpr auto EnglishLayoutTranslation286 = 0x6fe10; +inline constexpr auto EnglishLayoutTranslation287 = 0x6fe18; +inline constexpr auto EnglishLayoutTranslation288 = 0x6fe19; +inline constexpr auto EnglishLayoutTranslation289 = 0x6fe20; +inline constexpr auto EnglishLayoutTranslation29 = 0x6bf95; +inline constexpr auto EnglishLayoutTranslation290 = 0x6fe5c; +inline constexpr auto EnglishLayoutTranslation291 = 0x6fe78; +inline constexpr auto EnglishLayoutTranslation292 = 0x6fe83; +inline constexpr auto EnglishLayoutTranslation293 = 0x6ffc8; +inline constexpr auto EnglishLayoutTranslation294 = 0x702dc; +inline constexpr auto EnglishLayoutTranslation295 = 0x7039c; +inline constexpr auto EnglishLayoutTranslation296 = 0x70455; +inline constexpr auto EnglishLayoutTranslation297 = 0x70540; +inline constexpr auto EnglishLayoutTranslation298 = 0x7054c; +inline constexpr auto EnglishLayoutTranslation299 = 0x70d9a; +inline constexpr auto EnglishLayoutTranslation3 = 0x6bcb1; +inline constexpr auto EnglishLayoutTranslation30 = 0x6bf96; +inline constexpr auto EnglishLayoutTranslation300 = 0x70e2d; +inline constexpr auto EnglishLayoutTranslation301 = 0x70ebd; +inline constexpr auto EnglishLayoutTranslation302 = 0x70ec4; +inline constexpr auto EnglishLayoutTranslation303 = 0x70ec6; +inline constexpr auto EnglishLayoutTranslation304 = 0x70ed8; +inline constexpr auto EnglishLayoutTranslation305 = 0x70eea; +inline constexpr auto EnglishLayoutTranslation306 = 0x70eef; +inline constexpr auto EnglishLayoutTranslation307 = 0x70f0c; +inline constexpr auto EnglishLayoutTranslation308 = 0x70f10; +inline constexpr auto EnglishLayoutTranslation309 = 0x70f14; +inline constexpr auto EnglishLayoutTranslation31 = 0x6bfbe; +inline constexpr auto EnglishLayoutTranslation310 = 0x70f18; +inline constexpr auto EnglishLayoutTranslation311 = 0x70f1c; +inline constexpr auto EnglishLayoutTranslation312 = 0x70f20; +inline constexpr auto EnglishLayoutTranslation313 = 0x70f24; +inline constexpr auto EnglishLayoutTranslation314 = 0x70f28; +inline constexpr auto EnglishLayoutTranslation315 = 0x70f2c; +inline constexpr auto EnglishLayoutTranslation316 = 0x70f2e; +inline constexpr auto EnglishLayoutTranslation317 = 0x70f30; +inline constexpr auto EnglishLayoutTranslation318 = 0x70f32; +inline constexpr auto EnglishLayoutTranslation32 = 0x6c028; +inline constexpr auto EnglishLayoutTranslation33 = 0x6c0c0; +inline constexpr auto EnglishLayoutTranslation34 = 0x6c0c8; +inline constexpr auto EnglishLayoutTranslation35 = 0x6c0c9; +inline constexpr auto EnglishLayoutTranslation36 = 0x6c0cc; +inline constexpr auto EnglishLayoutTranslation37 = 0x6c141; +inline constexpr auto EnglishLayoutTranslation38 = 0x6c142; +inline constexpr auto EnglishLayoutTranslation39 = 0x6c143; +inline constexpr auto EnglishLayoutTranslation4 = 0x6bcb8; +inline constexpr auto EnglishLayoutTranslation40 = 0x6c1e4; +inline constexpr auto EnglishLayoutTranslation41 = 0x6c1e8; +inline constexpr auto EnglishLayoutTranslation42 = 0x6c1eb; +inline constexpr auto EnglishLayoutTranslation43 = 0x6c1ec; +inline constexpr auto EnglishLayoutTranslation44 = 0x6c2b8; +inline constexpr auto EnglishLayoutTranslation45 = 0x6c2ba; +inline constexpr auto EnglishLayoutTranslation46 = 0x6c2bc; +inline constexpr auto EnglishLayoutTranslation47 = 0x6c2bf; +inline constexpr auto EnglishLayoutTranslation48 = 0x6c2c4; +inline constexpr auto EnglishLayoutTranslation49 = 0x6c334; +inline constexpr auto EnglishLayoutTranslation5 = 0x6bcbc; +inline constexpr auto EnglishLayoutTranslation50 = 0x6c520; +inline constexpr auto EnglishLayoutTranslation51 = 0x6c568; +inline constexpr auto EnglishLayoutTranslation52 = 0x6c610; +inline constexpr auto EnglishLayoutTranslation53 = 0x6c684; +inline constexpr auto EnglishLayoutTranslation54 = 0x6c700; +inline constexpr auto EnglishLayoutTranslation55 = 0x6c734; +inline constexpr auto EnglishLayoutTranslation56 = 0x6c740; +inline constexpr auto EnglishLayoutTranslation57 = 0x6c74c; +inline constexpr auto EnglishLayoutTranslation58 = 0x6d02c; +inline constexpr auto EnglishLayoutTranslation59 = 0x6d08c; +inline constexpr auto EnglishLayoutTranslation6 = 0x6bce1; +inline constexpr auto EnglishLayoutTranslation60 = 0x6d14c; +inline constexpr auto EnglishLayoutTranslation61 = 0x6d14d; +inline constexpr auto EnglishLayoutTranslation62 = 0x6d158; +inline constexpr auto EnglishLayoutTranslation63 = 0x6d159; +inline constexpr auto EnglishLayoutTranslation64 = 0x6d15c; +inline constexpr auto EnglishLayoutTranslation65 = 0x6d169; +inline constexpr auto EnglishLayoutTranslation66 = 0x6d1b3; +inline constexpr auto EnglishLayoutTranslation67 = 0x6d1ce; +inline constexpr auto EnglishLayoutTranslation68 = 0x6d24f; +inline constexpr auto EnglishLayoutTranslation69 = 0x6d26a; +inline constexpr auto EnglishLayoutTranslation7 = 0x6be0c; +inline constexpr auto EnglishLayoutTranslation70 = 0x6d270; +inline constexpr auto EnglishLayoutTranslation71 = 0x6d272; +inline constexpr auto EnglishLayoutTranslation72 = 0x6d274; +inline constexpr auto EnglishLayoutTranslation73 = 0x6d29c; +inline constexpr auto EnglishLayoutTranslation74 = 0x6d3b4; +inline constexpr auto EnglishLayoutTranslation75 = 0x6d404; +inline constexpr auto EnglishLayoutTranslation76 = 0x6d408; +inline constexpr auto EnglishLayoutTranslation77 = 0x6d40c; +inline constexpr auto EnglishLayoutTranslation78 = 0x6d450; +inline constexpr auto EnglishLayoutTranslation79 = 0x6d458; +inline constexpr auto EnglishLayoutTranslation8 = 0x6be10; +inline constexpr auto EnglishLayoutTranslation80 = 0x6d45c; +inline constexpr auto EnglishLayoutTranslation81 = 0x6d464; +inline constexpr auto EnglishLayoutTranslation82 = 0x6d478; +inline constexpr auto EnglishLayoutTranslation83 = 0x6d488; +inline constexpr auto EnglishLayoutTranslation84 = 0x6d4d0; +inline constexpr auto EnglishLayoutTranslation85 = 0x6d568; +inline constexpr auto EnglishLayoutTranslation86 = 0x6d569; +inline constexpr auto EnglishLayoutTranslation87 = 0x6d56c; +inline constexpr auto EnglishLayoutTranslation88 = 0x6d570; +inline constexpr auto EnglishLayoutTranslation89 = 0x6d584; +inline constexpr auto EnglishLayoutTranslation9 = 0x6be14; +inline constexpr auto EnglishLayoutTranslation90 = 0x6d598; +inline constexpr auto EnglishLayoutTranslation91 = 0x6d5a4; +inline constexpr auto EnglishLayoutTranslation92 = 0x6d6d4; +inline constexpr auto EnglishLayoutTranslation93 = 0x6d84e; +inline constexpr auto EnglishLayoutTranslation94 = 0x6d850; +inline constexpr auto EnglishLayoutTranslation95 = 0x6d854; +inline constexpr auto EnglishLayoutTranslation96 = 0x6d85e; +inline constexpr auto EnglishLayoutTranslation97 = 0x6d860; +inline constexpr auto EnglishLayoutTranslation98 = 0x6d864; +inline constexpr auto EnglishLayoutTranslation99 = 0x6d867; +inline constexpr auto EnglishLeagueCupField = 0x7cf0a; +inline constexpr auto EnglishLeagueCupFirstRoundField = 0x7cf32; +inline constexpr auto EnglishLeagueCupFirstRoundResults = 0x7cfae; +inline constexpr auto EnglishLeagueCupQuarterFinalField = 0x7cf62; +inline constexpr auto EnglishLeagueCupQuarterFinalOtherLegResults = 0x7d004; +inline constexpr auto EnglishLeagueCupQuarterFinalResults = 0x7cfc6; +inline constexpr auto EnglishLeagueCupSemiFinalField = 0x7cfaa; +inline constexpr auto EnglishLeagueCupSemiFinalResults = 0x7d002; +inline constexpr auto Environment_FormatError_RuntimeField = 0xa50f0; +inline constexpr auto Environment_FormatError_RuntimeField2 = 0xa50f6; +inline constexpr auto Environment_Render_TextPointer = 0xaeb74; +inline constexpr auto Environment_SetEnvironment_ExecutableField = 0xaf394; +inline constexpr auto EuropeNameTable = 0xae710; +inline constexpr auto EventPasses = 0xa2ba1; +inline constexpr auto Field = 0xb6adc; +inline constexpr auto Field0 = 0xb60c4; +inline constexpr auto FieldUnsigned = 0xb6adcu; +inline constexpr auto FinalLeagueStrengthMaximum = 0xa2c2d; +inline constexpr auto FinanceStatisticsEnabled = 0xbdb7e; +inline constexpr auto First = 0xa3968; +inline constexpr auto FixtureAdvertisingCountersEnd = 0xbd4e0; +inline constexpr auto FixtureAdvertisingRatingsEnd = 0xac840; +inline constexpr auto FixtureAdvertisingWorkspaceEnd = 0xbda00; +inline constexpr auto FixtureAllTimeAppearanceColumn = 0xa396c; +inline constexpr auto FixtureAllTimePointsColumn = 0xa396e; +inline constexpr auto FixtureAllTimePrimaryMetric = 0xa3961; +inline constexpr auto FixtureAllTimeSecondaryMetric = 0xa3962; +inline constexpr auto FixtureBankMemoryImageSize = 0xc0840; +inline constexpr auto FixtureCalendarSecondLeagueBit = 0xa29f3; +inline constexpr auto FixtureControllerValueByteOne = 0xbd8ed; +inline constexpr auto FixtureControllerValueByteThree = 0xbd8ef; +inline constexpr auto FixtureControllerValueByteTwo = 0xbd8ee; +inline constexpr auto FixtureCupFirstDrawingScriptUnsigned = 0xa3bf0u; +inline constexpr auto FixtureCupSecondDrawingScriptUnsigned = 0xa3c32u; +inline constexpr auto FixtureDesktopFirstLabelPointer = 0xaf0f4; +inline constexpr auto FixtureDesktopPairCases = 0xa18b4; +inline constexpr auto FixtureDesktopSecondLabelPointer = 0xaf0f8; +inline constexpr auto FixtureDriverSavedFlag = 0xaf847; +inline constexpr auto FixtureDriverSavedValueWord = 0xaf838; +inline constexpr auto FixtureExecutableStorageSize = 0x50000; +inline constexpr auto FixtureFifthCupPresentationOption = 0xa25b6; +inline constexpr auto FixtureFirstCupPresentationOption = 0xa25b2; +inline constexpr auto FixtureFirstTacticMaximum = 0xa20ec; +inline constexpr auto FixtureFourthCupPresentationOption = 0xa25b5; +inline constexpr auto FixtureFriendlySecondBlankLabel = 0xadf5c; +inline constexpr auto FixtureNationalWorkspaceEnd = 0xbbccc; +inline constexpr auto FixturePairingsFifthButtonText = 0xadf8c; +inline constexpr auto FixturePairingsFourthButtonText = 0xadf88; +inline constexpr auto FixturePairingsSecondDescriptor = 0xb6282; +inline constexpr auto FixturePairingsThirdDescriptor = 0xb6288; +inline constexpr auto FixturePlayerCardFlagByte = 0xbb12e; +inline constexpr auto FixtureRealityHandoffSignedBias = 0xa49c0; +inline constexpr auto FixtureRegionalLeagueLabelPointer = 0xae6d0; +inline constexpr auto FixtureSecondBookedFriendly = 0xab68a; +inline constexpr auto FixtureSecondCupPresentationOption = 0xa25b3; +inline constexpr auto FixtureSecondDeskCursor = 0xbd6ce; +inline constexpr auto FixtureSecondManagerClub = 0xb5eb6; +inline constexpr auto FixtureSecondSeasonEntrant = 0xbb182; +inline constexpr auto FixtureSecondTacticMaximum = 0xa20ed; +inline constexpr auto FixtureSeriesFirstMetric = 0xa3884; +inline constexpr auto FixtureSeriesSecondMetric = 0xa3885; +inline constexpr auto FixtureSettingsBlankNumericalCell = 0xa2508; +inline constexpr auto FixtureSettingsFirstCell = 0xa24f8; +inline constexpr auto FixtureSportschauAdjacentStateByte = 0xb5d25; +inline constexpr auto FixtureSportschauDescriptorWords = 0xb6408; +inline constexpr auto FixtureSportschauIndoorFooterBias = 0xa47fa; +inline constexpr auto FixtureSportschauOptionsBegin = 0xa24f4; +inline constexpr auto FixtureSportschauOutdoorFooterBias = 0xa47f9; +inline constexpr auto FixtureStadiumAdjacentRuntimeByte = 0xbb12d; +inline constexpr auto FixtureStadiumBlockLabel = 0xaef78; +inline constexpr auto FixtureStadiumTierLabel = 0xae9d4; +inline constexpr auto FixtureTeamStatisticsColumnLabels = 0xae4f8; +inline constexpr auto FixtureTeamStatisticsFirstLabel = 0xae4b8; +inline constexpr auto FixtureTextDatabaseFilename = 0xa1677; +inline constexpr auto FixtureThirdTacticMaximum = 0xa20ee; +inline constexpr auto FixtureTransferCapacityFlag = 0xbbcb1; +inline constexpr auto FixtureTransferSecondIdentityValue = 0xab90c; +inline constexpr auto FixtureTransferSecondPlayerValue = 0xbb86e; +inline constexpr auto Flags = 0xbb12c; +inline constexpr auto FlagsUnsigned = 0xbb12cU; +inline constexpr auto FlagsUnsignedSpelling2 = 0xbb12cu; +inline constexpr auto Fltd_Layout_ExecutableField = 0xa1318; +inline constexpr auto Fltd_Layout_ExecutableField2 = 0xa1363; +inline constexpr auto Fltd_Layout_ExecutableField3 = 0xa138a; +inline constexpr auto Fltd_Layout_ExecutableField4 = 0xa13bb; +inline constexpr auto Fltd_Layout_ExecutableField5 = 0xa140a; +inline constexpr auto Fltd_Layout_ExecutableField6 = 0xa163c; +inline constexpr auto Fltd_Layout_TextPointer = 0xa004e; +inline constexpr auto Fltd_Layout_TextPointer2 = 0xa0051; +inline constexpr auto Fltd_Layout_TextPointer3 = 0xa0054; +inline constexpr auto Fltd_Layout_TextPointer4 = 0xa0056; +inline constexpr auto Fltd_Layout_TextPointer5 = 0xa105c; +inline constexpr auto ForeignClubStrength = 0xbb590; +inline constexpr auto ForeignPlayerLimitEnabled = 0xa4a80; +inline constexpr auto Formations = 0xb2cfc; +inline constexpr auto FreeKickTakerLabel = 0x80cc9; +inline constexpr auto FriendlyDays = 0xaf3c0; +inline constexpr auto FriendlyDaysUnsigned = 0xaf3c0u; +inline constexpr auto FriendlyPlanCount = 0xa3134; +inline constexpr auto FriendlyTeams = 0xab688; +inline constexpr auto FriendlyTeamsUnsigned = 0xab688u; +inline constexpr auto FundBlock = 0xac7b0; +inline constexpr auto FundBlockUnsigned = 0xac7b0u; +inline constexpr auto GameEndAlternate_FormatError_ExecutableField = 0xa4431; +inline constexpr auto GameEndTaxAnimation_LoadGameEndTaxAnimationAssets_ExecutableField = 0xa5118; +inline constexpr auto GameEnd_Copy_TextPointer = 0xae58c; +inline constexpr auto GameEnd_Copy_TextPointer2 = 0xae5a8; +inline constexpr auto GameEnd_Line_TextPointer = 0xae9e4; +inline constexpr auto GameEnd_Out_TextPointer = 0xaedc0; +inline constexpr auto GameEnd_SourceHyphenator_ExecutableField = 0xa227b; +inline constexpr auto GameEnd_SourceHyphenator_RuntimeField = 0xa228d; +inline constexpr auto GameMode = 0xbdb79; +inline constexpr auto GameModeUnsigned = 0xbdb79u; +inline constexpr auto GermanDataCompatibilityEnd = 0xab5a0; +inline constexpr auto GermanDataSegmentBegin = 0xa0000; +inline constexpr auto GermanImageEnd = 0xc1000; +inline constexpr auto GermanLayoutTranslation = 0xa1431; +inline constexpr auto GermanLayoutTranslation2 = 0xa2c26; +inline constexpr auto GermanLayoutTranslation3 = 0xa2c2c; +inline constexpr auto GermanLayoutTranslation4 = 0xa45b4; +inline constexpr auto HighscoreRuntimeField = 0xa513b; +inline constexpr auto IncomingTransfer_OutcomeFrameAt_RuntimeField = 0xa3fc9; +inline constexpr auto IncomingTransfer_RenderAtElapsed_ExecutableField = 0xa12c4; +inline constexpr auto IncomingTransfer_RenderAtElapsed_RuntimeField = 0xa3fca; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer = 0xa0040; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer10 = 0xaf2d4; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer11 = 0xaf2d8; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer12 = 0xaf2dc; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer13 = 0xaf2e0; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer14 = 0xaf2e4; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer2 = 0xae7e4; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer3 = 0xaedf8; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer3Unsigned = 0xaedf8u; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer4 = 0xaedfc; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer4Unsigned = 0xaedfcU; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer5 = 0xaf2ac; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer6 = 0xaf2b0; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer7 = 0xaf2b4; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer8 = 0xaf2b8; +inline constexpr auto IncomingTransfer_RenderAtElapsed_TextPointer9 = 0xaf2c8; +inline constexpr auto IndoorInvitationText = 0xa1100; +inline constexpr auto IndoorStandings_FormatError_TextPointer = 0xa50a2; +inline constexpr auto IndoorStandings_FormatError_TextPointer2 = 0xaf0a4; +inline constexpr auto IndoorStandings_FormatError_TextPointer3 = 0xaf0a8; +inline constexpr auto IndoorStandings_FormatError_TextPointer4 = 0xaf0b0; +inline constexpr auto IndoorStandings_FormatError_TextPointer5 = 0xaf0b4; +inline constexpr auto IndoorStandings_Render_TextPointer = 0xa10fd; +inline constexpr auto IndoorStandings_Render_TextPointer2 = 0xaf0ac; +inline constexpr auto LeagueCalendarBits = 0xa29f2; +inline constexpr auto LeagueHeaderTable = 0xae08c; +inline constexpr auto LeaguePairings_DateString_TextPointer = 0xa1070; +inline constexpr auto LeaguePairings_DateString_TextPointer2 = 0xae66c; +inline constexpr auto LeaguePairings_Fill_RuntimeField = 0xa4549; +inline constexpr auto LeaguePairings_Fill_RuntimeField2 = 0xa454b; +inline constexpr auto LeaguePairings_Fill_TextPointer = 0xa1469; +inline constexpr auto LeaguePairings_FormatError_ExecutableField = 0xa146d; +inline constexpr auto LeaguePairings_FormatError_TextPointer = 0xa146b; +inline constexpr auto LeaguePairings_FormatError_TextPointer10 = 0xaec90; +inline constexpr auto LeaguePairings_FormatError_TextPointer11 = 0xaec94; +inline constexpr auto LeaguePairings_FormatError_TextPointer12 = 0xaec98; +inline constexpr auto LeaguePairings_FormatError_TextPointer13 = 0xaeca0; +inline constexpr auto LeaguePairings_FormatError_TextPointer14 = 0xaf194; +inline constexpr auto LeaguePairings_FormatError_TextPointer2 = 0xa1471; +inline constexpr auto LeaguePairings_FormatError_TextPointer3 = 0xa1474; +inline constexpr auto LeaguePairings_FormatError_TextPointer4 = 0xadf78; +inline constexpr auto LeaguePairings_FormatError_TextPointer5 = 0xadf7c; +inline constexpr auto LeaguePairings_FormatError_TextPointer6 = 0xae6a8; +inline constexpr auto LeaguePairings_FormatError_TextPointer7 = 0xae6b8; +inline constexpr auto LeaguePairings_FormatError_TextPointer8 = 0xaeb0c; +inline constexpr auto LeaguePairings_FormatError_TextPointer9 = 0xaeb10; +inline constexpr auto LeaguePairings_LeaguePairingsConstants_RuntimeField = 0xa2be6; +inline constexpr auto LeaguePairings_SelectorEvent_RuntimeField = 0xa2c0e; +inline constexpr auto LeaguePairings_SelectorEvent_RuntimeField2 = 0xa4561; +inline constexpr auto LeaguePairings_SelectorEvent_RuntimeField3 = 0xa4563; +inline constexpr auto LeaguePairings_Selector_RuntimeField = 0xa4565; +inline constexpr auto LeaguePairings_Selector_RuntimeField2 = 0xa4567; +inline constexpr auto LeaguePairings_Selector_RuntimeField3 = 0xa4569; +inline constexpr auto LeaguePairings_Selector_RuntimeField4 = 0xa456c; +inline constexpr auto LeaguePresentationOptions = 0xa24f7; +inline constexpr auto LeaguePresentationOptionsUnsigned = 0xa24f7u; +inline constexpr auto LeagueRankHistory = 0xba380; +inline constexpr auto LeagueResults = 0xba3c4; +inline constexpr auto LeagueRoundCounters = 0xbb4c1; +inline constexpr auto LeagueSizes = 0xa2bcd; +inline constexpr auto LeagueStrengthRanges = 0xa2c1c; +inline constexpr auto LeagueTableDisplayModes = 0xb602c; +inline constexpr auto LeagueTableDisplayModesUnsigned = 0xb602cu; +inline constexpr auto LeagueTableRangeDialog_Backdrop_ExecutableField = 0xaf240; +inline constexpr auto LeagueTable_Glyph_TextPointer = 0xa1458; +inline constexpr auto LeagueTable_Glyph_TextPointer2 = 0xadf54; +inline constexpr auto LeagueTable_OriginalToUtf8_RuntimeField = 0xbdb78; +inline constexpr auto LeagueTable_OriginalToUtf8_TextPointer = 0xadf60; +inline constexpr auto LeagueTable_OriginalToUtf8_TextPointer2 = 0xaec7c; +inline constexpr auto Lineup_Render_TextPointer = 0xae0dc; +inline constexpr auto Lineup_Render_TextPointer2 = 0xae0e8; +inline constexpr auto Lineup_Render_TextPointer3 = 0xaf134; +inline constexpr auto Lineup_Render_TextPointer4 = 0xaf138; +inline constexpr auto LiveDeskDisabled = 0xa251f; +inline constexpr auto LiveMatchday_FormatError_ExecutableField = 0xa11da; +inline constexpr auto LiveMatchday_FormatError_ExecutableField10 = 0xa3e84; +inline constexpr auto LiveMatchday_FormatError_ExecutableField11 = 0xa3e88; +inline constexpr auto LiveMatchday_FormatError_ExecutableField12 = 0xa49c2; +inline constexpr auto LiveMatchday_FormatError_ExecutableField13 = 0xa49f2; +inline constexpr auto LiveMatchday_FormatError_ExecutableField14 = 0xa4a22; +inline constexpr auto LiveMatchday_FormatError_ExecutableField2 = 0xa11de; +inline constexpr auto LiveMatchday_FormatError_ExecutableField3 = 0xa11e3; +inline constexpr auto LiveMatchday_FormatError_ExecutableField4 = 0xa11e6; +inline constexpr auto LiveMatchday_FormatError_ExecutableField5 = 0xa11e8; +inline constexpr auto LiveMatchday_FormatError_ExecutableField6 = 0xa3d50; +inline constexpr auto LiveMatchday_FormatError_ExecutableField7 = 0xa3d55; +inline constexpr auto LiveMatchday_FormatError_ExecutableField8 = 0xa3d5a; +inline constexpr auto LiveMatchday_FormatError_ExecutableField9 = 0xa3d6e; +inline constexpr auto LiveMatchday_FormatError_RuntimeField = 0xa3d82; +inline constexpr auto LiveMatchday_FormatError_RuntimeField10 = 0xa3de9; +inline constexpr auto LiveMatchday_FormatError_RuntimeField11 = 0xa3dfd; +inline constexpr auto LiveMatchday_FormatError_RuntimeField12Unsigned = 0xa3f6cu; +inline constexpr auto LiveMatchday_FormatError_RuntimeField13Unsigned = 0xa3f6eu; +inline constexpr auto LiveMatchday_FormatError_RuntimeField14 = 0xbdb08; +inline constexpr auto LiveMatchday_FormatError_RuntimeField15 = 0xbdb82; +inline constexpr auto LiveMatchday_FormatError_RuntimeField2 = 0xa3d85; +inline constexpr auto LiveMatchday_FormatError_RuntimeField3 = 0xa3d96; +inline constexpr auto LiveMatchday_FormatError_RuntimeField4 = 0xa3d99; +inline constexpr auto LiveMatchday_FormatError_RuntimeField5 = 0xa3d9b; +inline constexpr auto LiveMatchday_FormatError_RuntimeField6 = 0xa3d9d; +inline constexpr auto LiveMatchday_FormatError_RuntimeField7 = 0xa3dad; +inline constexpr auto LiveMatchday_FormatError_RuntimeField8 = 0xa3dc1; +inline constexpr auto LiveMatchday_FormatError_RuntimeField9 = 0xa3dd5; +inline constexpr auto LiveMatchday_FormatError_TextPointer = 0xae078; +inline constexpr auto LiveMatchday_FormatError_TextPointer10 = 0xaf010; +inline constexpr auto LiveMatchday_FormatError_TextPointer11 = 0xaf05c; +inline constexpr auto LiveMatchday_FormatError_TextPointer12 = 0xaf060; +inline constexpr auto LiveMatchday_FormatError_TextPointer13 = 0xaf064; +inline constexpr auto LiveMatchday_FormatError_TextPointer14 = 0xaf068; +inline constexpr auto LiveMatchday_FormatError_TextPointer15 = 0xaf06c; +inline constexpr auto LiveMatchday_FormatError_TextPointer2 = 0xae1a8; +inline constexpr auto LiveMatchday_FormatError_TextPointer2Unsigned = 0xae1a8u; +inline constexpr auto LiveMatchday_FormatError_TextPointer3 = 0xae5c0; +inline constexpr auto LiveMatchday_FormatError_TextPointer4 = 0xaeb30; +inline constexpr auto LiveMatchday_FormatError_TextPointer5 = 0xaeb34; +inline constexpr auto LiveMatchday_FormatError_TextPointer6 = 0xaeb38; +inline constexpr auto LiveMatchday_FormatError_TextPointer7 = 0xaf004; +inline constexpr auto LiveMatchday_FormatError_TextPointer8 = 0xaf008; +inline constexpr auto LiveMatchday_FormatError_TextPointer9 = 0xaf00c; +inline constexpr auto LiveMatchday_FormatError_TextPointerUnsigned = 0xae078u; +inline constexpr auto LiveMatchday_LiveMatchdayFrame_TextPointer = 0xaf014; +inline constexpr auto LiveMatchday_PatternRect_RuntimeField = 0xa3457; +inline constexpr auto LiveMatchday_PatternRect_RuntimeFieldUnsigned = 0xa3457u; +inline constexpr auto LiveMatchday_RenderHeader_RuntimeFieldUnsigned = 0xa3f34u; +inline constexpr auto LiveMatchday_RenderHeader_TextPointer = 0xa11d8; +inline constexpr auto LiveMatchday_RenderSetPiece_RuntimeField = 0xa3e45; +inline constexpr auto LiveMatchday_RenderSetPiece_RuntimeField2 = 0xa3e55; +inline constexpr auto LiveMatchday_Render_ExecutableField = 0xa50a6; +inline constexpr auto LiveMatchday_Render_ExecutableFieldUnsigned = 0xa50a6u; +inline constexpr auto LiveMatchday_Render_RuntimeField = 0xa3d3e; +inline constexpr auto LiveMatchday_Render_RuntimeField2 = 0xa3d42; +inline constexpr auto LiveMatchday_Render_RuntimeField2Unsigned = 0xa3d42u; +inline constexpr auto LiveMatchday_Render_RuntimeField3 = 0xa3d46; +inline constexpr auto LiveMatchday_Render_RuntimeField3Unsigned = 0xa3d46u; +inline constexpr auto LiveMatchday_Render_RuntimeFieldUnsigned = 0xa3d3eu; +inline constexpr auto LiveSceneOptions = 0xa20f4; +inline constexpr auto LiveSetPiece_Motion_ExecutableField2Unsigned = 0xa3db9u; +inline constexpr auto LiveSetPiece_Motion_ExecutableFieldUnsigned = 0xa3dafu; +inline constexpr auto LiveSetPiece_Run_ExecutableField10Unsigned = 0xa3e69u; +inline constexpr auto LiveSetPiece_Run_ExecutableField11Unsigned = 0xa3e71u; +inline constexpr auto LiveSetPiece_Run_ExecutableField12Unsigned = 0xa3e79u; +inline constexpr auto LiveSetPiece_Run_ExecutableField13Unsigned = 0xa3e7cu; +inline constexpr auto LiveSetPiece_Run_ExecutableField2Unsigned = 0xa3e11u; +inline constexpr auto LiveSetPiece_Run_ExecutableField3Unsigned = 0xa3e2au; +inline constexpr auto LiveSetPiece_Run_ExecutableField4Unsigned = 0xa3e4du; +inline constexpr auto LiveSetPiece_Run_ExecutableField5Unsigned = 0xa3e5du; +inline constexpr auto LiveSetPiece_Run_ExecutableField6Unsigned = 0xa3e61u; +inline constexpr auto LiveSetPiece_Run_ExecutableField7Unsigned = 0xa3e63u; +inline constexpr auto LiveSetPiece_Run_ExecutableField8Unsigned = 0xa3e65u; +inline constexpr auto LiveSetPiece_Run_ExecutableField9Unsigned = 0xa3e67u; +inline constexpr auto LiveSetPiece_Run_ExecutableFieldUnsigned = 0xa3db5u; +inline constexpr auto LiveSetPiece_Wall_ExecutableFieldUnsigned = 0xa3e43u; +inline constexpr auto LoanTitleText = 0xae190; +inline constexpr auto Loans = 0xbd70c; +inline constexpr auto LoansUnsigned = 0xbd70cu; +inline constexpr auto MailboxRecipientMask = 0xaf8f4; +inline constexpr auto MailboxScreen_Click_RuntimeField = 0xa432e; +inline constexpr auto MailboxScreen_Click_RuntimeField2 = 0xa4332; +inline constexpr auto MailboxScreen_Click_RuntimeField3 = 0xa4336; +inline constexpr auto MailboxScreen_Click_RuntimeField4 = 0xa433a; +inline constexpr auto MailboxScreen_Click_RuntimeField5 = 0xa433e; +inline constexpr auto MailboxScreen_Click_RuntimeField6 = 0xa4342; +inline constexpr auto MailboxScreen_Click_RuntimeField7 = 0xa4346; +inline constexpr auto MailboxScreen_Click_RuntimeField8 = 0xa434a; +inline constexpr auto MailboxScreen_Render_RuntimeField = 0xa434e; +inline constexpr auto MailboxScreen_Render_RuntimeField2 = 0xa4350; +inline constexpr auto MailboxScreen_Render_RuntimeField3 = 0xa4352; +inline constexpr auto MailboxScreen_Render_RuntimeField4 = 0xa4354; +inline constexpr auto MailboxScreen_Render_TextPointer = 0xaed9c; +inline constexpr auto MailboxScreen_Render_TextPointer2 = 0xaeda0; +inline constexpr auto Main_FileScreen_RuntimeField = 0xa3f68; +inline constexpr auto Main_FileScreen_RuntimeField2 = 0xa3f69; +inline constexpr auto Main_FileScreen_RuntimeField3 = 0xa3f6a; +inline constexpr auto Main_FormatError_ExecutableField = 0xa24ff; +inline constexpr auto Main_FormatError_ExecutableField2 = 0xa2519; +inline constexpr auto Main_FormatError_ExecutableFieldUnsigned = 0xa24ffu; +inline constexpr auto Main_FormatError_RuntimeField = 0xa2522; +inline constexpr auto Main_FormatError_RuntimeField2 = 0xa252b; +inline constexpr auto Main_FormatError_RuntimeField3 = 0xa2534; +inline constexpr auto Main_FormatError_RuntimeField4 = 0xa253e; +inline constexpr auto Main_FormatError_RuntimeField5 = 0xa2543; +inline constexpr auto Main_FormatError_RuntimeField6 = 0xa256b; +inline constexpr auto Main_FormatError_RuntimeField7 = 0xa2586; +inline constexpr auto Main_Screen_RuntimeField = 0xa3f6b; +inline constexpr auto Main_Screen_RuntimeField2 = 0xbdb88; +inline constexpr auto ManagerAutomation = 0xa243a; +inline constexpr auto ManagerCount = 0xa24f6; +inline constexpr auto ManagerCountUnsigned = 0xa24f6u; +inline constexpr auto ManagerMailbox = 0xaf978; +inline constexpr auto ManagerMatchHistory = 0xafd04; +inline constexpr auto ManagerRatings = 0xac6c0; +inline constexpr auto ManagerRecords = 0xb6c18; +inline constexpr auto ManagerSettings = 0xb5f84; +inline constexpr auto Manager_FormatError_RuntimeField = 0xa2c02; +inline constexpr auto Manager_FormatError_RuntimeField2 = 0xa48ad; +inline constexpr auto Manager_FormatError_RuntimeField3 = 0xa48b5; +inline constexpr auto Manager_FormatError_RuntimeField4 = 0xa48bd; +inline constexpr auto Manager_FormatError_RuntimeField5 = 0xa48c5; +inline constexpr auto Manager_FormatError_RuntimeField6 = 0xa48cd; +inline constexpr auto Manager_FormatError_TextPointer = 0xaec28; +inline constexpr auto Manager_FormatError_TextPointer2 = 0xaec70; +inline constexpr auto Manager_Render_TextPointer = 0xade48; +inline constexpr auto Manager_SmallText_TextPointer = 0xaec2c; +inline constexpr auto MasterDatabaseMetadata = 0xba384; +inline constexpr auto MastersQualificationText = 0xa1075; +inline constexpr auto MastersWinnerText = 0xa10ba; +inline constexpr auto MatchEngine_EventImpl_ExecutableField = 0xa2555; +inline constexpr auto MatchEngine_EventImpl_ExecutableField2 = 0xa255e; +inline constexpr auto MatchEngine_EventImpl_ExecutableField3 = 0xa2567; +inline constexpr auto MatchEngine_InjurePlayer_TextPointer = 0xaead0; +inline constexpr auto MatchEngine_InjurePlayer_TextPointer2 = 0xaead4; +inline constexpr auto MatchEngine_Minute_ExecutableField = 0xaf9c7; +inline constexpr auto MatchEngine_Minute_ExecutableField2 = 0xafb40; +inline constexpr auto MatchEngine_Minute_ExecutableField3 = 0xafb71; +inline constexpr auto MatchEngine_Minute_ExecutableField4 = 0xafb7d; +inline constexpr auto MatchEngine_Side_ExecutableField = 0xa2507; +inline constexpr auto MatchEngine_Side_ExecutableField2 = 0xa2510; +inline constexpr auto MatchEngine_Side_ExecutableField3 = 0xa2516; +inline constexpr auto MatchEngine_Side_ExecutableField4 = 0xa2531; +inline constexpr auto MatchEngine_Side_ExecutableField5 = 0xa2570; +inline constexpr auto MatchEventsDisabled = 0xa5046; +inline constexpr auto MatchdayGroupDescriptors = 0xb636c; +inline constexpr auto MatchdayGroupWorkspace = 0xb600c; +inline constexpr auto MatchdayResults_CompetitionName_TextPointer = 0xae790; +inline constexpr auto MatchdaySetupRuntimeField14 = 0xbb1f0; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField = 0xa3eba; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField2 = 0xa3eca; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField3 = 0xa3eda; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField4 = 0xa3f12; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField5 = 0xa3f16; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField6 = 0xa3f1a; +inline constexpr auto MatchdaySetup_Attendance_ExecutableField7 = 0xa3f20; +inline constexpr auto MatchdaySetup_Attendance_TextPointer = 0xaeff8; +inline constexpr auto MatchdaySetup_Attendance_TextPointer2 = 0xaf000; +inline constexpr auto MatchdaySetup_ConsiderSportschauFixture_RuntimeField = 0xa258d; +inline constexpr auto MatchdaySetup_ConsiderSportschauFixture_RuntimeFieldUnsigned = 0xa258du; +inline constexpr auto MatchdaySetup_EvaluatePoolsCoupon_RuntimeField = 0xaf88c; +inline constexpr auto MatchdaySetup_IndoorTournamentDraw_RuntimeField = 0xbd424; +inline constexpr auto MatchdaySetup_IndoorTournamentReset_RuntimeField = 0xa2c87; +inline constexpr auto MatchdaySetup_IndoorTournamentReset_TextPointer = 0xaf0b8; +inline constexpr auto MatchdaySetup_KickOff_RuntimeField = 0xbd90d; +inline constexpr auto MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField = 0xa2529; +inline constexpr auto MatchdaySetup_SettlePoolsCoupon_TextPointer = 0xaf234; +inline constexpr auto MatchdaySetup_SetupMatchday_TextPointer = 0xaf058; +inline constexpr auto MatchdaySetup_WinterPostponements_RuntimeField = 0xa254f; +inline constexpr auto MatchdaySetup_WinterPostponements_RuntimeField2 = 0xa2582; +inline constexpr auto MinuteStatistics_SourceBarColor_RuntimeField = 0xa3aa4; +inline constexpr auto MissingInfofileText = 0xa1620; +inline constexpr auto Month_BoardMonth_TextPointer = 0xaee4c; +inline constexpr auto Month_BoardMonth_TextPointer2 = 0xaee50; +inline constexpr auto Month_BoardMonth_TextPointer3 = 0xaee54; +inline constexpr auto Month_BoardMonth_TextPointer4 = 0xaee58; +inline constexpr auto Month_MonthChange_RuntimeField = 0xbd4d4; +inline constexpr auto Month_MonthChange_TextPointer = 0xaee28; +inline constexpr auto Month_ReturnLoans_TextPointer = 0xaee2c; +inline constexpr auto Month_ReturnLoans_TextPointer2 = 0xaee30; +inline constexpr auto Month_ReturnLoans_TextPointer3 = 0xaee34; +inline constexpr auto Month_ReturnLoans_TextPointer4 = 0xaee38; +inline constexpr auto Month_ReturnLoans_TextPointer5 = 0xaee3c; +inline constexpr auto Month_ReturnLoans_TextPointer6 = 0xaee40; +inline constexpr auto Month_ReturnLoans_TextPointer7 = 0xaee44; +inline constexpr auto Month_ReturnLoans_TextPointer8 = 0xaee48; +inline constexpr auto Month_SearchProfileNews_TextPointer = 0xaedd8; +inline constexpr auto Month_SearchProfileNews_TextPointer2 = 0xaf254; +inline constexpr auto NationalFriendlyPayerPrefixText = 0xa000f; +inline constexpr auto NextDeskManager = 0xbd6cc; +inline constexpr auto NoClubText = 0xaec74; +inline constexpr auto NoPlayerText = 0xaec78; +inline constexpr auto NoTeamSquadStart = 0xa2c38; +inline constexpr auto OfferSlots = 0xbb844; +inline constexpr auto Opportunities_FormatError_RuntimeField = 0xa3a6e; +inline constexpr auto Opportunities_FormatError_RuntimeField2 = 0xa3a80; +inline constexpr auto Opportunities_FormatError_RuntimeField3 = 0xa3a92; +inline constexpr auto Opportunities_FormatError_TextPointer = 0xadefc; +inline constexpr auto Opportunities_FormatError_TextPointer2 = 0xaec6c; +inline constexpr auto Opportunities_Render_ExecutableField = 0xadee0; +inline constexpr auto Opportunities_Render_ExecutableField2 = 0xadee4; +inline constexpr auto Opportunities_Render_ExecutableField3 = 0xadee8; +inline constexpr auto Opportunities_Render_ExecutableField4 = 0xadeec; +inline constexpr auto Opportunities_Render_RuntimeField = 0xa3a68; +inline constexpr auto Opportunities_Render_RuntimeField2 = 0xa3a69; +inline constexpr auto Opportunities_Render_RuntimeField3 = 0xa3a6b; +inline constexpr auto Opportunities_Render_TextPointer = 0xadef0; +inline constexpr auto Opportunities_Render_TextPointer2 = 0xaec58; +inline constexpr auto Opportunities_Render_TextPointer3 = 0xaec5c; +inline constexpr auto Opportunities_Render_TextPointer4 = 0xaec60; +inline constexpr auto Opportunities_Render_TextPointer5 = 0xaec64; +inline constexpr auto Opportunities_Render_TextPointer6 = 0xaec68; +inline constexpr auto Opportunities_StatisticsWindow_RuntimeField = 0xa3a9b; +inline constexpr auto OriginalManagerCount = 0xa376f; +inline constexpr auto OtherGamesState_ForeignDetail_ExecutableField = 0xa50ae; +inline constexpr auto OtherGamesState_FormatNumber_ExecutableField = 0xa10f0; +inline constexpr auto OtherGamesState_OtherGamesStateFromGame_ExecutableField = 0xa10eb; +inline constexpr auto OtherGamesState_OtherGamesStateFromGame_ExecutableField2 = 0xa10ee; +inline constexpr auto OtherGamesState_ResultText_ExecutableField = 0xa1072; +inline constexpr auto OtherGames_Layout_ExecutableField = 0xae764; +inline constexpr auto OutcomeDelayDisabled = 0xa2532; +inline constexpr auto OutcomeDelayDisabledUnsigned = 0xa2532u; +inline constexpr auto OutgoingTransfer_DrawFooter_TextPointer = 0xae198; +inline constexpr auto OutgoingTransfer_Line_ExecutableField = 0xaf2cc; +inline constexpr auto OutgoingTransfer_Line_ExecutableField2 = 0xaf2d0; +inline constexpr auto OutgoingTransfer_Line_RuntimeField = 0xa3767; +inline constexpr auto OutgoingTransfer_Line_TextPointer = 0xaf2e8; +inline constexpr auto PenaltyTakerLabel = 0x80cd2; +inline constexpr auto PendingOffer_ConstructionNoticeDialog_TextPointer = 0xaee1c; +inline constexpr auto PendingOffer_ConstructionNoticeDialog_TextPointer2 = 0xaef84; +inline constexpr auto PendingOffer_FormatError_ExecutableField = 0xaed3c; +inline constexpr auto PendingOffer_FormatError_ExecutableField2 = 0xaee08; +inline constexpr auto PendingOffer_FormatError_ExecutableField2Unsigned = 0xaee08u; +inline constexpr auto PendingOffer_FormatError_ExecutableField3 = 0xaee24; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField = 0xaedec; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField10 = 0xaf150; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField2 = 0xaedf0; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField2Unsigned = 0xaedf0u; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField3 = 0xaedf4; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField4 = 0xaee04; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField5 = 0xaf13c; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField6 = 0xaf140; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField7 = 0xaf144; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField8 = 0xaf148; +inline constexpr auto PendingOffer_PendingOfferNoticeDialog_ExecutableField9 = 0xaf14c; +inline constexpr auto PendingOffer_PendingOfferOwnerTeam_RuntimeField = 0xbd6cd; +inline constexpr auto PendingOffer_TransferLastWeekDialog_ExecutableField = 0xaedcc; +inline constexpr auto Pitch_FormatError_TextPointer = 0xaf174; +inline constexpr auto Pitch_FormatError_TextPointer2 = 0xaf178; +inline constexpr auto Pitch_FormatError_TextPointer3 = 0xaf17c; +inline constexpr auto Pitch_Render_RuntimeField = 0xa3cbc; +inline constexpr auto Pitch_Render_TextPointer = 0xae0e4; +inline constexpr auto Pitch_Render_TextPointer2 = 0xae0ec; +inline constexpr auto Pitch_Render_TextPointer3 = 0xae0f0; +inline constexpr auto Pitch_Render_TextPointer4 = 0xae0f4; +inline constexpr auto Pitch_Render_TextPointer5 = 0xae0f8; +inline constexpr auto Placements = 0xbd38c; +inline constexpr auto PlainBackground = 0xa2569; +inline constexpr auto PlanTicketPrice = 0xa4856; +inline constexpr auto PlayerBonuses = 0xba38c; +inline constexpr auto PlayerCard_PlayerCardMarketValue_RuntimeField = 0xa431e; +inline constexpr auto PlayerCards = 0xba3b4; +inline constexpr auto PlayerConditionTechniqueForm = 0xba35c; +inline constexpr auto PlayerDevelopmentBalance = 0xbdaf8; +inline constexpr auto PlayerIdentityWords = 0xba364; +inline constexpr auto PlayerNameOffsets = 0xbb120; +inline constexpr auto PlayerSkillWords = 0xba368; +inline constexpr auto Poach_ClubAskingPercent_TextPointer = 0xaf280; +inline constexpr auto Poach_ClubAskingPercent_TextPointer2 = 0xaf284; +inline constexpr auto Poach_ClubAskingPercent_TextPointer3 = 0xaf288; +inline constexpr auto Poach_ClubAskingPercent_TextPointer4 = 0xaf28c; +inline constexpr auto Poach_StartPoach_TextPointer = 0xaecb8; +inline constexpr auto Poach_StartPoach_TextPointer2 = 0xaf26c; +inline constexpr auto Poach_StartPoach_TextPointer3 = 0xaf270; +inline constexpr auto Poach_StartPoach_TextPointer4 = 0xaf274; +inline constexpr auto Poach_StartPoach_TextPointer5 = 0xaf278; +inline constexpr auto Postponed = 0xb627c; +inline constexpr auto Prediction_TablePrediction_TextPointer = 0xae6c4; +inline constexpr auto Prediction_TablePrediction_TextPointer10 = 0xaeea8; +inline constexpr auto Prediction_TablePrediction_TextPointer11 = 0xaeeac; +inline constexpr auto Prediction_TablePrediction_TextPointer12 = 0xaeeb0; +inline constexpr auto Prediction_TablePrediction_TextPointer13 = 0xaeeb4; +inline constexpr auto Prediction_TablePrediction_TextPointer14 = 0xaeeb8; +inline constexpr auto Prediction_TablePrediction_TextPointer15 = 0xaeebc; +inline constexpr auto Prediction_TablePrediction_TextPointer2 = 0xaee88; +inline constexpr auto Prediction_TablePrediction_TextPointer3 = 0xaee8c; +inline constexpr auto Prediction_TablePrediction_TextPointer4 = 0xaee90; +inline constexpr auto Prediction_TablePrediction_TextPointer5 = 0xaee94; +inline constexpr auto Prediction_TablePrediction_TextPointer6 = 0xaee98; +inline constexpr auto Prediction_TablePrediction_TextPointer7 = 0xaee9c; +inline constexpr auto Prediction_TablePrediction_TextPointer8 = 0xaeea0; +inline constexpr auto Prediction_TablePrediction_TextPointer9 = 0xaeea4; +inline constexpr auto ProcessTimer_FormatError_RuntimeField = 0xa4358; +inline constexpr auto PurchaseTitleText = 0xae18c; +inline constexpr auto RealityMatch_FormatError_ExecutableField = 0xa250d; +inline constexpr auto RealityMatch_FormatError_ExecutableFieldUnsigned = 0xa250du; +inline constexpr auto RealityMotion_FormatError_RuntimeField2Unsigned = 0xa4a6au; +inline constexpr auto RealityMotion_FormatError_RuntimeField3Unsigned = 0xa4a72u; +inline constexpr auto RealityMotion_FormatError_RuntimeField4Unsigned = 0xa4c23u; +inline constexpr auto RealityMotion_FormatError_RuntimeField5Unsigned = 0xa4ef3u; +inline constexpr auto RealityMotion_FormatError_RuntimeField6Unsigned = 0xa502du; +inline constexpr auto RealityMotion_FormatError_RuntimeField7Unsigned = 0xa5039u; +inline constexpr auto RealityMotion_FormatError_RuntimeFieldUnsigned = 0xa4a62u; +inline constexpr auto RealityMotion_RealityMotion_RuntimeFieldUnsigned = 0xa4a52u; +inline constexpr auto RealityReporter_Evaluate_TextPointer = 0xaeb28; +inline constexpr auto RealityReporter_Evaluate_TextPointer2 = 0xaeb2c; +inline constexpr auto RealityReporter_Font_ExecutableField = 0xa163a; +inline constexpr auto RealityReporter_FormatError_TextPointer = 0xa2369; +inline constexpr auto RealityReporter_InitializeRealityReporter_RuntimeField = 0xaf9bb; +inline constexpr auto RealityScene_AdvanceRealityScene_RuntimeFieldUnsigned = 0xa49bfu; +inline constexpr auto RealityScene_AdvanceRealityScene_TextPointer = 0xaec30; +inline constexpr auto RealityScene_GoalMouth_RuntimeFieldUnsigned = 0xa244eu; +inline constexpr auto RealitySetup_InitializeReality_RuntimeFieldUnsigned = 0xa49b8u; +inline constexpr auto RealitySpace_RealityPenaltyArea_RuntimeField = 0xa49b4; +inline constexpr auto RealitySpace_RealityPenaltyArea_RuntimeField2 = 0xa49b5; +inline constexpr auto RealitySpace_RealityPenaltyArea_RuntimeField3 = 0xa49b6; +inline constexpr auto RealitySpace_RealityPenaltyArea_RuntimeField4 = 0xa49b7; +inline constexpr auto RefereeProperties = 0xbb3aa; +inline constexpr auto ReplayChanceMode = 0xa2521; +inline constexpr auto ReplayFixtures = 0xbb148; +inline constexpr auto ReplayProgressionMode = 0xa2518; +inline constexpr auto ReplayResults = 0xbb2fe; +inline constexpr auto RoundNameTable = 0xae09c; +inline constexpr auto RuleOptionDefaults = 0xa3650; +inline constexpr auto SaveLoad_Render_ExecutableField = 0xa148f; +inline constexpr auto SaveLoad_Render_RuntimeField = 0xa2334; +inline constexpr auto SaveLoad_Render_RuntimeField2 = 0xa233f; +inline constexpr auto SaveLoad_Render_RuntimeField3 = 0xa234a; +inline constexpr auto SaveLoad_Render_TextPointer = 0xa1512; +inline constexpr auto SaveLoad_Render_TextPointer2 = 0xae5f0; +inline constexpr auto SaveLoad_Render_TextPointer3 = 0xae620; +inline constexpr auto SaveLoad_Render_TextPointer4 = 0xae624; +inline constexpr auto SaveLoad_Render_TextPointer5 = 0xae644; +inline constexpr auto SaveLoad_Render_TextPointer6 = 0xae648; +inline constexpr auto SaveLoad_Render_TextPointer7 = 0xaeaa0; +inline constexpr auto SavedCompetition = 0xaf43c; +inline constexpr auto Savestate_Layout_ExecutableField = 0xa3889; +inline constexpr auto Savestate_Layout_ExecutableField2 = 0xafb3a; +inline constexpr auto Savestate_Layout_ExecutableField3 = 0xb6234; +inline constexpr auto Savestate_Layout_ExecutableField4 = 0xbb29c; +inline constexpr auto Savestate_Layout_ExecutableField5 = 0xbb466; +inline constexpr auto Savestate_Layout_ExecutableField6 = 0xbb833; +inline constexpr auto Savestate_Layout_ExecutableField7 = 0xbb854; +inline constexpr auto Savestate_Layout_ExecutableField8 = 0xbdb1a; +inline constexpr auto SeasonEntrants_FormatError_ExecutableField = 0xa3ce4; +inline constexpr auto SeasonEntrants_FormatError_ExecutableField2 = 0xa3cec; +inline constexpr auto SeasonEntrants_FormatError_ExecutableField3 = 0xa3cf4; +inline constexpr auto SeasonEntrants_FormatError_RuntimeField = 0xa3cfa; +inline constexpr auto SeasonEntrants_FormatError_TextPointer = 0xa3d03; +inline constexpr auto SeasonEntrants_FormatError_TextPointer2 = 0xae7bc; +inline constexpr auto SeasonEntrants_SeasonEntrantsFromGame_TextPointer = 0xa254e; +inline constexpr auto SeasonIndex = 0xbb46a; +inline constexpr auto SeasonPromotion_FormatError_RuntimeField = 0xa3228; +inline constexpr auto SeasonPromotion_FormatError_RuntimeFieldUnsigned = 0xa3228u; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField = 0xa2c8c; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField2 = 0xa2e94; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField3 = 0xa2e96; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField4 = 0xa2ee4; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField5 = 0xa2f84; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField6 = 0xa2fd4; +inline constexpr auto Season_CareerSeasonSetup_RuntimeField7 = 0xbdb10; +inline constexpr auto Season_ClubPopularity_TextPointer = 0xaee7c; +inline constexpr auto Season_ClubPopularity_TextPointer2 = 0xaee80; +inline constexpr auto Season_LicenceWithdrawals_TextPointer = 0xaf018; +inline constexpr auto Season_LicenceWithdrawals_TextPointer2 = 0xaf01c; +inline constexpr auto Season_LicenceWithdrawals_TextPointer3 = 0xaf020; +inline constexpr auto Season_List_RuntimeField = 0xbdd9c; +inline constexpr auto Season_Promotion_ExecutableField = 0xa3204; +inline constexpr auto Season_Promotion_ExecutableField2 = 0xa3206; +inline constexpr auto Season_Promotion_TextPointer = 0xaf024; +inline constexpr auto Season_SeasonAccounts_RuntimeField = 0xbbcc4; +inline constexpr auto Season_SeasonAccounts_TextPointer = 0xaeba0; +inline constexpr auto Season_SeasonAccounts_TextPointer2 = 0xaeba4; +inline constexpr auto Season_SeasonAccounts_TextPointer3 = 0xaeba8; +inline constexpr auto Season_SeasonAccounts_TextPointer4 = 0xaebcc; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer = 0xaebac; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer2 = 0xaebb0; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer3 = 0xaebb4; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer4 = 0xaebb8; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer5 = 0xaebbc; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer6 = 0xaebc0; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer7 = 0xaebc4; +inline constexpr auto Season_SeasonApplyProfitTax_TextPointer8 = 0xaebc8; +inline constexpr auto Season_SeasonAwards_TextPointer = 0xae210; +inline constexpr auto Season_SeasonAwards_TextPointer2 = 0xae21c; +inline constexpr auto Season_SeasonAwards_TextPointer3 = 0xaeb7c; +inline constexpr auto Season_SeasonAwards_TextPointer4 = 0xaeb80; +inline constexpr auto Season_SeasonAwards_TextPointer5 = 0xaeb84; +inline constexpr auto Season_SeasonAwards_TextPointer6 = 0xaeb88; +inline constexpr auto Season_SeasonEndSteps_RuntimeField = 0xaf452; +inline constexpr auto Season_SeasonEndSteps_RuntimeField2 = 0xaf4b2; +inline constexpr auto Season_SeasonEvent_TextPointer = 0xae1f0; +inline constexpr auto Season_SeasonEvent_TextPointer2 = 0xae200; +inline constexpr auto Season_SeasonEvent_TextPointer3 = 0xaeb70; +inline constexpr auto Season_SeasonPlayers_ExecutableField = 0xb9a58; +inline constexpr auto Season_SeasonPlayers_RuntimeField = 0xbb88a; +inline constexpr auto Season_SeasonPlayers_RuntimeField2 = 0xbb893; +inline constexpr auto Season_SeasonPlayers_TextPointer = 0xaf02c; +inline constexpr auto Season_SeasonPlayers_TextPointer2 = 0xaf030; +inline constexpr auto Season_SeasonPlayers_TextPointer3 = 0xaf034; +inline constexpr auto Season_SeasonPlayers_TextPointer4 = 0xaf038; +inline constexpr auto Season_SeasonPlayers_TextPointer5 = 0xaf03c; +inline constexpr auto Season_SeasonPlayers_TextPointer6 = 0xaf040; +inline constexpr auto Season_SeasonPlayers_TextPointer7 = 0xaf044; +inline constexpr auto Season_SeasonTickets_TextPointer = 0xaefec; +inline constexpr auto Season_SeasonTickets_TextPointer2 = 0xaeff0; +inline constexpr auto Season_SeasonTickets_TextPointer3 = 0xaeff4; +inline constexpr auto Season_SeasonTransition_RuntimeField = 0xbb83b; +inline constexpr auto SeriesRecords_Render_ExecutableField = 0xa102e; +inline constexpr auto SeriesRecords_Render_ExecutableField2 = 0xa1074; +inline constexpr auto SeriesRecords_Render_ExecutableField3 = 0xa169d; +inline constexpr auto SeriesRecords_Render_ExecutableField4 = 0xa16ac; +inline constexpr auto SeriesSelector = 0xa3960; +inline constexpr auto Settings_File_ExecutableField = 0xa2230; +inline constexpr auto Settings_File_ExecutableField2 = 0xa2246; +inline constexpr auto Settings_FormatError_RuntimeField = 0xaf443; +inline constexpr auto Settings_FormatError_TextPointer = 0xa46a8; +inline constexpr auto Settings_FormatError_TextPointer2 = 0xae1b8; +inline constexpr auto Settings_FormatError_TextPointer3 = 0xaeb3c; +inline constexpr auto Settings_FormatError_TextPointer4 = 0xaeb40; +inline constexpr auto Settings_FormatError_TextPointer5 = 0xaeb4c; +inline constexpr auto Settings_Letter_TextPointer = 0xa4796; +inline constexpr auto Settings_ProjectSettingsAvailability_RuntimeField = 0xa4798; +inline constexpr auto Settings_ProjectSettingsAvailability_RuntimeField2 = 0xa479f; +inline constexpr auto Settings_ProjectSettingsAvailability_RuntimeField3 = 0xa47a0; +inline constexpr auto Settings_ProjectSettingsAvailability_RuntimeField4 = 0xa47a7; +inline constexpr auto Setup_FormatError_RuntimeField = 0xa4804; +inline constexpr auto Setup_FormatError_RuntimeField10 = 0xa4838; +inline constexpr auto Setup_FormatError_RuntimeField11 = 0xa483a; +inline constexpr auto Setup_FormatError_RuntimeField2 = 0xa4808; +inline constexpr auto Setup_FormatError_RuntimeField3 = 0xa480c; +inline constexpr auto Setup_FormatError_RuntimeField4 = 0xa481c; +inline constexpr auto Setup_FormatError_RuntimeField5 = 0xa4824; +inline constexpr auto Setup_FormatError_RuntimeField6 = 0xa4828; +inline constexpr auto Setup_FormatError_RuntimeField7 = 0xa482c; +inline constexpr auto Setup_FormatError_RuntimeField8 = 0xa482f; +inline constexpr auto Setup_FormatError_RuntimeField9 = 0xa4835; +inline constexpr auto SolidPanelBackground = 0xa2560; +inline constexpr auto Spending = 0xbd4c8; +inline constexpr auto SportschauAwards_FinishSportschauAwards_RuntimeField = 0xa2533; +inline constexpr auto SportschauAwards_MatchdayIntroView_RuntimeField = 0xa2572; +inline constexpr auto SportschauAwards_MatchdayIntroView_TextPointer = 0xae6d8; +inline constexpr auto SportschauAwards_SportschauTeamInfoView_RuntimeField = 0xa253c; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField = 0xa47e0; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField2 = 0xa47e4; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField3 = 0xa47e8; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField4 = 0xa47ec; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField5 = 0xa47f0; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField6 = 0xa47f4; +inline constexpr auto SportschauRating_SportschauRatingTables_RuntimeField7 = 0xa47fb; +inline constexpr auto Sportschau_FormatError_RuntimeField = 0xa231d; +inline constexpr auto Sportschau_FormatError_RuntimeField2 = 0xa47f8; +inline constexpr auto Sportschau_FormatError_RuntimeField3 = 0xa47ff; +inline constexpr auto Sportschau_FormatError_TextPointer = 0xaeb6c; +inline constexpr auto Sportschau_Render_RuntimeField = 0xa4768; +inline constexpr auto Sportschau_Render_RuntimeField2 = 0xa476c; +inline constexpr auto Sportschau_Render_RuntimeField3 = 0xa4770; +inline constexpr auto Sportschau_Render_RuntimeField4 = 0xa4774; +inline constexpr auto Sportschau_Render_RuntimeField5 = 0xa4778; +inline constexpr auto Sportschau_Render_TextPointer = 0xa1188; +inline constexpr auto Sportschau_Render_TextPointer2 = 0xa4764; +inline constexpr auto Sportschau_Render_TextPointer3 = 0xaf180; +inline constexpr auto Sportschau_Result_ExecutableField = 0xa151b; +inline constexpr auto Sportschau_Result_TextPointer = 0xa151d; +inline constexpr auto Sportschau_Result_TextPointer2 = 0xae1c0; +inline constexpr auto SquadSlots = 0xbb128; +inline constexpr auto StadiumBlockCapacities = 0xa42fa; +inline constexpr auto StadiumPriceTable = 0xa3699; +inline constexpr auto Stadium_CopyCrop_TextPointer = 0xade98; +inline constexpr auto Stadium_CopyCrop_TextPointer2 = 0xadea4; +inline constexpr auto Stadium_CopyCrop_TextPointer3 = 0xaec48; +inline constexpr auto Stadium_CopyCrop_TextPointer4 = 0xaec4c; +inline constexpr auto Stadium_CopyCrop_TextPointer5 = 0xaec50; +inline constexpr auto Stadium_FormatError_ExecutableField = 0xa1375; +inline constexpr auto Stadium_FormatError_ExecutableField2 = 0xa1377; +inline constexpr auto Stadium_FormatError_ExecutableField3 = 0xaef1c; +inline constexpr auto Stadium_FormatError_RuntimeField = 0xaef10; +inline constexpr auto Stadium_Out_ExecutableField = 0xa137b; +inline constexpr auto Stadium_Out_ExecutableField2 = 0xa42d5; +inline constexpr auto Stadium_Out_ExecutableField3 = 0xa42d6; +inline constexpr auto Stadium_Out_ExecutableField4 = 0xae9b4; +inline constexpr auto Stadium_Out_ExecutableField5 = 0xae9d0; +inline constexpr auto Stadium_Out_RuntimeField = 0xa42b5; +inline constexpr auto Stadium_Out_RuntimeField2 = 0xa42b7; +inline constexpr auto Stadium_Out_TextPointer = 0xaef20; +inline constexpr auto Stadium_Out_TextPointer2 = 0xaef24; +inline constexpr auto Stadium_Out_TextPointer3 = 0xaef28; +inline constexpr auto Stadium_Out_TextPointer4 = 0xaef2c; +inline constexpr auto Stadium_Out_TextPointer5 = 0xaef30; +inline constexpr auto Stadium_Out_TextPointer6 = 0xaef34; +inline constexpr auto Stadium_PeripheryObjectAt_RuntimeField = 0xa4275; +inline constexpr auto Stadium_PeripheryObjectContains_ExecutableField = 0xa3feb; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer = 0xa137d; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer10 = 0xaef74; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer2 = 0xaef08; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer3 = 0xaef0c; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer4 = 0xaef14; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer5 = 0xaef18; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer6 = 0xaef5c; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer7 = 0xaef60; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer8 = 0xaef64; +inline constexpr auto Stadium_RenderBlockExpansion_TextPointer9 = 0xaef70; +inline constexpr auto Stadium_RenderInvestmentDialog_TextPointer = 0xaef04; +inline constexpr auto Stadium_RenderPanorama_ExecutableField = 0xa40e7; +inline constexpr auto Stadium_RenderPanorama_ExecutableField2 = 0xaef4c; +inline constexpr auto Stadium_RenderPanorama_RuntimeField = 0xa3fed; +inline constexpr auto Stadium_RenderPanorama_RuntimeField2 = 0xa3fef; +inline constexpr auto Stadium_RenderPanorama_RuntimeField3 = 0xa3ff1; +inline constexpr auto Stadium_RenderPanorama_RuntimeField4 = 0xa4093; +inline constexpr auto Stadium_RenderPanorama_RuntimeField5 = 0xa4095; +inline constexpr auto Stadium_RenderPanorama_RuntimeField6 = 0xa4267; +inline constexpr auto Stadium_RenderPanorama_RuntimeField7 = 0xa4283; +inline constexpr auto Stadium_RenderPanorama_RuntimeField8 = 0xa4291; +inline constexpr auto Stadium_RenderPanorama_TextPointer = 0xae940; +inline constexpr auto Stadium_RenderPanorama_TextPointer2 = 0xaef38; +inline constexpr auto Stadium_RenderPanorama_TextPointer3 = 0xaef3c; +inline constexpr auto Stadium_RenderPanorama_TextPointer4 = 0xaef40; +inline constexpr auto Stadium_RenderPanorama_TextPointer5 = 0xaef44; +inline constexpr auto Stadium_RenderPanorama_TextPointer6 = 0xaef48; +inline constexpr auto Stadium_StadiumDataFromGame_ExecutableField = 0xa1054; +inline constexpr auto Stadium_StadiumDataFromGame_TextPointer = 0xaec44; +inline constexpr auto StatisticsRankings_FormatError_RuntimeField = 0xa3caa; +inline constexpr auto StatisticsRankings_FormatError_RuntimeField2 = 0xa3cb3; +inline constexpr auto StockExchange = 0xac888; +inline constexpr auto Strengths_Fill_RuntimeField = 0xa454a; +inline constexpr auto Strengths_Fill_RuntimeField2 = 0xa454c; +inline constexpr auto Strengths_Fill_RuntimeField3 = 0xa4578; +inline constexpr auto Strengths_Fill_TextPointer = 0xa1477; +inline constexpr auto Strengths_PointerDown_RuntimeField = 0xa456f; +inline constexpr auto Strengths_SelectorAt_RuntimeField = 0xa4562; +inline constexpr auto Strengths_SelectorAt_RuntimeField2 = 0xa4564; +inline constexpr auto Strengths_Selector_RuntimeField = 0xa4566; +inline constexpr auto Strengths_Selector_RuntimeField2 = 0xa4568; +inline constexpr auto SyntheticCupAlternateResultBlock = 0xa8280; +inline constexpr auto SyntheticCupFifthParticipantBlock = 0xa8080; +inline constexpr auto SyntheticCupFifthResultBlock = 0xa82a0; +inline constexpr auto SyntheticCupFirstLegBegin = 0xa4000; +inline constexpr auto SyntheticCupFirstResultPadding = 0xa8202; +inline constexpr auto SyntheticCupFourthParticipantBlock = 0xa8060; +inline constexpr auto SyntheticCupFourthParticipantValue = 0xa8062; +inline constexpr auto SyntheticCupFourthResultBlock = 0xa8260; +inline constexpr auto SyntheticCupParticipantsBegin = 0xa8000; +inline constexpr auto SyntheticCupResultsBegin = 0xa8200; +inline constexpr auto SyntheticCupSecondLegBegin = 0xa4200; +inline constexpr auto SyntheticCupSecondParticipantBlock = 0xa8020; +inline constexpr auto SyntheticCupSecondResultBlock = 0xa8220; +inline constexpr auto SyntheticCupSecondResultPadding = 0xa8204; +inline constexpr auto SyntheticCupThirdParticipantBlock = 0xa8040; +inline constexpr auto SyntheticCupThirdResultBlock = 0xa8240; +inline constexpr auto SyntheticCupThirdResultPadding = 0xa8242; +inline constexpr auto SyntheticCupWorkspaceBegin = 0xa8400; +inline constexpr auto SystemManagerNameText = 0xaea94; +inline constexpr auto TableFlags = 0xa3883; +inline constexpr auto TableForecast_InvalidArgument_RuntimeField = 0xbd8f7; +inline constexpr auto TacticsBoards = 0xb327c; +inline constexpr auto Tactics_Click_RuntimeField = 0xa20cb; +inline constexpr auto Tactics_Click_RuntimeField2 = 0xa20d2; +inline constexpr auto Tactics_Click_RuntimeField3 = 0xa20d3; +inline constexpr auto Tactics_Click_RuntimeField4 = 0xa20db; +inline constexpr auto Tactics_Click_RuntimeField5 = 0xa20e3; +inline constexpr auto Tactics_Click_RuntimeField6 = 0xa20f2; +inline constexpr auto Tactics_DrawSetting_ExecutableFieldUnsigned = 0xa1fb4u; +inline constexpr auto Tactics_DrawSetting_RuntimeField = 0xa1fb0; +inline constexpr auto Tactics_DrawSetting_RuntimeField10 = 0xa202c; +inline constexpr auto Tactics_DrawSetting_RuntimeField11 = 0xa2083; +inline constexpr auto Tactics_DrawSetting_RuntimeField12 = 0xa2084; +inline constexpr auto Tactics_DrawSetting_RuntimeField2 = 0xa1ffc; +inline constexpr auto Tactics_DrawSetting_RuntimeField3 = 0xa1ffd; +inline constexpr auto Tactics_DrawSetting_RuntimeField4 = 0xa2004; +inline constexpr auto Tactics_DrawSetting_RuntimeField5 = 0xa2005; +inline constexpr auto Tactics_DrawSetting_RuntimeField6 = 0xa2010; +inline constexpr auto Tactics_DrawSetting_RuntimeField7 = 0xa2014; +inline constexpr auto Tactics_DrawSetting_RuntimeField8 = 0xa201c; +inline constexpr auto Tactics_DrawSetting_RuntimeField9 = 0xa2024; +inline constexpr auto Tactics_Render_TextPointer = 0xaf24c; +inline constexpr auto TeamFlags = 0xba3c0; +inline constexpr auto TeamMorale = 0xba37c; +inline constexpr auto TeamStatistics_Render_ExecutableField = 0xa16ae; +inline constexpr auto TeamStatistics_Render_RuntimeField = 0xa3886; +inline constexpr auto TeamStatistics_Render_RuntimeField2 = 0xa5116; +inline constexpr auto TeamStatistics_Render_RuntimeField3 = 0xae530; +inline constexpr auto TeamStatistics_Render_RuntimeField3Unsigned = 0xae530u; +inline constexpr auto TeamStatistics_Render_TextPointer = 0xae4a8; +inline constexpr auto TeamStatistics_Render_TextPointer10 = 0xae550; +inline constexpr auto TeamStatistics_Render_TextPointer10Unsigned = 0xae550u; +inline constexpr auto TeamStatistics_Render_TextPointer11 = 0xae558; +inline constexpr auto TeamStatistics_Render_TextPointer12 = 0xae55c; +inline constexpr auto TeamStatistics_Render_TextPointer13 = 0xae560; +inline constexpr auto TeamStatistics_Render_TextPointer14 = 0xae564; +inline constexpr auto TeamStatistics_Render_TextPointer15 = 0xae568; +inline constexpr auto TeamStatistics_Render_TextPointer16 = 0xae56c; +inline constexpr auto TeamStatistics_Render_TextPointer17 = 0xae570; +inline constexpr auto TeamStatistics_Render_TextPointer18 = 0xae574; +inline constexpr auto TeamStatistics_Render_TextPointer18Unsigned = 0xae574u; +inline constexpr auto TeamStatistics_Render_TextPointer19 = 0xae578; +inline constexpr auto TeamStatistics_Render_TextPointer19Unsigned = 0xae578u; +inline constexpr auto TeamStatistics_Render_TextPointer2 = 0xae4e8; +inline constexpr auto TeamStatistics_Render_TextPointer20 = 0xae57c; +inline constexpr auto TeamStatistics_Render_TextPointer20Unsigned = 0xae57cu; +inline constexpr auto TeamStatistics_Render_TextPointer21 = 0xae588; +inline constexpr auto TeamStatistics_Render_TextPointer22 = 0xaeb90; +inline constexpr auto TeamStatistics_Render_TextPointer22Unsigned = 0xaeb90u; +inline constexpr auto TeamStatistics_Render_TextPointer23 = 0xaeb94; +inline constexpr auto TeamStatistics_Render_TextPointer24 = 0xaeb98; +inline constexpr auto TeamStatistics_Render_TextPointer25 = 0xaeb9c; +inline constexpr auto TeamStatistics_Render_TextPointer3 = 0xae508; +inline constexpr auto TeamStatistics_Render_TextPointer4 = 0xae514; +inline constexpr auto TeamStatistics_Render_TextPointer5 = 0xae53c; +inline constexpr auto TeamStatistics_Render_TextPointer5Unsigned = 0xae53cu; +inline constexpr auto TeamStatistics_Render_TextPointer6 = 0xae540; +inline constexpr auto TeamStatistics_Render_TextPointer6Unsigned = 0xae540u; +inline constexpr auto TeamStatistics_Render_TextPointer7 = 0xae544; +inline constexpr auto TeamStatistics_Render_TextPointer7Unsigned = 0xae544u; +inline constexpr auto TeamStatistics_Render_TextPointer8 = 0xae548; +inline constexpr auto TeamStatistics_Render_TextPointer8Unsigned = 0xae548u; +inline constexpr auto TeamStatistics_Render_TextPointer9 = 0xae54c; +inline constexpr auto TeamStatistics_Render_TextPointerUnsigned = 0xae4a8u; +inline constexpr auto TeamStatistics_SourceLeagueName_RuntimeField = 0xbdb8d; +inline constexpr auto Teams = 0xb5e14; +inline constexpr auto TeamsWithSquads = 0xa2c2e; +inline constexpr auto TextGradientDisabled = 0xa2557; +inline constexpr auto TextGradientMode = 0xa3648; +inline constexpr auto TextPointerTable = 0xade00; +inline constexpr auto TitleText = 0xae194; +inline constexpr auto Titles = 0xaf450; +inline constexpr auto TopScorers_MetricTextAddress_ExecutableField = 0xae228; +inline constexpr auto TopScorers_MetricTextAddress_ExecutableField2 = 0xae22c; +inline constexpr auto TopScorers_MetricTextAddress_ExecutableField3 = 0xae230; +inline constexpr auto TopScorers_Render_TextPointer = 0xaeb8c; +inline constexpr auto TopScorers_ScopeTextAddress_ExecutableField = 0xae234; +inline constexpr auto TopScorers_ScopeTextAddress_ExecutableField2 = 0xae238; +inline constexpr auto Toto_FormatError_RuntimeField = 0xaf884; +inline constexpr auto Toto_Render_ExecutableField = 0xa143c; +inline constexpr auto Toto_Render_ExecutableField2 = 0xa143e; +inline constexpr auto Toto_Render_RuntimeField = 0xa23c1; +inline constexpr auto Toto_Render_RuntimeField2 = 0xa4536; +inline constexpr auto Toto_Render_TextPointer = 0xae114; +inline constexpr auto Toto_Render_TextPointer2 = 0xaf238; +inline constexpr auto Toto_Render_TextPointer3 = 0xaf23c; +inline constexpr auto TournamentName = 0xae738; +inline constexpr auto TrainingCamp_Click_RuntimeField = 0xa445b; +inline constexpr auto TrainingCamp_Click_RuntimeField2 = 0xa4463; +inline constexpr auto TrainingCamp_FocusControls_RuntimeField = 0xa4457; +inline constexpr auto TrainingCamp_FocusControls_RuntimeField2 = 0xa446b; +inline constexpr auto TrainingCamp_FocusControls_TextPointer = 0xa4474; +inline constexpr auto TrainingCamp_ResortDetails_RuntimeField = 0xa4453; +inline constexpr auto Training_Button_RuntimeField = 0xa435f; +inline constexpr auto Training_Click_RuntimeField = 0xa43b7; +inline constexpr auto Training_Click_RuntimeField2 = 0xa43bf; +inline constexpr auto Training_Click_RuntimeField3 = 0xa43c7; +inline constexpr auto Training_Click_RuntimeField4 = 0xa43cb; +inline constexpr auto Training_Click_RuntimeField5 = 0xa43cf; +inline constexpr auto Training_Click_RuntimeField6 = 0xa43d3; +inline constexpr auto Training_Click_RuntimeField7 = 0xa43d7; +inline constexpr auto Training_Click_RuntimeField8 = 0xa43db; +inline constexpr auto Training_Click_RuntimeField9 = 0xa43df; +inline constexpr auto Training_Render_RuntimeField = 0xa43a3; +inline constexpr auto Training_Render_TextPointer = 0xa43a7; +inline constexpr auto Training_Render_TextPointer2 = 0xa43af; +inline constexpr auto Training_Render_TextPointer3 = 0xae2e4; +inline constexpr auto Training_Render_TextPointer4 = 0xaf19c; +inline constexpr auto Training_Render_TextPointer5 = 0xaf1a0; +inline constexpr auto Training_Render_TextPointer6 = 0xaf1a4; +inline constexpr auto TransferHistory_FormatError_RuntimeField = 0xa39a0; +inline constexpr auto TransferHistory_FormatError_TextPointer = 0xa1048; +inline constexpr auto TransferMarket_Click_RuntimeField = 0xa211e; +inline constexpr auto TransferMarket_Click_RuntimeField2 = 0xa2120; +inline constexpr auto TransferMarket_Click_RuntimeField3 = 0xa2122; +inline constexpr auto TransferMarket_ListedPlayers_RuntimeField = 0xb6235; +inline constexpr auto TransferMarket_Rect_ExecutableField = 0xa0047; +inline constexpr auto TransferMarket_Rect_ExecutableField2 = 0xa004a; +inline constexpr auto TransferMarket_Rect_TextPointer = 0xa0041; +inline constexpr auto TransferMarket_Rect_TextPointer2 = 0xa0045; +inline constexpr auto TransferMarket_Rect_TextPointer3 = 0xae148; +inline constexpr auto TransferMarket_Rect_TextPointer4 = 0xae14c; +inline constexpr auto TransferMarket_Rect_TextPointer5 = 0xae150; +inline constexpr auto TransferMarket_Rect_TextPointer6 = 0xaecac; +inline constexpr auto TransferMarket_Rect_TextPointer7 = 0xaf250; +inline constexpr auto TransferMarket_Render_TextPointer = 0xaf264; +inline constexpr auto Turn_EventEnd_RuntimeField = 0xbdb1c; +inline constexpr auto Turn_FinishEvent_ExecutableField = 0xb63dc; +inline constexpr auto Week_AutoTraining_ExecutableField = 0x6e8ca; +inline constexpr auto Week_AutoTraining_ExecutableField2 = 0x6eac8; +inline constexpr auto Week_AutoTraining_ExecutableField3 = 0xa86ce; +inline constexpr auto Week_AutoTraining_ExecutableField4 = 0xae8c6; +inline constexpr auto Weekly_AdvertisingOffers_TextPointer = 0xaee84; +inline constexpr auto Weekly_DecideBids_TextPointer = 0xaedd0; +inline constexpr auto Weekly_DecideBids_TextPointer2 = 0xaedd4; +inline constexpr auto Weekly_DecideBids_TextPointer3 = 0xaeddc; +inline constexpr auto Weekly_ExecuteTransfer_RuntimeField = 0xa253b; +inline constexpr auto Weekly_ExecuteTransfer_TextPointer = 0xaee0c; +inline constexpr auto Weekly_ExecuteTransfer_TextPointer2 = 0xaee10; +inline constexpr auto Weekly_ExecuteTransfer_TextPointer3 = 0xaee14; +inline constexpr auto Weekly_ExecuteTransfer_TextPointer4 = 0xaee18; +inline constexpr auto Weekly_FacilityAgeing_TextPointer = 0xaeef8; +inline constexpr auto Weekly_FacilityDamage_TextPointer = 0xae850; +inline constexpr auto Weekly_FacilityDamage_TextPointer2 = 0xae868; +inline constexpr auto Weekly_FacilityDamage_TextPointer3 = 0xae978; +inline constexpr auto Weekly_FacilityDamage_TextPointer4 = 0xaeed0; +inline constexpr auto Weekly_FacilityDamage_TextPointer5 = 0xaeed4; +inline constexpr auto Weekly_Fail_TextPointer = 0xaee20; +inline constexpr auto Weekly_InterestedManagers_RuntimeField = 0xa2544; +inline constexpr auto Weekly_ManagerOffers_TextPointer = 0xaef90; +inline constexpr auto Weekly_ManagerOffers_TextPointer2 = 0xaef94; +inline constexpr auto Weekly_ManagerOffers_TextPointer3 = 0xaef98; +inline constexpr auto Weekly_ManagerOffers_TextPointer4 = 0xaef9c; +inline constexpr auto Weekly_ManagerOffers_TextPointer5 = 0xaefa8; +inline constexpr auto Weekly_ManagerOffers_TextPointer6 = 0xaf358; +inline constexpr auto Weekly_PendingSettleHumanBuyer_RuntimeField = 0xbdb93; +inline constexpr auto Weekly_PendingSettle_TextPointer = 0xaee00; +inline constexpr auto Weekly_PreMatchOffer_RuntimeField = 0xbb848; +inline constexpr auto Weekly_PreMatchOffer_RuntimeField2 = 0xbb84c; +inline constexpr auto Weekly_PreMatchOffer_RuntimeField3 = 0xbb850; +inline constexpr auto Weekly_PreMatchOffer_TextPointer = 0xaefb8; +inline constexpr auto Weekly_PreMatchOffer_TextPointer10 = 0xaefe0; +inline constexpr auto Weekly_PreMatchOffer_TextPointer2 = 0xaefbc; +inline constexpr auto Weekly_PreMatchOffer_TextPointer3 = 0xaefc0; +inline constexpr auto Weekly_PreMatchOffer_TextPointer4 = 0xaefc4; +inline constexpr auto Weekly_PreMatchOffer_TextPointer5 = 0xaefc8; +inline constexpr auto Weekly_PreMatchOffer_TextPointer6 = 0xaefd0; +inline constexpr auto Weekly_PreMatchOffer_TextPointer7 = 0xaefd4; +inline constexpr auto Weekly_PreMatchOffer_TextPointer8 = 0xaefd8; +inline constexpr auto Weekly_PreMatchOffer_TextPointer9 = 0xaefdc; +inline constexpr auto Weekly_ProcessPendingBatch_TextPointer = 0xaefe4; +inline constexpr auto Weekly_ProcessPendingBatch_TextPointer2 = 0xaefe8; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer = 0xaeed8; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer2 = 0xaeedc; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer3 = 0xaeee0; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer4 = 0xaeee4; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer5 = 0xaeee8; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer6 = 0xaeeec; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer7 = 0xaeef0; +inline constexpr auto Weekly_SeasonTicketCompensation_TextPointer8 = 0xaeef4; +inline constexpr auto Weekly_TransferListCountdown_TextPointer = 0xaede4; +inline constexpr auto Weekly_TransferListCountdown_TextPointer2 = 0xaede8; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer = 0xae8c4; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer2 = 0xaee5c; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer3 = 0xaee60; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer4 = 0xaee64; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer5 = 0xaee68; +inline constexpr auto Weekly_WeeklyProcessing_TextPointer6 = 0xaee6c; +inline constexpr auto WorldCupStatistics_FormatError_RuntimeField = 0xa3990; +inline constexpr auto WorldCupStatistics_FormatError_RuntimeField2 = 0xa3994; +inline constexpr auto WorldCupStatistics_FormatError_RuntimeField3 = 0xa3998; +inline constexpr auto WorldCupStatistics_Render_ExecutableField = 0xa1045; +inline constexpr auto EnglishFourTeamFixtureTable = 0x6eea0; +inline constexpr auto EnglishSixTeamFixtureTable = 0x6eed4; +inline constexpr auto EnglishTwelveTeamFixtureTable = 0x6f0bc; +inline constexpr auto EnglishTwentyTeamFixtureTable = 0x6ee40; +} // namespace bmh::layout diff --git a/src/formats/fbm.cpp b/src/formats/fbm.cpp new file mode 100644 index 0000000..a74240b --- /dev/null +++ b/src/formats/fbm.cpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/fbm.hpp" + +#include +#include + +namespace bmh { + +void fbm_decrypt(uint8_t* data, size_t n, uint8_t key) { + for (size_t i = 0; i < n; i++) { + data[i] = uint8_t((data[i] - key) ^ key); + key = uint8_t(key - 0x29); + } +} + +void fbm_encrypt(uint8_t* data, size_t n, uint8_t key) { + for (size_t i = 0; i < n; i++) { + data[i] = uint8_t((data[i] ^ key) + key); + key = uint8_t(key - 0x29); + } +} + +Savegame load_savegame(const std::filesystem::path& path) { + Bytes d = read_file(path); + static const char magic[] = "KRON_FBM"; + auto it = std::search(d.begin(), d.end(), magic, magic + 8); + if (it == d.end()) throw FormatError("FBM: magic KRON_FBM not found"); + size_t m = size_t(it - d.begin()); + if (m + 26 > d.size()) throw FormatError("FBM: truncated header"); + + Savegame s; + s.plain_header.assign(d.begin(), it); + size_t p = m + 10; // "KRON_FBM\0" + 1 byte + s.id1 = le32(d, p); + p += 4; + s.version.assign(reinterpret_cast(&d[p]), strnlen(reinterpret_cast(&d[p]), 6)); + p += 6; + s.id2 = le32(d, p); + p += 4; + s.random = d[p++]; + s.key = d[p++]; + + s.stream.assign(d.begin() + p, d.end() - 1); + s.checksum = d.back(); + fbm_decrypt(s.stream.data(), s.stream.size(), s.key); + + uint8_t sum = s.key; + for (uint8_t b : s.stream) sum = uint8_t(sum + b); + s.checksum_ok = sum == s.checksum; + return s; +} + +} // namespace bmh diff --git a/src/formats/fbm.hpp b/src/formats/fbm.hpp new file mode 100644 index 0000000..14edb8e --- /dev/null +++ b/src/formats/fbm.hpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// .FBM savegame container (docs/formats/FBM.md): plain header, magic, encrypted stream, checksum. +// Writer FbmDecrypt2 + NationalCoachAfterLoad, stream cipher in FbmDecrypt. +#include +#include +#include + +#include "formats/binary.hpp" + +namespace bmh { + +struct Savegame { + Bytes plain_header; // FbmDecrypt2 output (date, names for the load list) + uint32_t id1 = 0, id2 = 0; + std::string version; // "V2.24" + uint8_t random = 0, key = 0; + Bytes stream; // decrypted game state + trailer blocks + uint8_t checksum = 0; + bool checksum_ok = false; +}; + +// Stream cipher: encrypt c = (b ^ k) + k, decrypt b = (c - k) ^ k, then k -= 0x29 +void fbm_decrypt(uint8_t* data, size_t n, uint8_t key); +void fbm_encrypt(uint8_t* data, size_t n, uint8_t key); + +Savegame load_savegame(const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/formats/font.cpp b/src/formats/font.cpp new file mode 100644 index 0000000..156755a --- /dev/null +++ b/src/formats/font.cpp @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/font.hpp" + +namespace bmh { + +Font load_font(const std::filesystem::path& path) { + Bytes d = read_file(path); + if (d.size() < 28) throw FormatError("FNT: file too short"); + Font f; + f.height = le16(d, 0); + f.flags = d[3]; + f.nominal_width = le16(d, 4); + f.baseline = le16(d, 6); + f.lo_char = d[8]; + f.hi_char = d[9]; + f.modulo = le16(d, 16); + + size_t n = size_t(f.hi_char - f.lo_char + 2); + size_t bmp = 28, loc = bmp + size_t(f.height) * f.modulo, spc = loc + n * 4; + size_t end = spc + (f.flags == 2 ? 0 : n * 2); + if (end != d.size()) throw FormatError("FNT: size mismatch in " + path.string()); + + f.bitmap.assign(d.begin() + bmp, d.begin() + loc); + for (size_t i = 0; i < n; i++) { + int16_t adv = f.flags == 2 ? int16_t(f.nominal_width) : int16_t(le16(d, spc + i * 2)); + f.glyphs.push_back({le16(d, loc + i * 4), le16(d, loc + i * 4 + 2), adv}); + } + return f; +} + +const Font::Glyph& Font::glyph(uint8_t c) const { + if (c < lo_char || c > hi_char) return glyphs.back(); + return glyphs[c - lo_char]; +} + +int Font::text_width(std::string_view text) const { + int w = 0; + for (char c : text) w += glyph(uint8_t(c)).advance; + return w; +} + +int Font::draw(Image& target, int x, int y, std::string_view text, uint8_t color) const { + for (char c : text) { + const Glyph& g = glyph(uint8_t(c)); + for (int row = 0; row < height; row++) { + for (int b = 0; b < g.bit_width; b++) { + int bit = g.bit_offset + b; + if (!(bitmap[size_t(row) * modulo + bit / 8] & (0x80 >> (bit % 8)))) continue; + int px = x + b, py = y + row; + if (px >= 0 && py >= 0 && px < target.width && py < target.height) target.at(px, py) = color; + } + } + x += g.advance; + } + return x; +} + +} // namespace bmh diff --git a/src/formats/font.hpp b/src/formats/font.hpp new file mode 100644 index 0000000..4f1a605 --- /dev/null +++ b/src/formats/font.hpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// .FNT bitmap fonts, Amiga TextFont layout (docs/formats/FNT.md), original loader Glyph +#include +#include +#include +#include + +#include "formats/vga.hpp" + +namespace bmh { + +struct Font { + int height = 0; + int baseline = 0; + int nominal_width = 0; + uint8_t flags = 0; + uint8_t lo_char = 0, hi_char = 0; + int modulo = 0; + std::vector bitmap; // height * modulo, 1 bpp MSB first + struct Glyph { uint16_t bit_offset, bit_width; int16_t advance; }; + std::vector glyphs; // hi - lo + 2, last one = replacement glyph + + const Glyph& glyph(uint8_t c) const; + int text_width(std::string_view text) const; + // text in the game's ISO 646-DE encoding; returns the x after the last glyph + int draw(Image& target, int x, int y, std::string_view text, uint8_t color) const; +}; + +Font load_font(const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/formats/le.cpp b/src/formats/le.cpp new file mode 100644 index 0000000..f6b7814 --- /dev/null +++ b/src/formats/le.cpp @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/le.hpp" +#include "formats/rule_base.hpp" + +#include +#include +#include + +namespace bmh { + +namespace { + +struct Object { + uint32_t vsize, base, flags, page_index, page_count; +}; + +} // namespace + +std::string LeImage::cstring(uint32_t address) const { + std::string s; + while (contains(address) && u8(address) != 0) s.push_back(char(u8(address++))); + return s; +} + +namespace { +constexpr char kImageMagic[14] = "OPENBMH-IMAGE"; // 13 characters and the NUL +} + +void save_image(const LeImage& image, const std::filesystem::path& path) { + Bytes out(kImageMagic, kImageMagic + sizeof kImageMagic); + for (uint32_t v : {image.base(), image.size()}) + for (int b = 0; b < 4; ++b) out.push_back(uint8_t(v >> (8 * b))); + out.insert(out.end(), image.bytes().begin(), image.bytes().end()); + std::ofstream file(path, std::ios::binary | std::ios::trunc); + file.write(reinterpret_cast(out.data()), std::streamsize(out.size())); + if (!file) throw FormatError("cannot write the OpenBMH image"); +} + +LeImage load_le(const std::filesystem::path& path) { + const Bytes raw = read_file(path); + if (raw.size() >= sizeof kImageMagic + 8 && std::equal(kImageMagic, kImageMagic + sizeof kImageMagic, raw.begin())) { + const auto word = [&](size_t at) { return uint32_t(raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16) | uint32_t(raw[at + 3]) << 24; }; + const uint32_t base = word(sizeof kImageMagic), size = word(sizeof kImageMagic + 4); + if (raw.size() != sizeof kImageMagic + 8 + size_t(size)) throw FormatError("OpenBMH image: wrong size"); + LeImage img = LeImage::from_bytes(base, Bytes(raw.begin() + sizeof kImageMagic + 8, raw.end())); + apply_rule_base(img); + return img; + } + auto u8 = [&](size_t o) -> uint32_t { + if (o >= raw.size()) throw FormatError("LE: read beyond the file"); + return raw[o]; + }; + auto u16 = [&](size_t o) { return u8(o) | u8(o + 1) << 8; }; + auto u32 = [&](size_t o) { return u16(o) | uint32_t(u16(o + 2)) << 16; }; + const size_t le = u32(0x3c); + if (u16(le) != 0x454c) throw FormatError("LE: no LE header"); + auto h = [&](size_t off) { return u32(le + off); }; + const uint32_t pages = h(0x14), page_size = h(0x28), last_page = h(0x2c); + const size_t object_table = le + h(0x40), page_map = le + h(0x48); + const size_t fixup_pages = le + h(0x68), fixup_records = le + h(0x6c); + const uint32_t objects = h(0x44), data_pages = h(0x80); + + std::vector obj; + uint32_t lo = 0xFFFFFFFFu, hi = 0; + for (uint32_t i = 0; i < objects; i++) { + const size_t o = object_table + i * 24; + Object ob{u32(o), u32(o + 4), u32(o + 8), u32(o + 12), u32(o + 16)}; + obj.push_back(ob); + const uint32_t span = std::max(ob.vsize, ob.page_count * page_size); + lo = std::min(lo, ob.base); + hi = std::max(hi, ob.base + (span + page_size - 1) / page_size * page_size); + } + LeImage img; + img.base_ = lo; + img.bytes_.assign(hi - lo, 0); + std::vector page_address(pages + 1, 0); + for (const Object& ob : obj) + for (uint32_t p = 0; p < ob.page_count; p++) { + const uint32_t logical = ob.page_index + p; + const size_t e = page_map + (logical - 1) * 4; + const uint32_t file_page = u8(e) << 16 | u8(e + 1) << 8 | u8(e + 2); + const uint32_t va = ob.base + p * page_size; + if (logical <= pages) page_address[logical] = va; + if (u8(e + 3) != 0) continue; // not a loaded page + size_t size = file_page == pages ? last_page : page_size; + const size_t src = data_pages + size_t(file_page - 1) * page_size; + size = std::min(size, raw.size() - src); + std::copy(raw.begin() + long(src), raw.begin() + long(src + size), img.bytes_.begin() + (va - lo)); + } + auto put16 = [&](size_t pos, uint32_t v) { + img.bytes_[pos] = uint8_t(v), img.bytes_[pos + 1] = uint8_t(v >> 8); + }; + auto put32 = [&](size_t pos, uint32_t v) { put16(pos, v), put16(pos + 2, v >> 16); }; + for (uint32_t pg = 1; pg <= pages; pg++) { + size_t r = fixup_records + u32(fixup_pages + (pg - 1) * 4); + const size_t end = fixup_records + u32(fixup_pages + pg * 4); + while (r < end) { + const uint32_t src = u8(r), flags = u8(r + 1); + r += 2; + const uint32_t type = src & 0x0f; + const bool list = (src & 0x20) != 0; + uint32_t count = 1; + int16_t source_offset = 0; + if (list) count = u8(r++); + else source_offset = int16_t(u16(r)), r += 2; + if (flags & 3) throw FormatError("LE: external fixup"); + uint32_t target_object; + if (flags & 0x40) target_object = u16(r), r += 2; + else target_object = u8(r++); + uint32_t target_offset = 0; + if (type != 0x02) { + if (flags & 0x10) target_offset = u32(r), r += 4; + else target_offset = u16(r), r += 2; + } + std::vector offsets; + if (list) + for (uint32_t k = 0; k < count; k++) offsets.push_back(int16_t(u16(r))), r += 2; + else + offsets.push_back(source_offset); + const uint32_t target = obj.at(target_object - 1).base + target_offset; + for (int16_t so : offsets) { + const uint32_t sa = page_address[pg] + uint32_t(int32_t(so)); + const int64_t pos = int64_t(sa) - lo; + if (pos < 0 || pos + 4 > int64_t(img.bytes_.size())) continue; + switch (type) { + case 0x07: put32(size_t(pos), target); break; + case 0x08: put32(size_t(pos), target - (sa + 4)); break; + case 0x05: put16(size_t(pos), target); break; + case 0x02: put16(size_t(pos), target_object); break; + case 0x06: put32(size_t(pos), target), put16(size_t(pos) + 4, target_object); break; + default: break; + } + } + } + } + apply_rule_base(img); + return img; +} + +} // namespace bmh diff --git a/src/formats/le.hpp b/src/formats/le.hpp new file mode 100644 index 0000000..a3dab4d --- /dev/null +++ b/src/formats/le.hpp @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The original program itself (BMH.exe, a DOS/4GW "LE" linear executable) as a data file. +// +// Many tables and all message texts of the game live in the data object of BMH.exe. Like +// the other original files it is read at runtime, never shipped: load_le() loads every +// object at its link address and applies the internal fixups, so addresses and stored +// pointers are the "LE addresses" used throughout the port (e.g. MatchdaySetup_Attendance_ExecutableField), exactly as in +// the disassembly (runtime verification produces the same image for Ghidra). + +#include +#include +#include + +#include "formats/binary.hpp" + +namespace bmh { + +class LeImage { +public: + uint32_t base() const { return base_; } + uint32_t size() const { return uint32_t(bytes_.size()); } + bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); } + uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); } + uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); } + uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; } + // A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp). + std::string cstring(uint32_t address) const; + // The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer). + std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); } + const uint8_t* data(uint32_t address) const { return bytes_.data() + (address - base_); } + // Overwrites bytes inside the image (the rule base, formats/rule_base.hpp). + void patch(uint32_t address, const uint8_t* bytes, size_t count) { + for (size_t i = 0; i < count; ++i) bytes_.at(address - base_ + i) = bytes[i]; + } + + // An image built by OpenBMH itself (the English FLTD.EXE translated into the German + // address space, launch/fltd.hpp). + static LeImage from_bytes(uint32_t base, Bytes bytes) { + LeImage img; + img.base_ = base; + img.bytes_ = std::move(bytes); + return img; + } + const Bytes& bytes() const { return bytes_; } + + friend LeImage load_le(const std::filesystem::path& path); + +private: + uint32_t base_ = 0; + Bytes bytes_; +}; + +// OpenBMH deviates from the original: applies a shared supported rule profile when loading editions with different rule-table values. +// Throws FormatError for files that are not LE executables or use external fixups. +// A German BMH.EXE is loaded with the OpenBMH rule base applied (formats/rule_base.hpp): +// every edition plays by the supported rule profile rule values. +LeImage load_le(const std::filesystem::path& path); + +// The OpenBMH image format: "OPENBMH-IMAGE" NUL, u32 base, u32 size, the bytes. load_le() +// reads it as well, so a translated image can stand in for BMH.exe in a data directory. +void save_image(const LeImage& image, const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/formats/m3d.cpp b/src/formats/m3d.cpp new file mode 100644 index 0000000..402150a --- /dev/null +++ b/src/formats/m3d.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/m3d.hpp" + +#include + +namespace bmh { + +namespace { + +struct Reader { + const Bytes& d; + size_t pos = 0; + Bytes take(size_t n) { + if (pos + n > d.size()) throw FormatError("M3D: unexpected end of file"); + Bytes b(d.begin() + pos, d.begin() + pos + n); + pos += n; + return b; + } +}; + +std::vector split_pool(const Bytes& pool) { + std::vector out; + size_t start = 0; + for (size_t i = 0; i < pool.size(); i++) + if (pool[i] == 0) { out.emplace_back(reinterpret_cast(pool.data() + start), i - start); start = i + 1; } + return out; +} + +std::string pool_string(const Bytes& pool, size_t offset) { + if (offset >= pool.size()) throw FormatError("M3D: string offset out of range"); + const char* s = reinterpret_cast(pool.data() + offset); + return std::string(s, strnlen(s, pool.size() - offset)); +} + +} // namespace + +Database load_database(const std::filesystem::path& path, const DbCounts& c) { + Bytes d = read_file(path); + Reader r{d}; + Bytes lens = r.take(8); + size_t len_clubs = le16(lens, 0), len_players = le16(lens, 2), len_refs = le16(lens, 4), len_stadiums = le16(lens, 6); + + Database db; + db.raw_player_bonus_values = r.take(c.n66 + 0x32); + Bytes club_pool = r.take(len_clubs); + Bytes player_pool = r.take(len_players); + Bytes ref_pool = r.take(len_refs), stadium_pool = r.take(len_stadiums); + db.referees = split_pool(ref_pool); + db.stadiums = split_pool(stadium_pool); + Bytes club_ofs = r.take(c.clubs * 2); + Bytes player_ofs = r.take(c.players * 2); + db.pools[0] = club_pool, db.pools[1] = player_pool, db.pools[2] = ref_pool, db.pools[3] = stadium_pool; + db.raw_club_name_offsets = club_ofs, db.raw_player_name_offsets = player_ofs; + db.raw_database_metadata = r.take(100); + db.raw_club_auxiliary_words = r.take(c.n42 * 2); + db.raw_club_badge_selectors = r.take(c.clubs * 2); + db.raw_foreign_club_strength = r.take(0xFB); + db.raw_league_auxiliary_bytes = r.take(0xBD); + db.raw_referee_properties = r.take(0x32); + db.raw_club_kit_selectors = r.take(0x1A3); + db.raw_club_short_name_offsets = r.take(0xA8); + db.squad_list = r.take((c.n66 - 4) * 2 + 0x6C); + Bytes w35c = r.take(c.players * 4), w368 = r.take(c.players * 4), w364 = r.take(c.players * 4); + if (r.pos != d.size()) throw FormatError("M3D: trailing data, table sizes do not match"); + + for (uint32_t i = 0; i < c.clubs; i++) db.club_names.push_back(pool_string(club_pool, le16(club_ofs, i * 2))); + for (uint32_t i = 0; i < c.players; i++) + db.players.push_back({pool_string(player_pool, le16(player_ofs, i * 2)), le32(w35c, i * 4), le32(w368, i * 4), le32(w364, i * 4)}); + return db; +} + +} // namespace bmh diff --git a/src/formats/m3d.hpp b/src/formats/m3d.hpp new file mode 100644 index 0000000..3e59423 --- /dev/null +++ b/src/formats/m3d.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// M3D.MAN master database (docs/formats/M3D.md), read in CareerFirstSteps2 +#include +#include +#include +#include + +#include "formats/binary.hpp" + +namespace bmh { + +// Table sizes, initial values of CareerSession_DataDirectory_RuntimeField / CareerSession_DataDirectory_RuntimeField3 / CareerSession_DataDirectory_RuntimeField2 / CareerSession_DataDirectory_RuntimeField4 in BMH.exe V2.24 +struct DbCounts { + uint32_t clubs = 419; + uint32_t players = 2574; + uint32_t n42 = 168; + uint32_t n66 = 3096; +}; + +// A player as stored in the three parallel u32 tables of the database/savegame +// (named after the globals holding them in the original: *PlayerConditionTechniqueForm, *PlayerSkillWords, *PlayerIdentityWords). +// Player ids are 12 bit (squad lists store id | flags << 12). +// +// w35c bits 0- 6 form (FO) shown in the squad screen +// bits 7-13 technique (TE) +// bits 14-20 condition (KO) +// bits 21-26 unknown (0-63) +// bits 27-31 unknown, read by the code +// w368 bits 0-13 seven skills, 2 bits each (0-3), order: teamplay, speed, shooting, +// passing, tackling, free kick, corner (texts 135-141, "T.S.S.P.Z.F.E.") +// bits 14-26 unknown / runtime state +// bits 27-31 nationality (0 = Germany) +// w364 bits 0- 1 position: 0 goalkeeper, 1 defender, 2 midfielder, 3 forward +// bits 2-20 runtime state (injuries etc., not yet decoded) +// bits 21-25 age - 16 +// bits 26-31 unknown +// +// The values in M3D.MAN differ from a running game: they are varied when a career starts. +struct Player { + std::string name; // ISO 646-DE + uint32_t w35c = 0, w368 = 0, w364 = 0; + + enum Skill { TEAMPLAY, SPEED, SHOOTING, PASSING, TACKLING, FREE_KICK, CORNER }; + + int form() const { return int(w35c & 0x7F); } + int technique() const { return int(w35c >> 7 & 0x7F); } + int condition() const { return int(w35c >> 14 & 0x7F); } + int skill(Skill s) const { return int(w368 >> (2 * s) & 3); } // 0-3 + int nationality() const { return int(w368 >> 27); } // 0 = Germany + int position() const { return int(w364 & 3); } // 0 GK, 1 DEF, 2 MID, 3 FWD + int age() const { return int(w364 >> 21 & 0x1F) + 16; } + + // Strength "STÄ", Strength: form scales the sum of technique and condition. + // display = true gives the 0-99 value shown in the squad screen. + int strength(bool display = true) const { + int raw = ((form() >> 3) + 0x5E) * (technique() + condition()) / 100; + if (!display) return raw; + return raw / 2 > 99 ? 99 : raw / 2; + } +}; + +struct Database { + std::vector club_names; + std::vector referees; + std::vector stadiums; + std::vector players; + Bytes squad_list; // *SquadSlots, u16 entries (& 0xFFF = player id) + // The data as read into memory (CareerFirstSteps2): string pools (0 clubs, 1 players, 2 referees, + // 3 stadiums) and their offset tables (*ClubIdentities clubs, *PlayerNameOffsets players). + Bytes pools[4]; + Bytes raw_club_name_offsets, raw_player_name_offsets; + Bytes raw_player_bonus_values, raw_database_metadata, raw_club_auxiliary_words, raw_club_badge_selectors, raw_foreign_club_strength, raw_league_auxiliary_bytes, raw_referee_properties, raw_club_kit_selectors, raw_club_short_name_offsets; +}; + +Database load_database(const std::filesystem::path& path, const DbCounts& counts = {}); + +} // namespace bmh diff --git a/src/formats/palette.cpp b/src/formats/palette.cpp new file mode 100644 index 0000000..fea6e83 --- /dev/null +++ b/src/formats/palette.cpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/palette.hpp" + +#include "formats/binary.hpp" + +namespace bmh { + +Palette load_palette(const std::filesystem::path& path) { + Bytes b = read_file(path); + if (b.size() < 768) throw FormatError("palette too short: " + path.string()); + Palette p; + for (int i = 0; i < 256; i++) { + auto c = [&](int k) { return uint32_t(vga_dac_rgb8(b[i * 3 + k])); }; + p.argb[i] = 0xFF000000u | c(0) << 16 | c(1) << 8 | c(2); + } + return p; +} + +uint8_t Palette::nearest(uint8_t r, uint8_t g, uint8_t b) const { + int best = 0, best_dist = INT32_MAX; + for (int i = 0; i < 256; i++) { + int dr = int(argb[i] >> 16 & 0xFF) - r, dg = int(argb[i] >> 8 & 0xFF) - g, db = int(argb[i] & 0xFF) - b; + int dist = dr * dr + dg * dg + db * db; + if (dist < best_dist) best = i, best_dist = dist; + } + return uint8_t(best); +} + +} // namespace bmh diff --git a/src/formats/palette.hpp b/src/formats/palette.hpp new file mode 100644 index 0000000..4a9bfee --- /dev/null +++ b/src/formats/palette.hpp @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// M3PC.COL: 256 x RGB, 6 bit per channel (docs/formats/COL.md) +#include +#include +#include + +namespace bmh { + +struct Palette { + std::array argb{}; // 0xAARRGGBB, 8 bit per channel + + // index of the palette entry closest to the given colour + uint8_t nearest(uint8_t r, uint8_t g, uint8_t b) const; +}; + +// Expand the low six VGA-DAC bits to the nearest RGB8 level. Verified against +// the running Original; truncation darkens many colours by one channel step. +constexpr uint8_t vga_dac_rgb8(uint8_t channel) { + return uint8_t(((channel & 0x3f) * 255u + 31u) / 63u); +} + +Palette load_palette(const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/formats/rule_base.cpp b/src/formats/rule_base.cpp new file mode 100644 index 0000000..24d995e --- /dev/null +++ b/src/formats/rule_base.cpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "formats/rule_base.hpp" + +#include +#include + +namespace bmh { + +namespace { + +struct RuleBytes { + uint32_t address; + std::vector bytes; +}; + +// OpenBMH deviates from the original: normalizes live-scene defaults, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit across supported editions. +// Every byte here differs in at least one German edition from supported rule profile 2026-27 and is read by +// the engine as a rule (runtime verification exe_diff over the ten editions, minus texts, calendar, +// season values and screen positions). +const std::vector kRuleBase = { + {::bmh::layout::LiveSceneOptions, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01}}, // live scene options (CareerSession_DispatchLiveTactic_RuntimeField2, RerateTeam) + // (The training camp resorts DeskActions_ConfigureTrainingCampData_RuntimeField.. - qualities and prices - are content, not rules: + // every edition, the English one too, keeps its own resorts; + {::bmh::layout::LeagueStrengthRanges, {0x47, 0x5d, 0x31, 0x47, 0x1c, 0x31, 0x1c, 0x31, 0x0a, 0x1c}}, // league strength ranges (LeagueStrengthRanges) + {::bmh::layout::AdditionalLeagueStrengthRanges, {0x5f, 0x5a, 0x5f, 0x4b, 0x5f}}, // league strength ranges + {::bmh::layout::FinalLeagueStrengthMaximum, {0x5f}}, // league strength ranges + {::bmh::layout::RuleOptionDefaults, {0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x04, 0x02, 0x03, 0x02, 0x03, 0x06, 0x08, 0x06, 0x08, 0x0a, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x1e}}, // option defaults (ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4...) + {::bmh::layout::StadiumPriceTable, {0xa0, 0x25, 0x26, 0x00, 0xa0, 0xf0, 0x19, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0xc8, 0x10, 0x00, 0x60, 0xe3, 0x16, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0xa0, 0xbb, 0x0d, 0x00, 0xb0, 0x71, 0x0b, 0x00, 0x40, 0x77, 0x1b, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x30, 0x57, 0x05, 0x00, 0xc0, 0x27, 0x09, 0x00, 0x70, 0x64, 0x08, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xd0, 0x07, 0xb8, 0x0b, 0xb8, 0x0b, 0x40, 0x1f, 0xa0, 0x0f, 0xb8, 0x0b}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField) + {::bmh::layout::AdditionalStadiumPrices, {0x88, 0x13, 0xc0, 0x12, 0x60, 0x09, 0x40, 0x1f}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField) + {::bmh::layout::StadiumBlockCapacities, {0x12, 0x08, 0x0e, 0x08, 0x12, 0x08, 0x0e}}, // stadium block places (CareerSession_Invalid_RuntimeField) + {::bmh::layout::ComputerBettingLimits, {0x33, 0x20, 0x50, 0x74}}, // computer tip gaps (CareerSession_DispatchLeagueTableControl_RuntimeField) + {::bmh::layout::ForeignPlayerLimitEnabled, {0x00}}, // substitution rule switch (ForeignPlayerLimitEnabled) +}; + +} // namespace + +void apply_rule_base(LeImage& exe) { + // only the German data object has these addresses + if (exe.base() != 0x10000 || !exe.contains(::bmh::layout::GermanDataSegmentBegin) || !exe.contains(::bmh::layout::GermanDataCompatibilityEnd)) return; + for (const RuleBytes& r : kRuleBase) exe.patch(r.address, r.bytes.data(), r.bytes.size()); +} + +} // namespace bmh diff --git a/src/formats/rule_base.hpp b/src/formats/rule_base.hpp new file mode 100644 index 0000000..96c346a --- /dev/null +++ b/src/formats/rule_base.hpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// One engine uses a shared rule profile across supported editions. +// OpenBMH deviates from the original: normalizes live-scene options, league +// strength ranges, option defaults, stadium prices and capacities, betting limits, +// and the foreign-player limit. Texts, currency, calendar, league structure, screen +// positions, season values, and edition-specific resort content stay loaded from data. + +#include "formats/le.hpp" + +namespace bmh { + +// Applies the shared rule profile to compatible German executable images. +// Images without the matching data segment are left unchanged. +void apply_rule_base(LeImage& exe); + +} // namespace bmh diff --git a/src/formats/savestate.cpp b/src/formats/savestate.cpp new file mode 100644 index 0000000..47a0c61 --- /dev/null +++ b/src/formats/savestate.cpp @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "formats/savestate.hpp" + +#include +#include + +namespace bmh { + +namespace { + +// Size of a block, either fixed or derived from a database table size. +enum class Count { None, Clubs, Players, N42, N66, Teams, TeamsPlusCups }; + +struct BlockDef { + uint32_t address; + bool heap; + uint32_t fixed; // fixed part of the size + Count count; // table size multiplied by factor, added to fixed + uint32_t factor; + bool only_if_pointer; // block exists only if the preceding pointer value is non-zero +}; + +// The exact order of NationalCoachAfterLoad. Addresses are the globals in BMH.exe V2.24. +// Sizes marked with a Count depend on the master database: +// Clubs = CareerSession_DataDirectory_RuntimeField (419) Players = CareerSession_DataDirectory_RuntimeField3 (2574) +// N42 = CareerSession_DataDirectory_RuntimeField2 (168) N66 = CareerSession_DataDirectory_RuntimeField4 (3096) +// Teams = CareerSession_DispatchLineup_RuntimeField (138, teams in league play) +// TeamsPlusCups = CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (138 + 30) +constexpr BlockDef kBlocks[] = { + {::bmh::layout::Cup_AdvanceCup_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::LiveMatchday_FormatError_RuntimeField14, false, 6, Count::None, 0, false}, + {::bmh::layout::ManagerRecords, false, 0x373c, Count::None, 0, false}, // 5 manager records of 0xB0C bytes + {::bmh::layout::Loans, false, 0x1e0, Count::None, 0, false}, + {::bmh::layout::ManagerMatchHistory, false, 0x20d0, Count::None, 0, false}, // form history: 5 managers x 168 teams x 10 + {::bmh::layout::MatchdayGroupDescriptors, false, 0x4e0, Count::None, 0, false}, {::bmh::layout::ManagerAutomation, false, 0x14, Count::None, 0, false}, + {::bmh::layout::Desktops, false, 0x10e0, Count::None, 0, false}, // desktop layouts (.MEN), 5 x 0x360 + {::bmh::layout::CareerSession_DispatchToto_RuntimeField, false, 1, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField4, false, 1, Count::None, 0, false}, + {::bmh::layout::CalendarState_FormatError_RuntimeField3, false, 2, Count::None, 0, false}, {::bmh::layout::ActiveManager, false, 1, Count::None, 0, false}, // active manager + {::bmh::layout::CareerSession_RuntimeError_RuntimeField4, false, 1, Count::None, 0, false}, + {::bmh::layout::LeaguePresentationOptions, false, 0xb4, Count::None, 0, false}, // button settings (.EIN) + {::bmh::layout::FriendlyTeams, false, 0x78, Count::None, 0, false}, {::bmh::layout::FriendlyDays, false, 0x3c, Count::None, 0, false}, + {::bmh::layout::Cup_AdvanceCup_ExecutableField, false, 0x50, Count::None, 0, false}, {::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField, false, 0x50, Count::None, 0, false}, + {::bmh::layout::Placements, false, 0x50, Count::None, 0, false}, {::bmh::layout::ActiveSelectors, false, 8, Count::None, 0, false}, + {::bmh::layout::Career_CareerAddManager_RuntimeField2, false, 0x90, Count::None, 0, false}, {::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField, false, 0x2c, Count::None, 0, false}, + {::bmh::layout::NextDeskManager, false, 8, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField8, false, 10, Count::None, 0, false}, + {::bmh::layout::DeskPosition, false, 1, Count::None, 0, false}, {::bmh::layout::DeskRecords_Teams_RuntimeField, false, 0x114, Count::None, 0, false}, + {::bmh::layout::CareerSession_FormatError_RuntimeField7, false, 2, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField6, false, 6, Count::None, 0, false}, + {::bmh::layout::CurrentMatchday, false, 4, Count::None, 0, false}, // seed of the game RNG (GameRandom) + {::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::CoachActive, false, 1, Count::None, 0, false}, + {::bmh::layout::OriginalManagerCount, false, 1, Count::None, 0, false}, {::bmh::layout::CareerSession_Invalid_RuntimeField2, false, 4, Count::None, 0, false}, // saved RNG seed + {::bmh::layout::CareerDuration, false, 1, Count::None, 0, false}, {::bmh::layout::GameMode, false, 1, Count::None, 0, false}, + {::bmh::layout::CompetitionSelection, false, 4, Count::None, 0, false}, {::bmh::layout::ManagerCount, false, 1, Count::None, 0, false}, // number of managers + {::bmh::layout::SavedCompetition, false, 4, Count::None, 0, false}, {::bmh::layout::Difficulty, false, 1, Count::None, 0, false}, + {::bmh::layout::StockExchange, false, 0x450, Count::None, 0, false}, {::bmh::layout::FundBlock, false, 0xa8, Count::None, 0, false}, + {::bmh::layout::Coupon, false, 100, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField2, false, 3, Count::None, 0, false}, + {::bmh::layout::Savestate_Layout_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::AdGroupId, false, 1, Count::None, 0, false}, + {::bmh::layout::OfferSlots, false, 0x10, Count::None, 0, false}, {::bmh::layout::ForeignClubStrength, false, 0xfb, Count::None, 0, false}, + {::bmh::layout::Career_Put_ExecutableField3, false, 0xbd, Count::None, 0, false}, {::bmh::layout::ClubShortNameOffsets, false, 0xa8, Count::None, 0, false}, + {::bmh::layout::ClubKitSelectors, false, 0x1a3, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField7, false, 0x18, Count::None, 0, false}, + {::bmh::layout::ClubInfo_FormatError_RuntimeField, false, 0x420, Count::None, 0, false}, {::bmh::layout::Career_CareerManagersEnd_RuntimeField, false, 0x18, Count::None, 0, false}, + {::bmh::layout::ClubInfo_FormatError_RuntimeField2, false, 0xc, Count::None, 0, false}, {::bmh::layout::DeskActions_Unsupported_RuntimeField, false, 4, Count::None, 0, false}, + {::bmh::layout::Career_RemoveJoinLoans_RuntimeField, false, 800, Count::None, 0, false}, {::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField, false, 200, Count::None, 0, false}, + {::bmh::layout::ManagerRatings, false, 0xf0, Count::None, 0, false}, {::bmh::layout::DaysIntoSeason, false, 2, Count::None, 0, false}, // day since 1 July + {::bmh::layout::Career_CompetitionPointers_ExecutableField, false, 0x7e, Count::None, 0, false}, {::bmh::layout::Field, false, 0x100, Count::None, 0, false}, + {::bmh::layout::CalendarDay, false, 4, Count::None, 0, false}, {::bmh::layout::SeasonIndex, false, 2, Count::None, 0, false}, + {::bmh::layout::Savestate_Layout_ExecutableField5, false, 2, Count::None, 0, false}, {::bmh::layout::CompetitionCalendar, false, 0x2dc, Count::None, 0, false}, // calendar, u16/day + {::bmh::layout::Postponed, false, 0xf0, Count::None, 0, false}, {::bmh::layout::LeagueTableDisplayModes, false, 8, Count::None, 0, false}, + {::bmh::layout::CareerSession_FormatError_ExecutableField, false, 8, Count::None, 0, false}, {::bmh::layout::ManagerSettings, false, 8, Count::None, 0, false}, + {::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField, false, 4, Count::None, 0, false}, {::bmh::layout::CareerSession_AnyOf_ExecutableField, false, 8, Count::None, 0, false}, + {::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2, false, 4, Count::None, 0, false}, {::bmh::layout::ManagerMailbox, true, 0x1900, Count::None, 0, false}, + {::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField, false, 4, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField3, false, 8, Count::None, 0, false}, + {::bmh::layout::Flags, false, 0xc, Count::None, 0, false}, {::bmh::layout::Formations, false, 0x580, Count::None, 0, false}, // M3.DAT + {::bmh::layout::PlayerDevelopmentBalance, false, 4, Count::None, 0, false}, {::bmh::layout::PlayerBonuses, true, 0x36, Count::N66, 1, false}, + {::bmh::layout::EditorList, false, 0xf20, Count::None, 0, false}, {::bmh::layout::Field0, false, 0x70, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13, false, 0x68, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, false, 0x100, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22, false, 0x80, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23, false, 0x80, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, false, 0x80, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26, false, 0x40, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21, false, 0x40, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, false, 0x6c, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17, false, 0x9a, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField4, false, 0x62, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, false, 4, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, false, 2, Count::None, 0, false}, + {::bmh::layout::Teams, false, 0x20, Count::None, 0, false}, {::bmh::layout::MatchdayGroupWorkspace, false, 0x20, Count::None, 0, false}, + {::bmh::layout::Savestate_Layout_ExecutableField6, false, 1, Count::None, 0, false}, {::bmh::layout::EventPasses, false, 1, Count::None, 0, false}, + {::bmh::layout::LeagueResults, false, 0xd5c, Count::None, 0, false}, // match results, see game/schedule.hpp + {::bmh::layout::LeagueRoundCounters, false, 9, Count::None, 0, false}, + {::bmh::layout::TeamMorale, true, 0, Count::Clubs, 1, false}, {::bmh::layout::ClubBadgeSelectors, true, 0, Count::Clubs, 2, false}, + {::bmh::layout::TeamFlags, true, 0, Count::Clubs, 2, false}, {::bmh::layout::ClubIdentities, true, 0, Count::Clubs, 2, false}, // club name offsets + {::bmh::layout::PlayerNameOffsets, true, 0, Count::Players, 2, false}, // player name offsets + {::bmh::layout::MasterDatabaseMetadata, true, 100, Count::None, 0, false}, {::bmh::layout::ClubAuxiliaryWords, true, 0, Count::N42, 2, false}, + {::bmh::layout::LeagueRankHistory, true, 0, Count::Teams, 0x1a, false}, // table position history, 26 bytes per team + {::bmh::layout::Titles, false, 0x384, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField6, false, 6, Count::None, 0, false}, + {::bmh::layout::ClubAuxiliaryBytes, true, 0, Count::TeamsPlusCups, 1, false}, + {::bmh::layout::CupTable, false, 0x5a0, Count::None, 0, false}, {::bmh::layout::SquadSlots, true, 0x6c, Count::N66, 2, false}, // squad lists + {::bmh::layout::PlayerConditionTechniqueForm, true, 0, Count::Players, 4, false}, // player word 1: form, technique, condition + {::bmh::layout::PlayerCards, true, 0, Count::Players, 2, false}, + {::bmh::layout::PlayerSkillWords, true, 0, Count::Players, 4, false}, // player word 2: skills, nationality + {::bmh::layout::PlayerIdentityWords, true, 0, Count::Players, 4, false}, // player word 3: position, age + {::bmh::layout::TacticsBoards, false, 0x2940, Count::None, 0, false}, {::bmh::layout::TournamentName, true, 0x24, Count::None, 0, false}, + {::bmh::layout::Career_EuropeanClub_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::Career_EuropeanClub_ExecutableField2, false, 1, Count::None, 0, false}, + {::bmh::layout::Career_EuropeanClub_ExecutableField3, false, 1, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24, false, 0x28, Count::None, 0, false}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29, false, 0x14, Count::None, 0, false}, {::bmh::layout::ClubSeasonRecords, false, 4, Count::None, 0, false}, + {::bmh::layout::ClubSeasonRecords, true, 0x3090, Count::None, 0, true}, // club records (168 x 74), only if pointer != 0 +}; + +} // namespace + +SaveState::SaveState(const Bytes& stream, const DbCounts& c) : stream_(stream) { + // Teams in league play and cup-only teams are not part of DbCounts yet; + // these are the V2.24 values (CareerSession_DispatchLineup_RuntimeField, CareerSession_InstallLeagueSizes_RuntimeField6). + constexpr uint32_t kTeams = 138, kCupTeams = 30; + size_t pos = 0; + uint32_t last_pointer = 0; + for (const BlockDef& d : kBlocks) { + if (d.only_if_pointer && last_pointer == 0) continue; + uint32_t n = 0; + switch (d.count) { + case Count::None: n = 0; break; + case Count::Clubs: n = c.clubs; break; + case Count::Players: n = c.players; break; + case Count::N42: n = c.n42; break; + case Count::N66: n = c.n66; break; + case Count::Teams: n = kTeams; break; + case Count::TeamsPlusCups: n = kTeams + kCupTeams; break; + } + size_t size = d.fixed + size_t(n) * d.factor; + if (pos + size > stream.size()) throw FormatError("savegame: state blocks exceed stream"); + if (d.address == ::bmh::layout::ClubSeasonRecords && !d.heap) last_pointer = le32(stream, pos); + index_.try_emplace(d.address, blocks_.size()); + blocks_.push_back({d.address, d.heap, pos, size}); + pos += size; + } + // trailer: 4 string pools, each u16 length + data + for (int i = 0; i < 4; i++) { + if (pos + 2 > stream.size()) throw FormatError("savegame: trailer missing"); + size_t len = le16(stream, pos); + if (pos + 2 + len > stream.size()) throw FormatError("savegame: trailer exceeds stream"); + pools_.emplace_back(stream.begin() + pos + 2, stream.begin() + pos + 2 + len); + pos += 2 + len; + } + if (pos < stream.size()) { + // the OpenBMH extension (savestate.hpp) + static const char kMagic[8] = {0x4f, 0x42, 0x4d, 0x48, 0x45, 0x58, 0x54, 0x31}; // "OBMHEXT1" + if (stream.size() - pos < 10 || !std::equal(kMagic, kMagic + 8, stream.begin() + long(pos))) + throw FormatError("savegame: block sizes do not match stream length"); + size_t count = le16(stream, pos + 8); + pos += 10; + for (size_t i = 0; i < count; ++i) { + if (pos + 8 > stream.size()) throw FormatError("savegame: extension cut off"); + const uint32_t address = le32(stream, pos), size = le32(stream, pos + 4); + pos += 8; + if (pos + size > stream.size()) throw FormatError("savegame: extension block exceeds stream"); + extension_.push_back({address, Bytes(stream.begin() + long(pos), stream.begin() + long(pos + size))}); + pos += size; + } + } + if (pos != stream.size()) throw FormatError("savegame: block sizes do not match stream length"); +} + +void append_save_extension(Bytes& stream, const std::vector& blocks) { + if (blocks.empty()) return; + for (char ch : std::string("OBMHEXT1")) stream.push_back(uint8_t(ch)); + stream.push_back(uint8_t(blocks.size())), stream.push_back(uint8_t(blocks.size() >> 8)); + for (const auto& b : blocks) { + for (uint32_t v : {b.address, uint32_t(b.bytes.size())}) + for (int k = 0; k < 4; ++k) stream.push_back(uint8_t(v >> (8 * k))); + stream.insert(stream.end(), b.bytes.begin(), b.bytes.end()); + } +} + +const SaveBlock& SaveState::block(uint32_t address) const { + auto it = index_.find(address); + if (it == index_.end()) throw FormatError("savegame: unknown block"); + return blocks_[it->second]; +} + +} // namespace bmh + +namespace bmh { + +std::vector save_layout(const DbCounts& c, bool club_records) { + constexpr uint32_t kTeams = 138, kCupTeams = 30; + std::vector out; + size_t pos = 0; + for (const BlockDef& d : kBlocks) { + if (d.only_if_pointer && !club_records) continue; + uint32_t n = 0; + switch (d.count) { + case Count::None: n = 0; break; + case Count::Clubs: n = c.clubs; break; + case Count::Players: n = c.players; break; + case Count::N42: n = c.n42; break; + case Count::N66: n = c.n66; break; + case Count::Teams: n = kTeams; break; + case Count::TeamsPlusCups: n = kTeams + kCupTeams; break; + } + const size_t size = d.fixed + size_t(n) * d.factor; + out.push_back({d.address, d.heap, pos, size}); + pos += size; + } + return out; +} + +} // namespace bmh diff --git a/src/formats/savestate.hpp b/src/formats/savestate.hpp new file mode 100644 index 0000000..01c7db0 --- /dev/null +++ b/src/formats/savestate.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Structured view of the decrypted savegame stream. +// +// The original writes its whole game state by dumping global variables one after +// another (NationalCoachAfterLoad, 125 calls of the stream writer FbmDecrypt). There are no +// headers or tags: the position of every block follows only from the fixed order and +// the size of the preceding blocks. This file reproduces that order so a block can be +// looked up by the address of the global it was dumped from, e.g. block(LeagueResults) for +// the match results. +// +// Block sizes are either constants or depend on table sizes of the master database +// (DbCounts). Blocks that were heap allocations in the original ("*PlayerConditionTechniqueForm") store the +// pointed-to data, not the pointer. +// +// After the state blocks follow four trailer blocks, each a u16 length plus data. They +// are the string pools of the master database (club names, player names, referees, +// stadiums), saved so that renamed clubs/players survive. + +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "formats/m3d.hpp" + +namespace bmh { + +struct SaveBlock { + uint32_t address = 0; // address of the global variable in BMH.exe V2.24 (for reference) + bool heap = false; // true if the global was a pointer to heap data + size_t offset = 0; // byte offset inside the decrypted stream + size_t size = 0; +}; + +// The blocks of a savegame in the order NationalCoachAfterLoad writes them (offsets counted from 0). +// The heap copy of the club records (ClubSeasonRecords) is present only if `club_records` is set. +std::vector save_layout(const DbCounts& counts = {}, bool club_records = true); + +class SaveState { +public: + // Splits a decrypted stream (Savegame::stream). Throws FormatError if the block + // sizes do not add up exactly to the stream length. + SaveState(const Bytes& stream, const DbCounts& counts = {}); + + const std::vector& blocks() const { return blocks_; } + // First block dumped from the given global (some globals are dumped twice). + const SaveBlock& block(uint32_t address) const; + // Raw bytes of a block; valid as long as the stream passed to the constructor lives. + const uint8_t* data(uint32_t address) const { return stream_.data() + block(address).offset; } + const Bytes& stream() const { return stream_; } + + // The four string pools from the trailer (0 = club names, 1 = player names, + // 2 = referees, 3 = stadiums), same layout as in M3D.MAN. + const Bytes& pool(int index) const { return pools_.at(index); } + + // OpenBMH extension behind the trailer (only in OpenBMH saves of games that need it, such + // as the English cup memory): "OBMHEXT1", u16 count, then per block u32 address, + // u32 size, the bytes. Original saves have none. + struct ExtensionBlock { + uint32_t address; + Bytes bytes; + }; + const std::vector& extension() const { return extension_; } + +private: + const Bytes& stream_; + std::vector blocks_; + std::map index_; + std::vector pools_; + std::vector extension_; +}; + +// Appends the OpenBMH extension (SaveState::extension) to a save stream. +void append_save_extension(Bytes& stream, const std::vector& blocks); + +} // namespace bmh diff --git a/src/formats/textd.cpp b/src/formats/textd.cpp new file mode 100644 index 0000000..3362c7f --- /dev/null +++ b/src/formats/textd.cpp @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/textd.hpp" + +#include "formats/binary.hpp" + +namespace bmh { + +TextDb load_textd(const std::filesystem::path& path) { + Bytes d = read_file(path); + if (d.size() < 7) throw FormatError("TEXTD: file too short"); + // header: u8 id, u16 buffer size, u32 unknown; the buffer may be larger than the file rest + TextDb db; + size_t p = 7; + db.blob.assign(d.begin() + 7, d.end()); + while (db.strings.size() < TEXT_COUNT && p < d.size()) { + size_t start = p; + db.offsets.push_back(start - 7); + while (p < d.size() && d[p] != 0) p++; + db.strings.emplace_back(reinterpret_cast(d.data() + start), p - start); + p++; + } + if (db.strings.size() != TEXT_COUNT) throw FormatError("TEXTD: expected 1382 strings"); + return db; +} + +} // namespace bmh diff --git a/src/formats/textd.hpp b/src/formats/textd.hpp new file mode 100644 index 0000000..acc6793 --- /dev/null +++ b/src/formats/textd.hpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// TEXTD.BLK: UI strings (docs/formats/TEXTD.md), loaded in CareerFirstSteps2 +#include +#include +#include + +namespace bmh { + +constexpr size_t TEXT_COUNT = 0x566; // pointer table TextPointerTable[1382] + +struct TextDb { + std::vector strings; // raw ISO 646-DE, index = text id + // The texts as the original keeps them in memory: one block, NUL separated. Some + // routines copy a fixed number of bytes from a text and so also take the following + // ones (see raw()). + std::vector blob; + std::vector offsets; + std::vector raw(size_t id, size_t n) const { + std::vector r(n, 0); + for (size_t i = 0; i < n && offsets.at(id) + i < blob.size(); i++) r[i] = blob[offsets.at(id) + i]; + return r; + } + const std::string& operator[](size_t id) const { return strings.at(id); } +}; + +TextDb load_textd(const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/formats/vga.cpp b/src/formats/vga.cpp new file mode 100644 index 0000000..71ee2bd --- /dev/null +++ b/src/formats/vga.cpp @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/vga.hpp" + +namespace bmh { + +void Image::blit(const Image& src, int x, int y) { + for (int sy = 0; sy < src.height; sy++) { + int dy = y + sy; + if (dy < 0 || dy >= height) continue; + for (int sx = 0; sx < src.width; sx++) { + int dx = x + sx; + if (dx >= 0 && dx < width) at(dx, dy) = src.pixels[size_t(sy) * src.width + sx]; + } + } +} + +Image decode_vga(const Bytes& d) { + if (d.size() < 8) throw FormatError("VGA: file too short"); + Image img(le16(d, 0), le16(d, 2)); + size_t end = 8 + size_t(le32(d, 4)); + if (end > d.size()) throw FormatError("VGA: length field exceeds file"); + + size_t si = 8, di = 0, n = img.pixels.size(); + while (di < n) { + if (si >= end) throw FormatError("VGA: RLE data ends early"); + uint8_t c = d[si++]; + if (c >= 0x80) { // run: next byte repeated c - 0x7F times + if (si >= end) throw FormatError("VGA: truncated run"); + uint8_t v = d[si++]; + for (int k = 0; k < c - 0x7F && di < n; k++) img.pixels[di++] = v; + } else { // literal: c + 1 bytes + for (int k = 0; k <= c && di < n; k++) { + if (si >= end) throw FormatError("VGA: truncated literal"); + img.pixels[di++] = d[si++]; + } + } + } + // exactly one trailing byte follows the pixel data in every original file + if (si + 1 != end) throw FormatError("VGA: unexpected data after image"); + return img; +} + +Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); } + +} // namespace bmh diff --git a/src/formats/vga.hpp b/src/formats/vga.hpp new file mode 100644 index 0000000..89a1034 --- /dev/null +++ b/src/formats/vga.hpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// .VGA images: u16 width, u16 height, u32 length, RLE data (docs/formats/VGA.md) +#include +#include +#include + +#include "formats/binary.hpp" + +namespace bmh { + +// 8-bit indexed image, row-major +struct Image { + int width = 0; + int height = 0; + std::vector pixels; + + Image() = default; + Image(int w, int h, uint8_t fill = 0) : width(w), height(h), pixels(size_t(w) * h, fill) {} + uint8_t& at(int x, int y) { return pixels[size_t(y) * width + x]; } + void blit(const Image& src, int x, int y); +}; + +Image decode_vga(const Bytes& data); +Image load_vga(const std::filesystem::path& path); + +} // namespace bmh diff --git a/src/game/balance_plan.cpp b/src/game/balance_plan.cpp new file mode 100644 index 0000000..4475179 --- /dev/null +++ b/src/game/balance_plan.cpp @@ -0,0 +1,371 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/balance_plan.hpp" + +#include +#include + +#include "game/prediction.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "game/week.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecordSize = 0xb0c; +constexpr uint32_t kPlanTicketPrice = ::bmh::layout::PlanTicketPrice; // one byte per manager +// BalancePlanRuntimeField: months left in the business year by calendar month (July: 12, June: 1) +constexpr int8_t kMonthsLeft[13] = {0, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7}; +// BalancePlanRuntimeField2: which rows can be changed; BalancePlanRuntimeField3: the class of the maximum +// (BalancePlanRuntimeField4: 30 million, 25, 100000, 2 million) +constexpr uint8_t kEditable[0x16] = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1}; +constexpr uint8_t kMaximumClass[0x16] = {0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 1, 2, 1}; +constexpr int32_t kMaximum[4] = {30000000, 25, 100000, 2000000}; +// BalancePlanRuntimeField5: monthly running costs of the stadium facilities (BMHExeXa) +constexpr uint16_t kFacilityCost[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; +// BalancePlanRuntimeField6: monthly income of the first six facilities (FacilityIncome) +constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000}; +// BalancePlanRuntimeField7: catering income per visitor of the facilities 0-13 (BookMoney) +constexpr uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2}; +// Rec32: price units of the six funds (BMH.exe+MonthRuntimeField10) +constexpr int32_t kShareUnits[6] = {15, 18, 21, 24, 27, 30}; + +int32_t rec32(const GameState& g, int m, size_t o) { + const size_t at = size_t(m) * kRecordSize + o; + const auto& r = g.manager_records; + return int32_t(uint32_t(r.at(at)) | uint32_t(r.at(at + 1)) << 8 | uint32_t(r.at(at + 2)) << 16 | uint32_t(r.at(at + 3)) << 24); +} +void set_rec32(GameState& g, int m, size_t o, int32_t v) { + for (int i = 0; i < 4; i++) g.manager_records.at(size_t(m) * kRecordSize + o + size_t(i)) = uint8_t(uint32_t(v) >> (8 * i)); +} +uint8_t rec8(const GameState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * kRecordSize + o); } +int32_t mem32(const GameState& g, uint32_t a) { return g.memory.has(a + 3) ? int32_t(g.memory.u32(a)) : 0; } +int32_t wrap(int64_t v) { return int32_t(uint32_t(uint64_t(v))); } + +// Add32: the level of a facility (facility 0: its size step) +uint32_t facility_level(const GameState& g, int m, int k) { + const uint8_t v = rec8(g, m, size_t(k)); + return k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xff : 1; +} + +// DailyInterest2(0): the interest of one day without booking it - negative is income +// (balance 1 %, fixed deposit 2 % a year), positive an expense (overdraft 12 %, beyond the +// credit line 18 %). The divisor is -36500. +int32_t daily_interest_preview(const GameState& g, int m) { + constexpr int32_t kAnnual = -0x8e94; + const int32_t balance = rec32(g, m, 0x314), deposit = rec32(g, m, 0x318), credit = rec32(g, m, 0x31c); + int32_t result = 0; + if (balance < 0) { + const int32_t with_credit = wrap(int64_t(balance) + credit); + if (with_credit < 0) result = wrap(int64_t(with_credit) * 0x12) / kAnnual; + int32_t below = wrap(-int64_t(credit)); + if (below < balance) below = balance; + result = wrap(int64_t(result) + wrap(int64_t(below) * 0xc) / kAnnual); + } else { + result = balance / kAnnual; + } + return wrap(int64_t(result) + wrap(int64_t(deposit / 10000) * 20000) / kAnnual); +} + +// SharesAndLoans(manager, flags, months): flags 1 the dividends of the manager's funds and +// the loans he gave to other managers (income), 2 the loans he took (expense, negative); +// flag 4 multiplies by the months (loans: at most their remaining months). +int32_t shares_and_loans(const GameState& g, int m, int flags, int months) { + int32_t sum = 0; + if (flags & 1) { + for (int k = 0; k < 6; k++) { + const uint32_t unit = g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareUnits[k]) / 10000; + sum = wrap(int64_t(sum) + int64_t(unit * g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c))); + } + if (flags & 4) sum = wrap(int64_t(sum) * months); + } + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + for (int c = 0; c <= managers; c++) { + uint32_t row = uint32_t(c) * 0x18 + uint32_t(m) * 0x78; + int32_t amount = mem32(g, ::bmh::layout::Loans + row + 8); + if (amount != 0 && (flags & 2)) { + if (!(flags & 4)) { + sum = wrap(int64_t(sum) - amount); + } else { + int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10)); + sum = wrap(int64_t(sum) - int64_t(std::min(left, months)) * amount); + } + } + if (c == 0) continue; + row = uint32_t(m + 1) * 0x18 + uint32_t(c - 1) * 0x78; + amount = mem32(g, ::bmh::layout::Loans + row + 8); + if (amount != 0 && (flags & 1)) { + if (!(flags & 4)) { + sum = wrap(int64_t(sum) + amount); + } else { + int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10)); + sum = wrap(int64_t(sum) + int64_t(std::min(left, months)) * amount); + } + } + } + return sum; +} + +// MonthlyPay(manager, 0xb): a month of the squad's pay - bonus base (+0x4e), salary +// (+0x50) and the bonus each player can expect (ContractOffer with the fitness correction) +// for the predicted final rank (Void5 mode 4). Changes scratch tables: `g` is a copy. +int32_t monthly_pay(GameState& g, int m, uint8_t flags = 0xb) { + const int team = g.manager_teams.at(size_t(m)); + std::array buf{}; + const int predicted = table_prediction(g, team, 4, buf); + const int rank = predicted == 0 ? 0xb : predicted + 1; + const SquadRange range = squad_range(team); + int32_t sum = 0; + for (int s = 0; s < 0x18; s++) { + const size_t slot = size_t(m) * 0x840 + size_t(s) * 0x58; + if (g.tactics.at(slot + 0x3d) == 0xff) continue; + const int32_t bonus = int32_t((g.tactics.at(slot + 0x4e) | g.tactics.at(slot + 0x4f) << 8) & 0x7fff); + const int32_t salary = int32_t(uint32_t(g.tactics.at(slot + 0x50)) | uint32_t(g.tactics.at(slot + 0x51)) << 8 | + uint32_t(g.tactics.at(slot + 0x52)) << 16 | uint32_t(g.tactics.at(slot + 0x53)) << 24); + // a board row whose squad slot is empty (0xfff) makes the original read a player + // beyond the table; the port counts no expected bonus for it + const size_t player = g.squad_slots.at(range.first + size_t(s)) & 0xfff; + const int32_t expected = (flags & 1) && player < g.players.size() ? int32_t(expected_bonus(g, m, rank, s, int(player), true)) : 0; + sum = wrap(int64_t(sum) + ((flags & 2) ? salary : 0) + + ((flags & 1) ? expected : 0) + ((flags & 8) ? bonus : 0)); + } + return sum; +} + +// BMHExeXa: the facilities' monthly running costs +int32_t facility_costs(const GameState& g, int m) { + int32_t sum = 0; + for (int i = 0; i < 0xe; i++) sum += kFacilityCost[i]; + for (int i = 0xe; i < 0x16; i++) sum += (rec8(g, m, 0x2e + size_t(i)) & 7) * kFacilityCost[i]; + return sum; +} + +// FacilityIncome: the facilities' monthly income +int32_t facility_income(const GameState& g, int m) { + int32_t sum = 0; + for (int k = 0; k < 6; k++) + if (rec8(g, m, size_t(k)) != 0) sum += int32_t(facility_level(g, m, k)) * kFacilityIncome[k]; + return sum; +} + +// BookMoney(manager, gate, 1): kiosks and restaurants of one home game, without the +// random factor +uint32_t catering_per_game(const GameState& g, int m, int32_t gate) { + uint32_t sum = 0; + for (int k = 0; k < 14; k++) + if (rec8(g, m, size_t(k)) != 0) sum += kPerVisitor[k] * uint32_t(gate) * facility_level(g, m, k) / 100; + return sum; +} + +// OpenBMH deviates from the original: omits the discontinued youth-group cost categories and uses league-specific youth-academy limits. +// TeamLeague3 (supported rule profile patch): the youth academy limit of the league +int32_t youth_limit(const GameState& g, int m) { + const int league = team_league(g.manager_teams.at(size_t(m))); + return league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000; +} + +// The redraw of BalanceFromGame2 (with its continuation Redraw and the patch at +// Redraw2): recomputes the items if `refresh` asks for it, then the spectator income +// and the totals. +void redraw(const GameState& source, BalancePlanDraft& d) { + const int m = d.manager; + const int view = int(d.view); + auto& r = d.rows; + r[3] = view < 2 ? rec32(source, m, 0x868) : 0; + int32_t home = r[kBalanceLeagueHomeGames] + r[kBalanceOtherHomeGames]; // local_48 + if (view == 0) home = 0; + if (view < 2) { + const int month = month_code(source.date); + d.months_left = month >= 1 && month <= 12 ? kMonthsLeft[month] : 0; + d.days_left = 0x16d - source.season_day(); + const bool first_of_month = source.date == 0 || month_code(source.date - 1) != month; + if (source.season_day() != 0 && month == 7 && first_of_month) d.months_left = d.days_left = 0; + home -= int8_t(rec8(source, m, 0x28c)) + int8_t(rec8(source, m, 0x28d)) + int8_t(rec8(source, m, 0x28e)); + if (home < 0) home = 0; + } else { + d.months_left = 12; + d.days_left = 0x16d; + } + const int months = int8_t(d.months_left); + if (d.refresh != 0) { + if (view < 2) { + for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = rec32(source, m, 0x85c + size_t(i) * 4); + r[7] = wrap(int64_t(rec32(source, m, 0x33c)) + rec32(source, m, 0x334) + rec32(source, m, 0x338)); + } else { + std::fill(r.begin(), r.begin() + kBalanceItems, 0); + } + if (view != 0 && months != 0) + for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = wrap(int64_t(r[size_t(i)]) + d.adjustments[size_t(i)] * 12 / months); + if (d.refresh != 2) r[kBalanceAverageGate] = r[kBalanceGateSoFar]; + if (view != 0) { + GameState g = source; // scratch copy, see the header + const int32_t interest = wrap(int64_t(int16_t(d.days_left)) * daily_interest_preview(g, m)); + if (interest < 1) r[5] = wrap(int64_t(r[5]) - interest); + else r[0x10] = wrap(int64_t(r[0x10]) + interest); + r[5] = wrap(int64_t(r[5]) + shares_and_loans(g, m, 5, months)); + r[0x10] = wrap(int64_t(r[0x10]) - shares_and_loans(g, m, 6, months)); + // advertising: shirt (+0xadc) and TV (+0xae8) contracts, the 14 boards (+0xa34); + // free boards are expected to bring 80 % of the average board + r[0] = wrap(int64_t(r[0]) + int64_t(rec32(g, m, 0xadc)) * months); + r[2] = wrap(int64_t(r[2]) + int64_t(months) * rec32(g, m, 0xae8)); + int boards = 0; + for (int s = 0; s < 0xe; s++) { + const int32_t v = rec32(g, m, 0xa34 + size_t(s) * 0xc); + if (v != 0) boards++; + r[1] = wrap(int64_t(r[1]) + int64_t(v) * months); + } + if (g.memory.u8(::bmh::layout::GameMode) == 1 || (g.memory.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0)) boards = 0xe; + if (boards != 0 && boards < 0xe) { + int32_t missing = (r[1] / boards) * (0xe - boards); + if (months != 0) missing /= months; + r[1] = wrap(int64_t(r[1]) + int64_t(months) * ((int64_t(missing) * 0x50) / 100)); + } + r[7] = wrap(int64_t(r[7]) + int64_t(monthly_pay(g, m)) * months); + r[8] = wrap(int64_t(r[8]) + int64_t(facility_costs(g, m)) * months); + r[4] = wrap(int64_t(r[4]) + int64_t(facility_income(g, m)) * months); + const uint32_t catering = catering_per_game(g, m, r[kBalanceAverageGate]); + r[4] = wrap(int64_t(r[4]) + int64_t((catering * uint32_t(home)) / 12) * months); + // running costs Spending: the patch counts only the youth academy (index 1), + // with the whole league limit while +0x880 is below it + const uint32_t costs = ::bmh::layout::Spending + uint32_t(m) * 0x24; + if (mem32(g, costs + 4) != 0 && int64_t(months) * mem32(g, costs + 4) != 0) { + const int32_t limit = youth_limit(g, m); + if (uint32_t(rec32(g, m, 0x880)) < uint32_t(limit)) r[9] = wrap(int64_t(r[9]) + limit); + } + for (int k = 0; k < 3; k++) r[size_t(10 + k)] = wrap(int64_t(r[size_t(10 + k)]) + int64_t(months) * mem32(g, costs + 0xc + uint32_t(k) * 4)); + for (int k = 0; k < 2; k++) r[size_t(14 + k)] = wrap(int64_t(r[size_t(14 + k)]) + int64_t(months) * rec32(g, m, 0x854 + size_t(k) * 4)); + } + d.refresh = 0; + } + // the view "real" leaves out the season tickets of the remaining league home games + int32_t season_tickets = 0; + if (view == 1) { + int32_t sold = int32_t(uint16_t(rec8(source, m, 0x2ac) | rec8(source, m, 0x2ad) << 8)); + if (r[kBalanceAverageGate] < sold) sold = r[kBalanceAverageGate]; + int32_t games = r[kBalanceLeagueHomeGames] - int8_t(rec8(source, m, 0x28c)); + if (games < 0) games = 0; + season_tickets = wrap(int64_t((sold * 0x46) / 100) * r[kBalanceTicketPrice] * games); + } + r[3] = wrap(int64_t(r[3]) + (int64_t(home) * r[kBalanceTicketPrice] * r[kBalanceAverageGate] - season_tickets)); + double total = 0; + for (int i = 0; i < kBalanceItems; i++) { + if (r[size_t(i)] < 0) r[size_t(i)] = 0; + total += double(r[size_t(i)]) * (i < 7 ? 1 : -1); + } + d.depreciation = view < 2 ? rec32(source, m, 0x30c) : 0; + d.total = total - double(d.depreciation); +} + +} // namespace + +// StadiumRequiredAttendance: Source's monthly preview differs from booked month_change totals. +// Prediction may touch scratch tables; both pay previews run on an owned copy. +int32_t stadium_required_attendance(const GameState& source, int manager) { + if (manager < 0 || manager > 4) throw FormatError("stadium attendance: invalid manager"); + GameState g = source; + const int team = g.manager_teams.at(size_t(manager)); + const int league = team > 0x164 ? 0 : team_league(team); + if (league < 0 || league >= kLeagueCount) + throw FormatError("stadium attendance: manager has no Source league"); + const int home_games = league_matchdays(league) / 2; + if (home_games <= 0) throw FormatError("stadium attendance: invalid Source league home count"); + const int m = manager; + int32_t costs = wrap(int64_t(facility_costs(g, m)) + rec32(g, m, 0x854) + rec32(g, m, 0x858)); + costs = wrap(int64_t(costs) + monthly_pay(g, m, 0xa)); + for (int k = 0; k < 6; ++k) { + int32_t value = mem32(g, ::bmh::layout::Spending + uint32_t(m) * 0x24 + uint32_t(k) * 4); + if (k == 0 || k == 2) value = 0; // OpenBMH deviates from the original: omits the discontinued youth-group cost categories and uses league-specific youth-academy limits. +// supported rule profile MonthlyExpenses + if (k == 1 && value != 0) + value = uint32_t(rec32(g, m, 0x880)) < uint32_t(youth_limit(g, m)) ? youth_limit(g, m) : 0; + costs = wrap(int64_t(costs) + value); + } + costs = wrap(int64_t(costs) - shares_and_loans(g, m, 2, 0) + int(rec8(g, m, 0x179)) * 1000); + if (costs < 0) costs = 0; + int32_t income = facility_income(g, m); + for (int i = 0; i < 16; ++i) income = wrap(int64_t(income) + rec32(g, m, 0xa34 + size_t(i) * 12)); + constexpr int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // DeskState_DeskDate_RuntimeField + const int month = month_code(g.date); + if (month < 1 || month > 12) throw FormatError("stadium attendance: invalid Source month"); + income = wrap(int64_t(income) + shares_and_loans(g, m, 1, 0) - + int64_t(daily_interest_preview(g, m)) * days[month]); + const int32_t bonus = monthly_pay(g, m, 9); + int32_t needed = wrap(int64_t(wrap(int64_t(costs) - income)) * 12 + bonus) / home_games; + const int price = rec8(g, m, 0x26e); + if (price != 0) needed /= price; + return std::max(needed, int32_t(0)); +} + +BalancePlanDraft open_balance_plan(const GameState& g, int manager) { + BalancePlanDraft d; + d.manager = manager; + const int m = manager; + d.view = BalanceView(std::clamp(int(int8_t(rec8(g, m, 0x310))), 0, 2)); + const int league = team_league(g.manager_teams.at(size_t(m))); + auto& r = d.rows; + r[kBalanceLeagueHomeGames] = league < kLeagueCount ? league_matchdays(league) / 2 : 0; + r[kBalanceOtherHomeGames] = rec32(g, m, 0x2f8); + r[kBalanceAverageGate] = rec32(g, m, 0x2fc); + uint8_t ticket = g.memory.has(kPlanTicketPrice + uint32_t(m)) ? g.memory.u8(kPlanTicketPrice + uint32_t(m)) : 0; + if (ticket == 0) ticket = rec8(g, m, 0x26e); + r[kBalanceTicketPrice] = ticket; + r[kBalanceAccount] = rec32(g, m, 0x314); + // the average gate of the last league home games (+0x340, count +0x283) + int32_t sum = 0; + const int games = rec8(g, m, 0x283); + for (int i = 0; i < games; i++) sum = wrap(int64_t(sum) + rec32(g, m, 0x340 + size_t(i) * 4)); + r[kBalanceGateSoFar] = games != 0 ? sum / games : sum; + if (rec32(g, m, 0x300) != 0) r[kBalanceAverageGate] = rec32(g, m, 0x304) / rec32(g, m, 0x300); + for (int i = 0; i < kBalanceItems; i++) d.adjustments[size_t(i)] = rec32(g, m, 0x2b0 + size_t(i) * 4); + d.refresh = 2; + redraw(g, d); + return d; +} + +void cycle_balance_view(const GameState& g, BalancePlanDraft& d) { + d.view = BalanceView((int(d.view) + 1) % 3); + d.refresh = d.rows[kBalanceAverageGate] != 0 ? 2 : 1; + redraw(g, d); +} + +void reset_balance_plan(const GameState& g, BalancePlanDraft& d) { + d.adjustments.fill(0); + d.refresh = 1; + redraw(g, d); +} + +int32_t balance_row_maximum(const BalancePlanDraft& d, int row) { + if (row < 0 || row >= 0x16 || !kEditable[row]) return -1; + (void)d; // the input dialog BalanceFromGame only offers other step sizes for the gate + return kMaximum[kMaximumClass[row]]; +} + +BalanceEditStatus edit_balance_plan(const GameState& g, BalancePlanDraft& d, int row, int32_t value) { + if (row < 0 || row >= 0x16 || !kEditable[row]) return BalanceEditStatus::not_editable; + if (d.view == BalanceView::so_far) return BalanceEditStatus::view_so_far; + if (value < 0 || value > balance_row_maximum(d, row)) return BalanceEditStatus::out_of_range; + if (row < kBalanceItems) + d.adjustments[size_t(row)] = wrap(int64_t(d.adjustments[size_t(row)]) + + wrap(int64_t(int8_t(d.months_left)) * (int64_t(value) - d.rows[size_t(row)])) / 12); + d.rows[size_t(row)] = value; + if (row > 0x11) d.refresh = 2; + redraw(g, d); + return BalanceEditStatus::changed; +} + +bool close_balance_plan(GameState& g, const BalancePlanDraft& d) { + const int m = d.manager; + const bool warning = double(rec32(g, m, 0x314)) + d.total < -4000000.0; // BalancePlanRuntimeField8 + for (int i = 0; i < kBalanceItems; i++) set_rec32(g, m, 0x2b0 + size_t(i) * 4, d.adjustments[size_t(i)]); + set_rec32(g, m, 0x308, int32_t(std::lround(d.total))); + if (g.memory.has(kPlanTicketPrice + uint32_t(m))) g.memory.set8(kPlanTicketPrice + uint32_t(m), uint8_t(d.rows[kBalanceTicketPrice])); + set_rec32(g, m, 0x2f8, d.rows[kBalanceOtherHomeGames]); + set_rec32(g, m, 0x2fc, d.rows[kBalanceAverageGate]); + set_rec32(g, m, 0x310, int32_t(d.view)); + return warning; +} + +} // namespace bmh diff --git a/src/game/balance_plan.hpp b/src/game/balance_plan.hpp new file mode 100644 index 0000000..bdb69b2 --- /dev/null +++ b/src/game/balance_plan.hpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: uses the supported staff and youth-academy cost categories. +// The balance plan ("Bilanz", desk menu 28, mode III; H2 p. 26-27; BMH.exe V2.24 + supported rule profile +// patch): the screen BalanceFromGame2 projects the club's income and expenses for the business +// year and lets the manager change every item. When he leaves the screen the resulting +// profit/loss becomes the plan figure (manager record +0x308). On the 16th Bundesliga +// matchday the plan is handed to the DFB (+0x308 -> +0x320, matchday.cpp); from then on it +// lifts or lowers the advertising offers (weekly.cpp, plan / 100000 within -10..10) and at +// the end of the season the DFB punishes a result more than 1 million below the plan +// (season.cpp, SeasonEvent). +// +// The screen has three views (left button, captions BalancePlan_DrawButtons_TextPointer): +// so_far "bisher" - the booked figures of the season so far (record +0x85c..), no changes +// real "real" - booked figures plus a projection for the months left +// future "zukunft" - a projection for twelve months +// The manager's changes are kept per item normalised to twelve months (record +0x2b0, the +// screen's local_c8) and are added again on the next visit; "Werte akt." (right button) +// drops them. +// +// The screen's state is a BalancePlanDraft (the locals of BalanceFromGame2); the functions below +// are its event handlers. Projections run on a copy of the GameState: the wage projection +// (MonthlyPay -> table prediction) writes scratch tables, and a console must be able to +// look at the plan without changing the game. + +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +constexpr int kBalanceItems = 18; // 0-6 income, 7-17 expenses (labels BalancePlan_DrawRows_TextPointer5) +// Rows after the items (labels BalancePlan_DrawRows_TextPointer4): league home games, other home games, average +// gate (calculated), ticket price, average gate so far, account balance. +enum BalanceRow : int { + kBalanceLeagueHomeGames = 0x12, + kBalanceOtherHomeGames = 0x13, + kBalanceAverageGate = 0x14, + kBalanceTicketPrice = 0x15, + kBalanceGateSoFar = 0x16, + kBalanceAccount = 0x17, + kBalanceRows = 0x18, +}; + +enum class BalanceView : uint8_t { so_far = 0, real = 1, future = 2 }; + +struct BalancePlanDraft { + int manager = -1; + BalanceView view = BalanceView::so_far; // local_14 (record +0x310) + std::array rows{}; // local_178[0..20], local_124, local_120, local_11c + std::array adjustments{}; // local_c8 (record +0x2b0) + int refresh = 2; // local_18: 0 keep the items, 1 recompute, 2 recompute keeping the gate + int months_left = 0; // local_24 + int days_left = 0; // local_34 + int64_t depreciation = 0; // "Abschreibungen": record +0x30c in the views so_far/real + double total = 0; // GEWINN (> 0) / VERLUST (< 0), the plan figure on leaving +}; + +// BalanceFromGame2 up to its first redraw: the draft of `manager` with the stored view, the +// stored changes and the projection of that view. +// StadiumRequiredAttendance: minimum average attendance at the current stadium entry price. +// Pure preview, using a copy for Source prediction scratch writes; no RNG. +int32_t stadium_required_attendance(const GameState&, int manager); + +BalancePlanDraft open_balance_plan(const GameState& g, int manager); + +// The left button: the next view (so_far -> real -> future -> so_far), projected again. +void cycle_balance_view(const GameState& g, BalancePlanDraft& draft); +// The right button "Werte akt.": drops the manager's changes and projects again. +void reset_balance_plan(const GameState& g, BalancePlanDraft& draft); + +enum class BalanceEditStatus : uint8_t { + changed, + view_so_far, // "Bitte den linken Button auf REAL oder ZUKUNFT stellen" (BalancePlan_BalanceFromGame_TextPointer) + not_editable, // spectator income, league home games, gate so far, balance + out_of_range, +}; +// Range of a row in the number input (BalanceFromGame): 0 .. maximum. +int32_t balance_row_maximum(const BalancePlanDraft& draft, int row); +// A click on a row and a new value: items keep the change in `adjustments` (scaled to twelve +// months); the home games, the gate and the ticket price project the plan again. +BalanceEditStatus edit_balance_plan(const GameState& g, BalancePlanDraft& draft, int row, int32_t value); + +// Leaving the screen: writes the changes (+0x2b0), the plan figure (+0x308), the other home +// games and the gate (+0x2f8/+0x2fc), the view (+0x310) and the ticket price of the plan +// (PlanTicketPrice). Returns true when the DFB demands a better balance (account + plan below +// -4 million, message BalancePlan_BalanceFromGame_TextPointer2) - the plan is stored nevertheless. +bool close_balance_plan(GameState& g, const BalancePlanDraft& draft); + +} // namespace bmh diff --git a/src/game/bank_credit.cpp b/src/game/bank_credit.cpp new file mode 100644 index 0000000..41dfcad --- /dev/null +++ b/src/game/bank_credit.cpp @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/bank_credit.hpp" + +#include +#include +#include +#include +#include +#include +#include "game/matchday.hpp" + +namespace bmh { +namespace { +constexpr uint32_t kLoans = ::bmh::layout::Loans; +constexpr size_t kRecord = 0xb0c; +int32_t signed_word(uint32_t v) { return std::bit_cast(v); } +uint32_t word(int32_t v) { return std::bit_cast(v); } +int32_t add(int32_t a, int32_t b) { return signed_word(word(a) + word(b)); } +int32_t sub(int32_t a, int32_t b) { return signed_word(word(a) - word(b)); } +int32_t mul(int32_t a, int32_t b) { return signed_word(word(a) * word(b)); } +int32_t divide(int32_t a, int32_t b) { + if (!b || (a == std::numeric_limits::min() && b == -1)) + throw std::invalid_argument("invalid native credit division"); + return a / b; +} +uint32_t read_record(const GameState& g, size_t at) { + uint32_t v = 0; + for (int i = 0; i < 4; ++i) v |= uint32_t(g.manager_records.at(at + i)) << (i * 8); + return v; +} +// Amount: signed IMUL/IDIV, x87 intermediate, QWORD store, +// exact-zero floor, then Amount2's explicit rounding toward zero. +int32_t amount(const BankCreditContext& c, uint32_t months, int32_t principal) { + if (months > 48 || c.rate_table[months] <= 100 || c.divisor != 100.0) + throw std::invalid_argument("invalid native credit factors"); + const int32_t factor = c.rate_table[months]; + const int32_t base = divide(mul(principal, factor), 100); + const int32_t den = divide(10000, factor - 100); + const long double intermediate = (static_cast(base) / c.divisor) + * den / c.divisor; + double raw = static_cast(intermediate); + if (raw == 0 && principal != 0) raw = 1; + raw = std::trunc(raw); + if (!std::isfinite(raw) || raw < std::numeric_limits::min() + || raw > std::numeric_limits::max()) + throw std::invalid_argument("invalid native credit amount"); + return static_cast(raw); +} +void balance(const BankCreditContext& c, BankCreditDraft& d) { + int32_t result = add(c.cash, signed_word(d.values[0])); + result = sub(result, signed_word(c.saved[0])); + result = sub(result, signed_word(d.values[6])); + result = add(result, d.refund); + result = sub(result, d.fees); + d.values[7] = word(sub(result, d.interest_adjustment)); +} +} + +BankCreditContext bank_credit_context(const GameState& g, const LeImage& exe, int manager, int counterparty) { + BankCreditContext c; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() + || g.manager_records.size() < (size_t(manager) + 1) * kRecord) return c; + // case 5: another human manager lends (row lender + 1 of the borrower's matrix) + if (counterparty < 0 || counterparty > 4 || counterparty - 1 == manager || + (counterparty > 0 && size_t(counterparty - 1) >= g.manager_teams.size())) return c; + c.counterparty = counterparty; + const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(counterparty) * 0x18; + try { + for (size_t i = 0; i < c.saved.size(); ++i) c.saved[i] = g.memory.u32(at + uint32_t(i) * 4); + for (size_t i = 0; i < c.rate_table.size(); ++i) c.rate_table[i] = exe.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i)); + const uint64_t bits = uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32; + c.divisor = std::bit_cast(bits); + const size_t rec = size_t(manager) * kRecord; + c.cash = signed_word(read_record(g, rec + 0x314)); + c.overdraft = signed_word(read_record(g, rec + 0x31c)); + if (counterparty > 0) { + const size_t lender = size_t(counterparty - 1) * kRecord; + c.lender_liquidity = add(signed_word(read_record(g, lender + 0x314)), signed_word(read_record(g, lender + 0x31c))); + } + c.available = c.divisor == 100.0 && c.saved[3] <= 48 && c.saved[4] <= 48; + for (auto factor : c.rate_table) c.available = c.available && factor > 100; + } catch (const std::out_of_range&) { return {}; } + return c; +} + +bool change_bank_credit_interest(GameState& g, int manager, uint8_t new_rate) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || !g.credit_rate_table_available) + return false; + const uint32_t at = kLoans + uint32_t(manager) * 0x78; + for (uint32_t i = 0; i < 24; ++i) if (!g.memory.has(at + i)) return false; + try { + const int32_t principal = signed_word(g.memory.u32(at)); + const int32_t term = signed_word(g.memory.u32(at + 12)); + const int32_t elapsed = signed_word(g.memory.u32(at + 16)); + const int32_t remaining = sub(principal, mul(divide(principal, term), elapsed)); + const int32_t adjusted = divide(remaining, 100); + const int32_t next_principal = mul(adjusted, 100 - int32_t(new_rate)); + const int32_t next_term = sub(term, elapsed); + BankCreditContext c; + c.rate_table = g.credit_rate_table; + c.divisor = g.credit_divisor; + const uint32_t payment = word(amount(c, uint32_t(next_term), next_principal)); + g.memory.set32(at, word(next_principal)); + g.memory.set32(at + 12, word(next_term)); + g.memory.set32(at + 16, 0); + g.memory.set32(at + 20, 0); + g.memory.set32(at + 8, payment); + g.memory.set32(at + 4, payment * uint32_t(next_term)); + return true; + } catch (const std::exception&) { return false; } +} + +BankCreditDraft bank_credit_draft(const BankCreditContext& c) { + BankCreditDraft d; + for (size_t i = 0; i < c.saved.size(); ++i) d.values[i] = c.saved[i]; + // Source clears the working paid field after its first rendering. The UI + // still uses the saved field for that initial display. + d.values[5] = 0; + d.values[7] = word(c.cash); + return d; +} + +BankCreditBounds bank_credit_bounds(const BankCreditContext& c, const BankCreditDraft& d, int field) { + if (!c.available || (field != 0 && field != 1 && field != 3 && field != 6 && !(field == 2 && c.counterparty)) + || (field == 6 && !c.saved[0])) return {}; + try { + const auto& v = d.values; + int32_t accrued = 0; + if (v[0]) { + const uint32_t elapsed = v[4] ? v[4] : 1; + accrued = sub(mul(amount(c, elapsed, signed_word(v[0])), signed_word(elapsed)), + signed_word(v[5])); + } + const int32_t liquidity = add(c.cash, c.overdraft); + int32_t lo = 0, hi = 0; + if (field == 0) { + lo = 1000; + hi = sub(12000000, accrued); + // case 5: no more than the lender can pay out (balance + credit line) + if (c.counterparty && c.lender_liquidity < hi) hi = sub(c.lender_liquidity, accrued); + } + if (field == 2) { + // case 5 only: the monthly payment within 20 % of the annuity (Amount + // with the term and the net principal); the input starts at the annuity of + // the whole principal + const int32_t rate = amount(c, v[3], signed_word(v[0] - v[6])); + lo = sub(rate, rate / 5); + hi = add(rate, rate / 5); + if (lo >= hi || lo < 0) return {}; + return {word(lo), word(hi), word(amount(c, v[3], signed_word(v[0]))), true}; + } + if (field == 1) { lo = c.cash < accrued ? sub(accrued, liquidity) : liquidity; hi = accrued; } + if (field == 3) { + lo = 1; + hi = amount(c, v[3], signed_word(v[0] - v[6])) == 0 ? 0 : 48; + } + if (field == 6) { hi = liquidity < accrued ? liquidity : signed_word(v[0]); } + // Source checks availability before overriding the principal bounds. + if (lo >= hi) return {}; + if (field == 0 && lo < signed_word(c.saved[0])) { lo = signed_word(c.saved[0]); hi = 12000000; } + if (lo < 0 || hi < 0 || lo >= hi) return {}; + return {word(lo), word(hi), word(lo - (lo == 1)), true}; + } catch (const std::invalid_argument&) { return {}; } +} + +bool edit_bank_credit(const BankCreditContext& c, BankCreditDraft& draft, int field, uint32_t value) { + const auto bounds = bank_credit_bounds(c, draft, field); + if (!bounds.available || value < bounds.minimum || value > bounds.maximum) return false; + BankCreditDraft d = draft; + try { + if (!d.interest_adjustment) { + d.principal_paid = c.saved[3] + ? mul(signed_word(c.saved[4]), divide(signed_word(c.saved[0]), signed_word(c.saved[3]))) + : mul(signed_word(c.saved[0]), signed_word(c.saved[4])); + } + d.values[field] = value; + // fees only for the bank (case 4) + d.fees = !c.counterparty && c.saved[0] && (d.values[6] || d.values[3] != c.saved[3]) ? 5000 : 0; + if (!d.interest_adjustment && (field == 0 || field == 3 || field == 6)) { + const int32_t term = c.saved[3] ? signed_word(c.saved[3]) : 1; + const int32_t saved_p = signed_word(c.saved[0]); + const int32_t remaining = sub(saved_p, d.principal_paid); + const int32_t interest = sub(sub(amount(c, 1, saved_p), saved_p), + sub(amount(c, 1, remaining), remaining)); + d.interest_adjustment = divide(mul(interest, signed_word(c.saved[3] - c.saved[4])), term); + d.refund = mul(signed_word(c.saved[4]), divide(saved_p, term)); + d.values[4] = d.values[5] = 0; + d.principal_paid = 0; + } + if (field != 2 && field != 3 && field != 6) d.values[3] = 48; + const int32_t net = signed_word(d.values[0] - d.values[6]); + // a monthly payment set in case 5 stays; every other edit computes the annuity + if (field != 2) d.values[2] = net ? word(amount(c, d.values[3], net)) : 0; + if (d.fees) d.fees = add(d.fees, sub(amount(c, 1, signed_word(d.values[6])), signed_word(d.values[6]))); + d.values[1] = d.values[2] * d.values[3]; + d.initial_display = false; + d.edits.push_back({field, value}); + balance(c, d); + } catch (const std::invalid_argument&) { return false; } + draft = std::move(d); + return true; +} + +BankCreditResult commit_bank_credit(GameState& g, const LeImage& exe, int manager, + const std::array& expected, const std::vector& edits, bool accept_fees, + int counterparty) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return {BankCreditStatus::invalid_manager}; + const auto c = bank_credit_context(g, exe, manager, counterparty); + if (!c.available) return {BankCreditStatus::invalid_state}; + if (c.saved != expected) return {BankCreditStatus::stale_request}; + if (edits.empty()) return {BankCreditStatus::no_change}; + if (edits.size() > 4096) return {BankCreditStatus::invalid_request}; + auto d = bank_credit_draft(c); + for (const auto& edit : edits) + if (!edit_bank_credit(c, d, edit.field, edit.value)) return {BankCreditStatus::invalid_request}; + // only the bank charges (and asks for) fees and the interest adjustment + const int32_t fees = c.counterparty ? 0 : add(d.fees, d.interest_adjustment); + const int lender = c.counterparty - 1; + if (fees && !accept_fees) return {BankCreditStatus::confirmation_required, fees, d.refund}; + auto resulting_record = c.saved; + if (!d.values[1]) resulting_record.fill(0); + else { + for (size_t i = 0; i < 5; ++i) resulting_record[i] = d.values[i]; + resulting_record[0] -= d.values[6]; + if (signed_word(resulting_record[1]) < signed_word(resulting_record[0])) + resulting_record[1] += resulting_record[0]; + if (signed_word(resulting_record[0]) < 1) resulting_record[0] = 1; + if (d.refund) resulting_record[4] = resulting_record[5] = 0; + } + if (!fees && !d.refund && c.saved[0] - d.values[0] + d.values[6] == 0 + && resulting_record == c.saved) return {BankCreditStatus::no_change}; + GameState staged = g; + if (fees) book_money(staged, manager, fees, true, false); + if (d.refund) { + d.values[4] = 0; + // the repaid part comes back from the bank or from the lender + if (lender >= 0) book_money(staged, lender, d.refund, true, false); + book_money(staged, manager, sub(0, d.refund), true, false); + } + const int32_t principal_change = signed_word(c.saved[0] - d.values[0] + d.values[6]); + book_money(staged, manager, principal_change, true, false); + if (lender >= 0) book_money(staged, lender, sub(0, principal_change), true, false); + const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(c.counterparty) * 0x18; + if (!d.values[1]) { + for (uint32_t i = 0; i < 6; ++i) staged.memory.set32(at + i * 4, 0); + } else { + d.values[0] -= d.values[6]; + if (signed_word(d.values[1]) < signed_word(d.values[0])) d.values[1] += d.values[0]; + if (signed_word(d.values[0]) < 1) d.values[0] = 1; + for (uint32_t i = 0; i < 5; ++i) staged.memory.set32(at + i * 4, d.values[i]); + if (d.refund) staged.memory.set32(at + 20, 0); + } + g = std::move(staged); + return {BankCreditStatus::accepted, fees, d.refund}; +} +} // namespace bmh diff --git a/src/game/bank_credit.hpp b/src/game/bank_credit.hpp new file mode 100644 index 0000000..0e6ca4a --- /dev/null +++ b/src/game/bank_credit.hpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include "formats/le.hpp" +#include "game/state.hpp" + +namespace bmh { + +// MaxSharesToBuy case 4 (the bank) and case 5 (another manager lends). Row c of +// each manager's native 0x78-byte loan matrix (Loans + borrower * 0x78 + c * 0x18) +// is the credit from the bank (c = 0) or from manager c - 1, and contains principal, +// total, monthly payment, term, elapsed months and payments made. Case 5 differs only +// in: the principal is limited by the lender's balance plus credit line, the monthly +// payment (field 2) can be set within 20 % of the annuity, there are no fees and no +// fee question, and every booking is mirrored on the lender. The original asks the +// lender nothing. Projection and draft editing are read-only. +struct BankCreditContext { + int counterparty = 0; // 0 the bank, else lender manager + 1 + int32_t lender_liquidity = 0; // case 5: lender balance (+0x314) + credit line (+0x31c) + std::array saved{}; + std::array rate_table{}; + double divisor = 0; + int32_t cash = 0, overdraft = 0; + bool available = false; +}; + +struct BankCreditEdit { + int field = -1; + uint32_t value = 0; + friend bool operator==(const BankCreditEdit&, const BankCreditEdit&) = default; +}; + +struct BankCreditDraft { + std::array values{}; + int32_t fees = 0, interest_adjustment = 0, refund = 0, principal_paid = 0; + bool initial_display = true; + std::vector edits; +}; + +struct BankCreditBounds { + uint32_t minimum = 0, maximum = 0, initial = 0; + bool available = false; +}; + +BankCreditContext bank_credit_context(const GameState&, const LeImage&, int manager, int counterparty = 0); +// ChangeBankCreditInterest: apply the automatic interest change to the bank loan record. +bool change_bank_credit_interest(GameState&, int manager, uint8_t new_rate); +BankCreditDraft bank_credit_draft(const BankCreditContext&); +BankCreditBounds bank_credit_bounds(const BankCreditContext&, const BankCreditDraft&, int field); +bool edit_bank_credit(const BankCreditContext&, BankCreditDraft&, int field, uint32_t value); + +enum class BankCreditStatus { + accepted, no_change, invalid_manager, invalid_state, invalid_request, + stale_request, confirmation_required +}; +struct BankCreditResult { + BankCreditStatus status = BankCreditStatus::invalid_request; + int32_t fees = 0, refund = 0; +}; + +// Replay the local Source edits against the current native record before +// booking; fees and refund are derived here, never trusted from a UI amount. +BankCreditResult commit_bank_credit(GameState&, const LeImage&, int manager, + const std::array& expected, const std::vector& edits, + bool accept_fees, int counterparty = 0); + +} // namespace bmh diff --git a/src/game/career.cpp b/src/game/career.cpp new file mode 100644 index 0000000..0101b7a --- /dev/null +++ b/src/game/career.cpp @@ -0,0 +1,689 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/career.hpp" + +#include + +#include "game/messages.hpp" +#include "game/schedule.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kPoolSlots = 2928; // CareerRuntimeField: the clubs' squads end here +constexpr size_t kTailFrom = 2928 + 40; +constexpr size_t kTailTo = 2972; // CareerRuntimeField2 +constexpr size_t kExtraSlots = 3096; // CareerSession_DataDirectory_RuntimeField4: 54 extra players from here +constexpr size_t kSquadSlots = 3096 + 54; +constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField + +// LeagueSizes: clubs per league; LeagueStrengthRanges: (minimum, maximum) strength per league. +// (the clubs per league are kLeagueSizes, schedule.hpp) +constexpr int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28}, + {85, 95}, {90, 95}, {75, 95}, {80, 95}}; + +} // namespace + +void generate_player(GameState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand) { + Player& p = g.players.at(size_t(id)); + const bool keep_age = (level_flags & 0x1000) != 0, exact = (level_flags & 0x2000) != 0; + const int level = int16_t(level_flags & 0x0fff); + uint32_t w = 0x3000000; // goalkeepers + if ((p.w364 & 3) != 0) { + w = uint32_t(game.range(0, 7)) << 24; + w += uint32_t(game.range(0, 7)) << 21; + } + const int lo = exact ? level : level - level / 10, hi = exact ? level : level + level / 10; + const int condition = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); // ClampInteger + w += uint32_t(condition) << 14; + const int technique = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); + w += uint32_t(technique) << 7; + p.w35c = w + uint32_t(game.range(0x23, 0x41)); + p.w368 = (p.w368 & 0xff03c000u) + uint32_t(rand.range(0, 0x3fff)); + p.w364 &= ~(0x1fu << 21); + if (!keep_age) p.w364 |= uint32_t(game.range(2, 5)) << 21; +} + +std::vector startup_squad_list(const Database& db) { + std::vector slots(kSquadSlots, 0x0fff); + for (size_t i = 0; i + 1 < db.squad_list.size() && i / 2 < slots.size(); i += 2) + slots[i / 2] = uint16_t(db.squad_list[i] | db.squad_list[i + 1] << 8); + std::copy_backward(slots.begin() + long(kTailFrom), slots.begin() + long(kTailFrom + (kSquadSlots - kTailTo)), slots.end()); + return slots; +} + +void startup_players(GameState& g, GameRandom& game, WatcomRandom& rand) { + for (size_t i = 0; i < 0x36; i++) { + const int level = rand.range(i < 0x16 ? 0x14 : 0x46, 0x5a); + generate_player(g, int16_t(g.squad_slots.at(kExtraSlots + i)), int16_t(level), game, rand); + } + int previous = 0, index = -1; // local_18, local_1c + for (int team = 0; team < kLeagueTeams; team++) { + const int league = team_league(team); + index = league == previous ? index + 1 : 0; + previous = league; + const uint32_t count = uint32_t(kLeagueSizes[league]); + const uint32_t range = uint32_t(kLeagueStrength[league][1] - kLeagueStrength[league][0]); + const int level = int16_t(int((count - uint32_t(index)) * range * 100) / int(count) / 100) + kLeagueStrength[league][0]; + const SquadRange r = squad_range(team); + for (size_t s = r.first; s < r.first + r.count; s++) { + const int id = g.squad_slots.at(s) & 0x0fff; + if (id != 0x0fff) generate_player(g, id, level | 0x1000, game, rand); + } + } +} + +} // namespace bmh + +#include "formats/le.hpp" +#include "formats/savestate.hpp" + +namespace bmh { + +GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat) { + const DbCounts counts; + const std::vector layout = save_layout(counts, true); + Bytes stream; + for (const SaveBlock& b : layout) { + Bytes data(b.size, 0); + auto put = [&](const Bytes& src, size_t at = 0) { + for (size_t i = 0; i < src.size() && at + i < data.size(); i++) data[at + i] = src[i]; + }; + if (!b.heap) { + for (size_t i = 0; i < b.size; i++) + if (exe.contains(b.address + uint32_t(i))) data[i] = exe.u8(b.address + uint32_t(i)); + } + switch (b.address) { + case ::bmh::layout::PlayerBonuses: if (b.heap) put(db.raw_player_bonus_values); break; + case ::bmh::layout::ClubBadgeSelectors: if (b.heap) put(db.raw_club_badge_selectors); break; + case ::bmh::layout::ClubIdentities: if (b.heap) put(db.raw_club_name_offsets); break; + case ::bmh::layout::PlayerNameOffsets: if (b.heap) put(db.raw_player_name_offsets); break; + case ::bmh::layout::MasterDatabaseMetadata: if (b.heap) put(db.raw_database_metadata); break; + case ::bmh::layout::ClubAuxiliaryWords: if (b.heap) put(db.raw_club_auxiliary_words); break; + case ::bmh::layout::ForeignClubStrength: put(db.raw_foreign_club_strength); break; + case ::bmh::layout::Career_Put_ExecutableField3: put(db.raw_league_auxiliary_bytes); break; + case ::bmh::layout::RefereeProperties: put(db.raw_referee_properties); break; + case ::bmh::layout::ClubKitSelectors: put(db.raw_club_kit_selectors); break; + case ::bmh::layout::ClubShortNameOffsets: put(db.raw_club_short_name_offsets); break; + case ::bmh::layout::ClubSeasonRecords: if (!b.heap) data[0] = 1; break; // the pointer: records allocated + case ::bmh::layout::NextDeskManager: + for (size_t m = 0; m < 4; m++) data[m * 2] = uint8_t(m), data[m * 2 + 1] = 0; + break; + case ::bmh::layout::ManagerAutomation: + for (size_t m = 0; m < 4; m++) data[m * 5] = 1; + break; + case ::bmh::layout::ActiveManager: data[0] = 4; break; + case ::bmh::layout::Desktops: + for (size_t k = 0; k < 5; k++) put(m3_men, k * 0x360); + break; + case ::bmh::layout::Formations: + put(m3_dat); + for (size_t k = 1; k < 4; k++) + for (size_t i = 0; i < 0x160; i++) data[k * 0x160 + i] = data[i]; + break; + case ::bmh::layout::SquadSlots: + if (b.heap) { + const std::vector slots = startup_squad_list(db); + for (size_t i = 0; i < slots.size() && 2 * i + 1 < data.size(); i++) + data[2 * i] = uint8_t(slots[i]), data[2 * i + 1] = uint8_t(slots[i] >> 8); + } + break; + case ::bmh::layout::PlayerConditionTechniqueForm: + case ::bmh::layout::PlayerSkillWords: + case ::bmh::layout::PlayerIdentityWords: + if (b.heap) { + for (size_t i = 0; i < db.players.size() && 4 * i + 3 < data.size(); i++) { + uint32_t w = b.address == ::bmh::layout::PlayerConditionTechniqueForm ? db.players[i].w35c : b.address == ::bmh::layout::PlayerSkillWords ? db.players[i].w368 : db.players[i].w364; + if (b.address == ::bmh::layout::PlayerSkillWords && i + 32 >= db.players.size()) + w = (w & 0x07ffffffu) | uint32_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 - uint32_t(db.players.size() - i))) << 27; + for (int k = 0; k < 4; k++) data[4 * i + size_t(k)] = uint8_t(w >> (8 * k)); + } + } + break; + default: break; + } + stream.insert(stream.end(), data.begin(), data.end()); + } + for (const Bytes& pool : db.pools) { + stream.push_back(uint8_t(pool.size())); + stream.push_back(uint8_t(pool.size() >> 8)); + stream.insert(stream.end(), pool.begin(), pool.end()); + } + const SaveState save(stream, counts); + GameState g = GameState::from_save(save, counts); + competition_pointers(g.memory, exe); // CompetitionPointers + return g; +} + +} // namespace bmh + +#include "game/matchday.hpp" +#include "game/season.hpp" +#include "game/week.hpp" + +namespace bmh { + +void new_career_markets_and_moods(GameState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + for (uint32_t k = 0; k < 12; k++) { + if (k < 6) mem.set32(::bmh::layout::FundBlock + k * 0x1c, (1u << k) * 100000); + const size_t s = size_t(k) * 0x5c; + const uint32_t value = k * 2000 + 10000; + for (int i = 0; i < 4; i++) g.stocks.at(s + size_t(i)) = uint8_t(value >> (8 * i)); + g.stocks.at(s + 0x4e) = uint8_t(k * 20 + 100), g.stocks.at(s + 0x4f) = uint8_t((k * 20 + 100) >> 8); + } + stir_random(game, rand); + const int first = game.range(0, 1); + if (g.texts) { + auto name = [&](int record, uint32_t pointer) { + const std::string& t = (*g.texts)[(pointer - ::bmh::layout::TextPointerTable) / 4]; + const size_t at = size_t(record) * 0xb0c + 0xa8; + for (size_t i = 0; i <= t.size(); i++) g.manager_records.at(at + i) = i < t.size() ? uint8_t(t[i]) : 0; + }; + name(first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField); + name(1 - first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField2); + name(2, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField3); + name(3, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField4); + } + for (int day = 0; day < 30; day++) stock_market(g, game); + for (uint32_t i = 0; i < 900; i++) mem.set8(::bmh::layout::Titles + i, 0xff); + for (uint32_t i = 0; i < 4; i++) mem.set8(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2 + i, uint8_t(1 << i)); + for (uint32_t i = 0; i < 0x2c; i++) mem.set16(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField + i * 0x58, 0xfff); + reset_club_moods(g, game, rand, true); +} + +bool new_career_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + for (size_t slot = 0; slot < 2928; slot++) { + const int id = g.squad_slots.at(slot) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + p.w364 |= uint32_t(rand.range(4, 0x10)) << 21; + p.w368 = (p.w368 & 0xffffc000u) + uint32_t(rand.range(0, 0x3fff)); + } + for (int slot = 3096; slot < 3096 + 0x36; slot++) + if (!release_player(g, slot, game, rand, report)) return false; + return !report.unsupported; +} + +bool new_career_before_dialog(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + // CareerFirstSteps2 clears all four pending offers immediately before calling + // InitializeCareer. Raw executable BSS starts at zero, which is a valid offer + // for manager/player zero in ResolvePendingOffer, rather than the empty sentinel. + for (uint32_t offer = 0; offer < 4; ++offer) + g.memory.set32(::bmh::layout::OfferSlots + offer * 4, 0xffffffff); + new_career_markets_and_moods(g, game, rand); + return new_career_players(g, game, rand, report); +} + +} // namespace bmh + +#include "game/lineup.hpp" +#include "game/national.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecord = 0xb0c; + +uint16_t team_of(const GameState& g, int m) { + const size_t at = size_t(m) * kRecord + 0x290; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} + +// FindManagerForClub: a club of a human manager (manager slot 4 counts when manager 0 coaches +// the national team). +bool human_club(const GameState& g, int team) { + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + for (int m = 0; m < managers; m++) + if (team_of(g, m) == uint16_t(team)) return true; + return team_of(g, 0) == 0x165 && team_of(g, 4) == uint16_t(team); +} + +// OpenBMH deviates from the original: skips reserved calendar positions when assigning a joining manager to a club. +// The supported rule profile patch reserves club places whose calendar word (CompetitionCalendar, read with the +// club id as index) has the bits 0x4001. +bool reserved_place(const GameState& g, int team) { + return team >= 0 && (g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(team) * 2) & 0x4001) == 0x4001; +} + +// EuropeanClub: only the active prefixes of the three European lists count. +bool european_club(const GameState& g, int team) { + for (const auto& entry : {std::pair{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}}) + for (uint32_t i = 0; i < g.memory.u8(entry.second); ++i) + if (g.memory.u16(entry.first + i * 2) == uint16_t(team)) return true; + return false; +} + +// RemoveJoinTransfers: remove a joining club's sale entries and parallel bid fields. +void remove_join_transfers(GameState& g, int team) { + StaticMemory& mem = g.memory; + for (uint32_t row = 0; row < 44; ++row) { + const uint32_t base = ::bmh::layout::EditorList + row * 0x58; + if ((mem.u16(base + 8) & 0x7fff) == uint16_t(team)) { + g.squad_slots.at(kPoolSlots + row) = kEmptySlot; + continue; + } + int bid = 0; + while (bid < 4 && mem.u16(base + uint32_t(bid) * 2) != uint16_t(team)) ++bid; + if (bid == 4) continue; + const uint32_t found = uint32_t(bid); + if (bid != 3) { + for (uint32_t k = found; k < 3; ++k) { + mem.set16(base + k * 2, mem.u16(base + (k + 1) * 2)); + mem.set32(base + 0xc + k * 4, mem.u32(base + 0xc + (k + 1) * 4)); + mem.set32(base + 0x1c + k * 4, mem.u32(base + 0x1c + (k + 1) * 4)); + mem.set8(base + 0x34 + k, mem.u8(base + 0x34 + k + 1)); + for (uint32_t b = 0; b < 7; ++b) + mem.set8(base + 0x38 + k * 7 + b, mem.u8(base + 0x38 + (k + 1) * 7 + b)); + } + ++bid; // The Source terminator is found + 1, not always the last bid. + } + mem.set16(base + uint32_t(bid) * 2, 0xffff); + if (row > 39) { + g.squad_slots.at(kPoolSlots + row + 40) = kEmptySlot; + mem.set32(::bmh::layout::Career_RemoveJoinTransfers_RuntimeField + row * 4, 0xffffffff); + } + } +} + +// ConfirmManager: clean loans only after the final club swap/remapping. +bool remove_join_loans(GameState& g, int team, MinuteReport& report) { + StaticMemory& mem = g.memory; + for (uint32_t i = 0; i < 200; ++i) { + const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + i * 4, loan = mem.u32(at); + if (loan == 0) continue; + const int owner = int((loan >> 12) & 0x3ff), borrower = int((loan >> 22) & 0x3ff); + if (owner == team) mem.set32(at, 0); + else if (borrower == team) { + mem.set32(at, 0); + if (human_club(g, owner)) { + uint32_t k = 0; + while (k < 12 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2) != (loan & 0xfff)) ++k; + if (k == 12) { + report.fail("joining-manager loan has no human owner entry (PresentLoanReturn(0x3c))"); + return false; + } + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2, kEmptySlot); + } + } + } + return true; +} + +void put32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i)); +} + +// CareerAddManager2(team, mode): condition and technique of every player of a league club around +// a level of its league (mode 0 random W(min, max), 1 min + 3, 2 the middle + 1, 3 max - 3). +void set_club_strength(GameState& g, int team, int mode, WatcomRandom& rand) { + if (team >= kLeagueTeams) return; + const int league = team_league(team); + const int lo = kLeagueStrength[league][0], hi = kLeagueStrength[league][1]; + int level = mode; + switch (mode) { + case 0: level = rand.range(lo, hi); break; + case 1: level = lo + 3; break; + case 2: level = (hi + lo) / 2 + 1; break; + case 3: level = hi - 3; break; + default: break; + } + level = int16_t(level); + const SquadRange r = squad_range(team); + for (size_t s = r.first; s < r.first + r.count; s++) { + const int id = g.squad_slots.at(s) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + const int condition = std::clamp(rand.range(level - 6, level + 6), 0, 99); // ClampInteger + const int technique = std::clamp(rand.range(level - 6, level + 6), 0, 99); + p.w35c = (p.w35c & 0xffe0007fu) | uint32_t(condition) << 14 | uint32_t(technique) << 7; + } +} + +// CareerAddManager3(record, league, mode): the stadium of a human club - eight stand blocks +// (Career_BuildStadium_RuntimeField4[league] thousand places each), the facilities of the league +// (Career_BuildStadium_RuntimeField, levels W(Career_BuildStadium_RuntimeField2, Career_BuildStadium_RuntimeField3) << 2) and eight block values W(100, 140). +// Mode 1 (CareerDuration) builds everything one step better. +void build_stadium(GameState& g, const LeImage& exe, int m, int league, int mode, WatcomRandom& rand) { + uint8_t* rec = &g.manager_records.at(size_t(m) * kRecord); + for (int k = 0; k < 8; k++) { + rec[0x4c + k] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 + uint32_t(league)) + (mode == 1 ? 1 : 0)); + rec[0x5c] = uint8_t(rec[0x5c] + rec[0x4c + k]); + } + for (int i = 0; i < 0x16; i++) { + const uint8_t level = mode == 1 ? 3 : exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(i + league * 0x17)); + if (i == 0x10 || i == 0x11 || level == 0) continue; + if (i == 0) { + rec[0] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0)); + } else { + rec[i] = uint8_t(rand.range(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField2 + uint32_t(i * 5)), exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField3 + uint32_t(i * 5))) << 2); + } + if (i > 0xd) rec[i + 0x2e] = uint8_t(level + (mode == 1 ? 1 : 0)); + } + rec[0x3f] = rec[0x3e] = uint8_t((mode == 1) + 1); + for (int k = 0x16; k < 0x1e; k++) rec[k] = uint8_t(rand.range(100, 0x8c)); +} + +} // namespace + +// StartingSponsors: in mode GameMode == 1 or in the one-year mode before +// the first season day, the three sponsor contracts start at the value for the +// selected league and difficulty. Use GameState.date: memory CalendarDay can be +// stale in the port after a new-career/season transition. +void starting_sponsors(GameState& g, int m) { + const StaticMemory& mem = g.memory; + if (!(mem.u8(::bmh::layout::GameMode) == 1 || (mem.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0))) return; + const size_t rec = size_t(m) * kRecord; + int league = g.manager_records.at(rec + 0x210); + if (league > 2) league--; + const int v = (((league * -20 + 80) * 60000 + 1000000) / 12 * (mem.u8(::bmh::layout::Difficulty) * -5 + 0xaa)) / 3000000 * 10000; + for (size_t o : {size_t(0xae8), size_t(0xadc), size_t(0xa34)}) put32(g.manager_records, rec + o, uint32_t(v)); + for (size_t o : {size_t(0xaed), size_t(0xae1), size_t(0xa39)}) g.manager_records.at(rec + o) = 1; +} + +void career_managers_begin(GameState& g, bool adding) { + g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + const size_t rec = 4 * kRecord; + put32(g.manager_records, rec + 0x314, 1000000); + put32(g.manager_records, rec + 0x324, 1000000); + for (size_t i = 0; i < 0xd; i++) g.manager_records.at(rec + 0xc5 + i) = 2; + if (adding) { + const size_t count = g.memory.u8(::bmh::layout::ManagerCount); + g.manager_teams.resize(count); + for (size_t m = 0; m < count; ++m) g.manager_teams[m] = team_of(g, int(m)); + } else g.manager_teams.assign(g.memory.u8(::bmh::layout::ManagerCount), 0); + // ConfirmManager(0) posts PostSeasonNotice(0xff) immediately after the accepted + // new-career options dialog. The join path starts at a nonzero manager slot and + // must not repeat these three introduction messages. + if (adding || g.manager_teams.empty() || g.manager_teams.size() > 4) return; + post_text(g, -1, 1001); // CareerRuntimeField3 + post_text(g, -1, 1002); // CareerRuntimeField4 + post_text(g, -1, 1003); // CareerRuntimeField5 +} + +bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + // Reject malformed requests before changing records or consuming either RNG. + if (!g.memory.has(::bmh::layout::ManagerCount) || m < 0 || m >= 4 || + g.memory.u8(::bmh::layout::ManagerCount) > 4 || m >= g.memory.u8(::bmh::layout::ManagerCount) || + size_t(m) >= g.manager_teams.size() || g.manager_records.size() < 5 * kRecord || + choice.team < 0 || choice.team >= 168 || size_t(choice.team) >= g.club_ids.size() || + choice.league < 0 || choice.league > 4 || choice.strength < 0 || choice.strength > 2 || + choice.portrait < 0 || choice.portrait > 11 || choice.name.size() > 24 || + g.tactics.size() < size_t(m + 1) * 0x840 || + g.manager_ratings.size() < size_t(m + 1) * 0x3c || + g.manager_results.size() < g.manager_teams.size() * 0x690 || + g.squad_slots.size() < kSquadSlots || g.club_ids.size() < 168 || + g.team_morale.size() < 168 || g.team_flags.size() < 168 || + g.club_heap_bc.size() < 168 * 2 || g.club_heap_78.size() < 168 * 2 || + g.club_heap_b8.size() < 168 || g.position_history.size() < 138 * 0x1a || + (!g.club_table.empty() && g.club_table.size() < 168 * 0x4a) || + g.player_bonus.size() < g.players.size() || g.player_cards.size() < g.players.size() || + !exe.contains(::bmh::layout::Career_CareerAddManager_ExecutableField) || !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField3 + 0x15 * 5) || + !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField + 4 * 0x17 + 0x15)) { + report.fail("invalid career manager choice or slot"); + return false; + } + for (int other = 0; other < m; ++other) + if (g.manager_teams[size_t(other)] == choice.team) { + report.fail("career manager club is already managed"); + return false; + } + for (size_t slot = 0; slot < kPoolSlots; ++slot) { + const uint16_t player = g.squad_slots[slot] & 0x0fff; + if (player != kEmptySlot && size_t(player) >= g.players.size()) { + report.fail("invalid career manager squad player"); + return false; + } + } + StaticMemory& mem = g.memory; + const size_t rec = size_t(m) * kRecord; + std::vector& r = g.manager_records; + for (size_t i = 0; i < 0x12; i++) r.at(rec + 0x1f6 + i) = 1; + for (size_t i = 0; i < 10; i++) r.at(rec + 0x8b6 + i) = 0xff; + r.at(rec + 0x1f6) = 0x40; + // the values of the dialog (ManagerScreen2) + for (size_t i = 0; i < 0x19; i++) r.at(rec + 0xa8 + i) = i < choice.name.size() ? uint8_t(choice.name[i]) : 0; + r.at(rec + 0x290) = uint8_t(choice.team), r.at(rec + 0x291) = uint8_t(choice.team >> 8); + r.at(rec + 0x221) = uint8_t(choice.portrait); + r.at(rec + 0x210) = uint8_t(choice.league); + g.manager_teams.at(size_t(m)) = int16_t(choice.team); + + int place = 1 + m; // the club's place in the first league + if (!adding && mem.u8(::bmh::layout::CareerDuration) <= 1) mem.set8(::bmh::layout::Career_CareerAddManager_RuntimeField, 0); + else place = m + 9; + while (reserved_place(g, place) || human_club(g, place) || (adding && european_club(g, place))) place++; // CareerAddManager4 + int league = r.at(rec + 0x210); // local_18 + const int team = int16_t(team_of(g, m)); + if (adding) remove_join_transfers(g, team); + if (team_league(team) != league) { + int other = place; + if (league != 0) { + const int first = league_first_team(league), last = first + 12; // CareerRuntimeField6 (league * 18 in DE) + do other = int16_t(game.range(first, last)); + while (human_club(g, other)); // ReservedPlace2 + // ReservedPlace: the next of 13 places that is neither reserved nor human + int c = other; + for (int k = 0; k < 13; k++) { + if (!reserved_place(g, c) && !human_club(g, c)) { + other = c; + break; + } + if (++c > last) c -= 13; + } + } + if (adding) remove_join_transfers(g, other); + clubs_change_places(g, team, other); + set_club_strength(g, team, 0, rand); + place = 0; + } + if (league == 0 && place != 0) { + if (adding) remove_join_transfers(g, place); + clubs_change_places(g, int16_t(team_of(g, m)), place); + } + set_club_strength(g, int16_t(team_of(g, m)), choice.strength + 1, rand); + + const int club = int16_t(team_of(g, m)); + if (adding && !remove_join_loans(g, club, report)) return false; + g.team_morale.at(size_t(club)) |= 0x80; + r.at(rec + 0x26f) = 0x32; + if (league > 2) league--; + starting_sponsors(g, m); + r.at(rec + 0x26e) = uint8_t(std::max(20 - 2 * league, 14)); + build_stadium(g, exe, m, league, mem.u8(::bmh::layout::CareerDuration), rand); + if (league > 2) league = 2; + for (uint32_t i = 0; i < 3; i++) { + const uint32_t base = ::bmh::layout::Career_CareerAddManager_RuntimeField2 + uint32_t(m) * 0x24; + mem.set8(base + i, uint8_t(0x52 - league * 15)); + mem.set8(base + 3 + i, 6); + mem.set8(base + 6 + i, uint8_t(league)); + mem.set32(base + 0x18 + i * 4, 5000); + } + const SquadRange squad = squad_range(club); + r.at(rec + 0x288) = 0x16; + for (size_t i = 0; i < 0xd; i++) r.at(rec + 0xc5 + i) = 2; + for (size_t i = 0; i < 6; i++) r.at(rec + 0x8aa + 2 * i) = 0x26, r.at(rec + 0x8ab + 2 * i) = 0x02; + for (size_t i = 0; i < 0x3c; i++) g.manager_ratings.at(size_t(m) * 0x3c + i) = 100; + const int players = adding ? squad_count(g, club, 2) : 20; + for (int i = 0; i < players; i++) { + const size_t slot = squad.first + size_t(i); + Player& p = g.players.at(size_t(g.squad_slots.at(slot) & 0x0fff)); + p.w364 &= ~(0x1fu << 21); + p.w364 |= uint32_t(rand.range(4, 9)) << 21; + new_board_entry(g, m, i, int(slot), rand); + g.tactics.at(size_t(m) * 0x840 + size_t(i) * 0x58 + 0xd) = 100; + } + // Deviation from the original: a new career fills exactly 20 board rows (local_28 = 0x14), + // but new_career_players runs before the dialog and may already have moved a free agent + // into the chosen club (transfer_bid, "straight to the club"). That 21st player had no + // board row - no salary, and team_rating divides by his base pay (the original crashes + // once he plays). The remaining occupied rows get their entry the same way; with the + // usual 20 players nothing changes and no random number is drawn. + if (!adding) + for (size_t i = 20; i < squad.count && i < 24; i++) { + const size_t slot = squad.first + i; + const int id = g.squad_slots.at(slot) & 0x0fff; + if (id == 0x0fff) continue; + Player& p = g.players.at(size_t(id)); + p.w364 &= ~(0x1fu << 21); + p.w364 |= uint32_t(rand.range(4, 9)) << 21; + new_board_entry(g, m, int(i), int(slot), rand); + g.tactics.at(size_t(m) * 0x840 + i * 0x58 + 0xd) = 100; + } + for (size_t i = 0; i < 0x690; i++) g.manager_results.at(size_t(m) * 0x690 + i) = 0xff; + const uint8_t level = mem.u8(::bmh::layout::Difficulty); + const uint32_t money = level == 0 ? 50000000u : 4000000u - level * 200000u; + put32(r, rec + 0x314, money); + put32(r, rec + 0x324, money); + r.at(rec + 0x219) = r.at(rec + 0x218) = 0xf; + put32(r, rec + 0x31c, uint32_t(400000 - league * 100000)); + put32(r, rec + 0x310, 1); + auto_lineup(g, club, 100); + return !report.unsupported; +} + +void career_managers_end(GameState& g, bool adding) { + g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 0); + if (!adding) + for (uint32_t i = 0; i < 12; i++) g.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xfff); +} + +} // namespace bmh + +namespace bmh { + +// The English counterpart of CompetitionPointers: the Football Limited GermanRoundTable. The cup table +// (translated to CupTable, launch/fltd.hpp) is the English one; its entries 0-24 have the +// same roles as in German, so their arrays are the German ones (same sizes). Different: +// entry 0 (FA Cup qualifying stage) and the English-only competitions - entry 28 (FA Cup +// proper), 25-27 (League Cup) and 35 - which use memory blocks at their English addresses +// (english_competition_blocks); there are no indoor tournaments and no Masters. +namespace { + +// English round-string pointer tables -> the German ones the engine knows (cup.cpp) +uint32_t german_round_table(uint32_t en) { + switch (en) { + case ::bmh::layout::Career_GermanRoundTable_ExecutableField2: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField; // 4 teams + case ::bmh::layout::Career_GermanRoundTable_ExecutableField3: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField2; // 6 + case ::bmh::layout::Career_GermanRoundTable_ExecutableField: return ::bmh::layout::CareerSession_RuntimeError_ExecutableField2; // 20 + case ::bmh::layout::Career_GermanRoundTable_ExecutableField4: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField3; // 12 + default: return en; + } +} + +void competition_pointers_english(StaticMemory& mem, const LeImage& exe) { + auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; }; + english_competition_blocks(mem); + for (uint32_t k = 1; k < 0xf; k++) { + uint32_t b = k; + if (k > 9) b -= 9; + if (k > 0xc) b -= 3; + mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc); + } + uint32_t k = 7; + for (uint32_t i = 0; i < 8; i += 2, k++) { + if (k == 10) k = 0xc; + mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2); + } + const std::pair single[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, + {::bmh::layout::CupTable, kEnglishFaQualifyingField}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, kEnglishFaResults}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}}; + for (const auto& [at, to] : single) mem.set_pointer(at, to); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10); + for (uint32_t i = 0; i < 4; i++) { + const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i)); + mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30); + mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc); + const std::pair more[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}, + // the English-only cup entry table (entries 25-28 and 35) + {entry(28), ::bmh::layout::EnglishFaCupProperField}, {entry(28) + 0xc, ::bmh::layout::EnglishFaCupStageResults}, // FA Cup proper + {entry(25), ::bmh::layout::EnglishLeagueCupFirstRoundField}, {entry(25) + 0xc, ::bmh::layout::EnglishLeagueCupFirstRoundResults}, // League Cup + {entry(26), ::bmh::layout::EnglishLeagueCupQuarterFinalField}, {entry(26) + 0xc, ::bmh::layout::EnglishLeagueCupQuarterFinalResults}, {entry(26) + 0x10, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults}, + {entry(27), ::bmh::layout::EnglishLeagueCupSemiFinalField}, {entry(27) + 0xc, ::bmh::layout::EnglishLeagueCupSemiFinalResults}, + {entry(35) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField}, {entry(35), ::bmh::layout::EnglishAdditionalCupField}, {entry(35) + 0xc, ::bmh::layout::EnglishAdditionalCupResults}}; + for (const auto& [at, to] : more) mem.set_pointer(at, to); + // round tables the English table holds itself (static pointers to English strings) + for (uint32_t e = 0; e < 0x24; e++) { + const uint32_t at = entry(e) + 8; + const uint32_t p = mem.u32(at); + if (p >= ::bmh::layout::EnDataStart && p < ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField) mem.set_pointer(at, german_round_table(p)); + } +} + +} // namespace + +void english_competition_blocks(StaticMemory& mem) { + for (const auto& [at, size] : kEnglishCompetitionBlocks) + if (!mem.has(at)) mem.add_block(at, size); +} + +void competition_pointers(StaticMemory& mem, const LeImage& exe) { + if (kEnglishCompetitions) { + competition_pointers_english(mem, exe); + return; + } + auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; }; + // the cups of the leagues 1..14 (entries 1..14) + for (uint32_t k = 1; k < 0xf; k++) { + uint32_t b = k; + if (k > 9) b -= 9; + if (k > 0xc) b -= 3; + mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc); + } + // entries 7, 8, 9, 12 (Career_CompetitionPointersEnglish_RuntimeField10 pairs) + uint32_t k = 7; + for (uint32_t i = 0; i < 8; i += 2, k++) { + if (k == 10) k = 0xc; + mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2); + mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2); + } + const std::pair single[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, {::bmh::layout::CupTable, ::bmh::layout::Field}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, ::bmh::layout::Career_CompetitionPointers_ExecutableField}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}}; + for (const auto& [at, to] : single) mem.set_pointer(at, to); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10); + for (uint32_t i = 0; i < 4; i++) { + const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i)); + mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30); + mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15); + for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc); + const std::pair more[] = { + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28}, + {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}}; + for (const auto& [at, to] : more) mem.set_pointer(at, to); + // the indoor tournaments and the Masters (entries 25..29) + for (uint32_t i = 0; i < 5; i++) { + const uint32_t e = entry(0x19 + i); + mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(e + 0xc, ::bmh::layout::MatchdayGroupWorkspace + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField4 + i)) * 2); + mem.set_pointer(e, ::bmh::layout::Teams + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField5 + i)) * 2); + } + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField); + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField, ::bmh::layout::Teams); + mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField3, ::bmh::layout::MatchdayGroupWorkspace); +} + +} // namespace bmh diff --git a/src/game/career.hpp b/src/game/career.hpp new file mode 100644 index 0000000..b617bbf --- /dev/null +++ b/src/game/career.hpp @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// The start of a new career (BMH.exe V2.24 + supported rule profile patch). +// +// The original starts every career at program start: CareerFirstSteps2 loads the data files +// (TEXTD.BLK, M3.MEN, M3.DAT, M3D.MAN), gives every player new values and then calls +// InitializeCareer, which sets up shares, funds, club moods, ages and skills, shows the +// options and manager dialogs (SetupScreen2) inside ConfirmManager and finally prepares the +// first season. Loading a savegame from the options screen replaces all of that. +// +// The game generator starts at 0 (CareerSession_Save_RuntimeField is not initialised), the Watcom generator +// at the clock value of srand() - recordings capture it. + +#include +#include +#include + +#include "formats/m3d.hpp" +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// GeneratePlayer with the supported rule profile patch GeneratePlayer2: new values for player `id` around +// `level` (low 12 bits of `level_flags`; 0x1000 = leave the age at 0, 0x2000 = exactly +// the level instead of +-10 %): +// - w35c bits 21-26: G(0, 7) << 3 | G(0, 7) for field players, 0x18 for goalkeepers +// (two game draws, high part first); +// - condition and technique G(level - level / 10, level + level / 10), each cut to +// 10..99; form G(35, 65); bits 27-31 cleared; +// - w368: skills W(0, 0x3fff), bits 18-23 (cards) cleared; +// - w364: age bits cleared, then (without 0x1000) G(2, 5) = 18..21 years. +void generate_player(GameState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand); + +// The part of CareerFirstSteps2 after loading M3D.MAN: the 54 players of the extra slots +// (CareerSession_DataDirectory_RuntimeField4 ..) get W(20 or 70, 90) as level (the first 22 from 20), then the players +// of every league club get the level of its place in the database order of its league, +// from the league's maximum (first club) down towards its minimum (LeagueStrengthRanges pairs, +// club counts LeagueSizes), keeping the age at 0 for InitializeCareer. +void startup_players(GameState& g, GameRandom& game, WatcomRandom& rand); + +// The squad list as CareerFirstSteps2 leaves it: all slots 0xfff, the database list read +// over them and its tail (from slot CareerRuntimeField + 40) moved up to slot CareerRuntimeField2 +// (memmove; the four slots before keep their values). +std::vector startup_squad_list(const Database& db); + +} // namespace bmh + +namespace bmh { + +class LeImage; + +// The memory of the original after loading the data files in CareerFirstSteps2, as a GameState +// (built like a savegame: every saved block from the program's data object - zero where +// it is uninitialised - with the data of M3.MEN, M3.DAT and M3D.MAN read over it): +// manager order 0..3, option byte 0 of each manager 1, active manager 4, M3.MEN five +// times (Desktops), the first 0x160 bytes of M3.DAT four times (the other three +// parts of the file are overwritten), the nationality of the last 32 players from +// CareerRuntimeField7. The player values are those of the database; startup_players follows. +GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat); + +// CompetitionPointers (part of startup_state): the pointers of the competition table CupTable +// (36 entries of 0x28 bytes: +0 the teams, +8 the rounds, +0xc the results) to the tables of +// the leagues, cups and tournaments. +void competition_pointers(StaticMemory& mem, const LeImage& exe); + +// The memory of the English-only competitions (Football Limited, kEnglishCompetitions): +// blocks at their English addresses, which no German address uses. FA Cup results (67 +// matches) and fields (68 clubs: the 20 Premier League clubs, the 48 of the qualifying +// stage, the proper rounds), the League Cup (44 clubs, three entries) and entry 35. +constexpr uint32_t kEnglishFaResults = ::bmh::layout::EnglishFaCupResults; // 0x86 bytes, entry 0 +0x0c +constexpr uint32_t kEnglishFaField = ::bmh::layout::EnglishFaCupField; // 68 clubs: 20 + kEnglishFaQualifyingField +constexpr uint32_t kEnglishFaQualifyingField = ::bmh::layout::EnglishFaCupQualifyingField; // the 48 of the qualifying stage (entry 0) +constexpr uint32_t kEnglishLeagueCupField = ::bmh::layout::EnglishLeagueCupField; // 44 clubs: 20 + 24 at layout field (entry 25) +constexpr std::pair kEnglishCompetitionBlocks[] = { + {::bmh::layout::EnglishFaCupResults, 0x1ba}, // FA Cup: results EnglishFaCupResults, stage results EnglishFaCupStageResults, field EnglishFaCupField, proper EnglishFaCupProperField + {::bmh::layout::EnglishLeagueCupField, 0x136}, // League Cup: fields EnglishLeagueCupField/EnglishLeagueCupFirstRoundField/EnglishLeagueCupQuarterFinalField/EnglishLeagueCupSemiFinalField, results EnglishLeagueCupFirstRoundResults/EnglishLeagueCupQuarterFinalResults/EnglishLeagueCupSemiFinalResults/EnglishLeagueCupQuarterFinalOtherLegResults + {::bmh::layout::EnglishAdditionalCupResults, 0x48}, // entry 35: results EnglishAdditionalCupResults, field EnglishAdditionalCupField +}; +void english_competition_blocks(StaticMemory& mem); + +} // namespace bmh + +namespace bmh { + +// InitializeCareer up to the options dialog (SetupScreen2, called first in ConfirmManager(0)): +// - funds (price (1 << k) * 100 000) and shares (value k * 2000 + 10 000, price +// k * 20 + 100); +// - stir_random; G(0, 1) chooses which of the two computer manager names (Career_NewCareerMarketsAndMoods_ExecutableField / +// aeafc) the records 0 and 1 get, records 2 and 3 get Career_NewCareerMarketsAndMoods_ExecutableField3 / Career_NewCareerMarketsAndMoods_ExecutableField4 (needs +// g.texts; skipped without); +// - 30 days of share prices (stock_market); +// - Titles (900 bytes) 0xff, Career_NewCareerMarketsAndMoods_RuntimeField2 = 1, 2, 4, 8, the transfer list's 44 +// entries empty (player 0xfff); +// - club moods (reset_club_moods, career mode); +// - every club player (squad slots 0 .. CareerRuntimeField) gets an age W(4, 16) and new +// skills W(0, 0x3fff); +// - the 54 extra players leave for the free agents (release_player, MonthChange). +// Returns false if a step is not supported (report). +bool new_career_before_dialog(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); +// Its two parts: up to the club moods, and the ages, skills and extra players. +void new_career_markets_and_moods(GameState& g, GameRandom& game, WatcomRandom& rand); +bool new_career_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh + +namespace bmh { + +// A manager as confirmed in his dialog (ManagerScreen2; the UI's ManagerChoice): the dialog +// writes name (record +0xa8), club (+0x290), start league 0..4 (+0x210) and portrait +// (+0x221) into the record and returns the strength 0 (lower third) .. 2 (upper third). +struct CareerManager { + std::string name; // ISO 646-DE bytes, at most 24 + int team = 0; // club id at the moment of the confirmation + int league = 0; // start league 0..4 + int strength = 1; // 0 lower, 1 middle, 2 upper third + int portrait = 0; // 0..11 +}; + +// ConfirmManager before the first dialog: manager slot 4 (the national team's) gets the +// training plan 2 and 1 000 000 money. +void career_managers_begin(GameState& g, bool adding = false); + +// StartingSponsors initializes the three sponsor contracts for mode I, or for a +// one-year career before season day 0. The date check uses GameState.date, +// because the serialized CalendarDay mirror can be stale during startup/reset. +void starting_sponsors(GameState& g, int manager); + +// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers. +// The body of ConfirmManager's loop for manager `m` (`adding` = a manager joins a running +// game, param_1 != 0): the record is prepared and the dialog's values entered, then +// - the club moves to its place: in a league other than the chosen start league it +// changes places with a club of that league (G(first, first + 12), supported rule profile ReservedPlace2 +// / ReservedPlace skip clubs of humans and reserved places), which gets new values +// (CareerAddManager2(club, 0)); in the first league with a club place m + 1 (m + 9 when +// adding; supported rule profile CareerAddManager4 skips reserved and human places); +// - the club's players get condition and technique around the chosen strength +// (CareerAddManager2, W(level - 6, level + 6)); +// - record values: morale flag, board patience, stadium (CareerAddManager3, StartingSponsors), +// training plan, ratings, money (4 000 000 - level * 200 000; 50 000 000 at level 0), +// credit line, the first 20 players (or the whole squad when adding) on the tactics +// board with a new age W(4, 9), and an automatic line-up. +// The optional file of CareerAddManager (bonus codes) is not read. Needs the program image +// for its tables (Career_BuildStadium_RuntimeField4, Career_BuildStadium_RuntimeField, Career_BuildStadium_RuntimeField2). +bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ConfirmManager after the loop: clear CareerSession_FormatError_RuntimeField6; only a new career empties the twelve +// human loan entries Career_CareerManagersEnd_RuntimeField. Joining preserves unrelated entries. +void career_managers_end(GameState& g, bool adding); + +} // namespace bmh diff --git a/src/game/club_info.cpp b/src/game/club_info.cpp new file mode 100644 index 0000000..b355162 --- /dev/null +++ b/src/game/club_info.cpp @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/club_info.hpp" +#include +namespace bmh { +ClubInfoEntry prepare_club_info_entry(GameState& g, int team) { + if (team < 0 || (team >= 138 && team != kNoTeam)) + throw std::invalid_argument("club info: team has no squad"); + const SquadRange range = squad_range(team); + if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first) + throw std::invalid_argument("club info: truncated squad range"); + size_t occupied = 0; + for (size_t row = 0; row < range.count; ++row) { + const int id = g.squad_slots[range.first + row] & 0x0fff; + if (id == 0x0fff) continue; + if (size_t(id) >= g.players.size()) + throw std::invalid_argument("club info: invalid player ID"); + ++occupied; + } + // Allocate the owned pre-cleanup drawing rows before the first engine write. + ClubInfoEntry entry; + entry.displayed_slots.assign(g.squad_slots.begin() + range.first, + g.squad_slots.begin() + range.first + range.count); + // SquadCount(team,2) counts occupied IDs over the complete range. PrepareLineupEntry + // scans that count-sized prefix, even if the supplied map is sparse. + int last = int(occupied) - 1; + while (last >= 0 && (g.squad_slots[range.first + size_t(last)] & 0xc000) == 0) --last; + for (int row = 0; row <= last && row < 17; ++row) { + auto& slot = g.squad_slots[range.first + size_t(row)]; + slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000)); + } + entry.displayed_slots.assign(g.squad_slots.begin() + range.first, + g.squad_slots.begin() + range.first + range.count); + // PrepareClubInfoEntry clears bits13..15 for injured players over the entire range. + // Empty slots are a dummy ID in Original; preserve the sentinel explicitly. + for (size_t row = 0; row < range.count; ++row) { + auto& slot = g.squad_slots[range.first + row]; + const int id = slot & 0x0fff; + if (id != 0x0fff && ((g.players[size_t(id)].w364 >> 16) & 0x1f) != 0) + slot &= 0x1fff; + } + return entry; +} +uint8_t set_club_info_category(GameState& g, int team, int requested) { + constexpr size_t scan_count = 0x147; + if (team < 0 || size_t(team) >= g.team_morale.size() || + g.team_morale.size() < scan_count || requested < 0 || requested > 2) + throw std::invalid_argument("club info: invalid category request or club table"); + const size_t manager_count = g.memory.has(::bmh::layout::ManagerCount) + ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size(); + if (manager_count > 4 || manager_count > g.manager_teams.size()) + throw std::invalid_argument("club info: truncated manager teams"); + const bool national = !g.manager_teams.empty() && g.manager_teams.front() == kNoTeam; + constexpr size_t national_club = 4 * 0xb0c + 0x290; + if (national && g.manager_records.size() < national_club + 2) + throw std::invalid_argument("club info: truncated national manager record"); + // FindManagerForClub matches the first ManagerCount teams, irrespective of manager name, + // then the fifth record when the first manager is the national coach. + const auto human = [&](int club) { + for (size_t m = 0; m < manager_count; ++m) + if (g.manager_teams[m] == club) return true; + return national && (g.manager_records[national_club] | + uint16_t(g.manager_records[national_club + 1]) << 8) == club; + }; + uint8_t category = uint8_t(requested); + uint8_t seen = 0; + if (category == 2) { + for (size_t club = 0; club < scan_count; ++club) { + if ((g.team_morale[club] >> 6) != 2) continue; + ++seen; + if (seen != 4 || category != 2) continue; + if (!human(team)) category = 0; + else { + // Source local10 stays0: every search restarts at the first club. + for (size_t other = 0; other < scan_count; ++other) { + if ((g.team_morale[other] >> 6) == 2 && !human(int(other))) { + g.team_morale[other] = uint8_t((g.team_morale[other] & 0x3f) | 0x40); + --seen; + break; + } + } + } + } + } + g.team_morale[size_t(team)] = uint8_t((g.team_morale[size_t(team)] & 0x3f) | (category << 6)); + return category; +} + +} diff --git a/src/game/club_info.hpp b/src/game/club_info.hpp new file mode 100644 index 0000000..ccc30b7 --- /dev/null +++ b/src/game/club_info.hpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +#include "game/state.hpp" +namespace bmh { +// ClubInfoFromGame -> LineupScreen(..., param11=1): PrepareLineupEntry before +// drawing, PrepareClubInfoEntry after drawing. No player selection or RNG. +// Applies to computer and human domestic squads and the national squad. +// Invalid team/range/player IDs throw before any mutation. +struct ClubInfoEntry { + std::vector displayed_slots; // normalized flags before post-draw injury cleanup +}; +ClubInfoEntry prepare_club_info_entry(GameState& g, int team); +// ClubInfoFromGame numeric icon -> SetClubInfoCategory. Returns the applied raw +// category (0..2); may demote another computer club's category2 to1. +uint8_t set_club_info_category(GameState& g, int team, int requested); +} diff --git a/src/game/club_player_detail.cpp b/src/game/club_player_detail.cpp new file mode 100644 index 0000000..0f1666a --- /dev/null +++ b/src/game/club_player_detail.cpp @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/club_player_detail.hpp" + +#include +#include + +#include "game/matchday.hpp" +#include "game/month.hpp" +#include "game/national.hpp" +#include "game/lineup.hpp" +#include "game/weekly.hpp" + +namespace bmh { +namespace { +constexpr size_t kRecord = 0xb0c, kBoard = 0x840, kBoardRow = 0x58; + +uint16_t record_word(const GameState& g, size_t manager, size_t offset) { + const size_t at = manager * kRecord + offset; + if (at + 2 > g.manager_records.size()) throw std::invalid_argument("player detail: truncated manager record"); + return uint16_t(g.manager_records[at] | uint16_t(g.manager_records[at + 1]) << 8); +} + +int source_manager(const GameState& g, int club) { + const size_t count = g.memory.has(::bmh::layout::ManagerCount) ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size(); + if (count > 4 || count > g.manager_teams.size()) throw std::invalid_argument("player detail: invalid manager count"); + for (size_t m = 0; m < count; ++m) if (g.manager_teams[m] == club) return int(m); + if (count && g.manager_teams[0] == kNoTeam && record_word(g, 4, 0x290) == club) return 4; + return -1; +} + +int club_of_slot(int slot) { + if (slot < 0) return -1; + if (slot < 90 * 24) return slot / 24; + if (slot < 90 * 24 + 48 * 16) return (slot - 90 * 8) / 16; + if (slot >= 3072 && slot < 3096) return kNoTeam; + return -1; +} + +std::array board_copy(const GameState& g, int manager, int row) { + const size_t at = size_t(manager) * kBoard + size_t(row) * kBoardRow; + if (at + kBoardRow > g.tactics.size()) throw std::invalid_argument("player detail: truncated manager board"); + std::array out{}; + std::copy_n(g.tactics.begin() + static_cast(at), out.size(), out.begin()); + return out; +} +} // namespace + +ClubPlayerDetailContext club_player_detail_context(const GameState& g, const ClubPlayerDetailSelection& s) { + if ((s.origin != ClubPlayerDetailOrigin::squad && s.origin != ClubPlayerDetailOrigin::market_pool) || + s.player_id < 0 || size_t(s.player_id) >= g.players.size() || + size_t(s.player_id) >= g.player_cards.size() || size_t(s.player_id) >= g.player_bonus.size()) + throw std::invalid_argument("player detail: invalid player identity"); + ClubPlayerDetailContext out; + out.selection = s; + out.active_manager = g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0; + if (out.active_manager < 0 || size_t(out.active_manager) >= g.manager_teams.size()) + throw std::invalid_argument("player detail: invalid active manager"); + if (s.origin == ClubPlayerDetailOrigin::market_pool) { + if (s.runtime_team != -1 || s.physical_row != -1 || s.human_loan_index != -1 || + s.market_pool_slot < kClubPlayerDetailMarketPoolFirst || + s.market_pool_slot >= kClubPlayerDetailMarketPoolFirst + kClubPlayerDetailMarketPoolCount || + s.rendered_row < 0 || s.rendered_row >= kClubPlayerDetailMarketPoolCount || + size_t(s.market_pool_slot) >= g.squad_slots.size()) + throw std::invalid_argument("player detail: invalid transfer-market slot"); + out.source_slot = s.market_pool_slot; + out.displayed_slot = g.squad_slots[size_t(out.source_slot)]; + if (out.displayed_slot == kEmptySlot || (out.displayed_slot & 0x0fff) != s.player_id) + throw std::invalid_argument("player detail: stale transfer-market identity"); + out.market_pool = true; + out.source_manager = -1; + out.primary_club = -1; + } else { + if (s.rendered_row < 0 || s.rendered_row >= 24 || s.runtime_team < 0 || + (s.runtime_team >= 138 && s.runtime_team != kNoTeam)) + throw std::invalid_argument("player detail: invalid runtime club"); + const auto range = squad_range(s.runtime_team); + if (range.first + range.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated squad"); + out.source_manager = source_manager(g, s.runtime_team); + out.primary_club = s.runtime_team; + } + if (s.origin == ClubPlayerDetailOrigin::market_pool) { + // The validated pool identity is already loaded. National resolution + // below may select a real squad copy; offers never imply a board. + } else if (s.human_loan_index >= 0) { + const auto range = squad_range(s.runtime_team); + if (s.human_loan_index >= 12 || s.physical_row != -1 || s.runtime_team == kNoTeam || out.source_manager < 0) + throw std::invalid_argument("player detail: invalid human loan row"); + const uint32_t loan = uint32_t(s.human_loan_index); + const uint32_t player_at = ::bmh::layout::Career_CareerManagersEnd_RuntimeField + loan * 2, owner_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField2 + loan, board_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField + loan * kBoardRow; + if (!g.memory.has(player_at + 1) || !g.memory.has(owner_at) || !g.memory.has(board_at + kBoardRow - 1) || + g.memory.u16(player_at) != s.player_id || g.memory.u8(owner_at) != out.source_manager) + throw std::invalid_argument("player detail: stale human loan identity"); + out.human_loan = true; + out.source_slot = int(range.first) + s.rendered_row; + out.displayed_slot = uint16_t(s.player_id); + out.board.emplace(); + for (size_t i = 0; i < kBoardRow; ++i) (*out.board)[i] = g.memory.u8(board_at + uint32_t(i)); + } else { + const auto range = squad_range(s.runtime_team); + if (s.human_loan_index != -1 || s.physical_row < 0 || size_t(s.physical_row) >= range.count) + throw std::invalid_argument("player detail: invalid physical row"); + out.source_slot = int(range.first) + s.physical_row; + out.displayed_slot = g.squad_slots[size_t(out.source_slot)]; + if ((out.displayed_slot & 0x0fff) != s.player_id) throw std::invalid_argument("player detail: stale physical identity"); + } + if (!out.human_loan) { + if (g.manager_teams[size_t(out.active_manager)] == kNoTeam) { + const auto national = squad_range(kNoTeam); + if (national.first + national.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated national squad"); + bool selected = false; + for (size_t row = 0; row < national.count; ++row) + if ((g.squad_slots[national.first + row] & 0x0fff) == s.player_id) selected = true; + out.national_mode = selected ? 2 : 1; + // ClubPlayerDetailFromGame remaps BOTH modes to the first matching slot below + // LargeSquadClubCount, including pool slots, before resolving club/owner/board. + size_t slot = 0; + while (slot < national.first && (g.squad_slots[slot] & 0x0fff) != s.player_id) ++slot; + if (slot == national.first) throw std::invalid_argument("player detail: national player has no source slot before national squad"); + out.source_slot = int(slot); + out.primary_club = club_of_slot(out.source_slot); + out.secondary_club = selected ? kNoTeam : -1; + out.displayed_slot = g.squad_slots[slot]; + out.source_manager = out.primary_club < 0 ? -1 : source_manager(g, out.primary_club); + } + if (out.national_mode != 0 && out.primary_club == int(record_word(g, 4, 0x290)) && g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3)) { + const uint8_t owner = g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3); // literal SquadRange override + out.source_manager = owner == 0xff ? -1 : owner; + } + if (out.source_manager >= 0) { + const auto owner_range = squad_range(out.primary_club); + const int row = out.source_slot - int(owner_range.first); + if (row < 0 || size_t(row) >= owner_range.count) throw std::invalid_argument("player detail: board row outside owner squad"); + out.board = board_copy(g, out.source_manager, row); + } + } + for (int loan = 0; loan < 200; ++loan) { + const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan) * 4; + if (!g.memory.has(at + 3)) continue; + const uint32_t value = g.memory.u32(at); + if (value == 0 || (value & 0x0fff) != uint32_t(s.player_id)) continue; + out.loan_record = loan; + out.loan_duration = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) ? g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) : 0; + if (out.human_loan || out.national_mode == 0) { + out.primary_club = int((value >> 12) & 0x3ff); + out.secondary_club = int((value >> 22) & 0x3ff); + } + break; + } + if (out.human_loan && out.loan_record < 0) throw std::invalid_argument("player detail: missing packed human loan record"); + out.attributes = g.players[size_t(s.player_id)]; + out.cards = g.player_cards[size_t(s.player_id)]; + out.bonus = g.player_bonus[size_t(s.player_id)]; + out.original_name = g.player_name(s.player_id); + const uint8_t national_override = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) ? uint8_t(g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) & 10) : 0; + const bool national_label = !out.human_loan && out.national_mode != 0 && national_override == 0 && + out.attributes.nationality() + ((out.bonus & 0x80) >> 2) == 0; + for (int offer = 0; !national_label && offer < 4; ++offer) { + const uint32_t at = ::bmh::layout::OfferSlots + uint32_t(offer) * 4; + if (!g.memory.has(at + 3)) continue; + const uint32_t value = g.memory.u32(at); + if ((out.source_manager < 0 || int(value & 31) == out.source_manager) && + int((value >> 10) & 0x0fff) == s.player_id) { out.active_offer = offer; break; } + } + // ClubPlayerDetail_InvalidArgument_RuntimeField2/nationality select the label and the ResolvePendingOffer fallback, not the + // ClubPlayerDetailRedraw dispatch: any existing action remains national in modes1/2. + out.national_action_available = !out.human_loan && out.national_mode != 0 && + (national_label || out.active_offer >= 0); + return out; +} + +ClubPlayerDetailRedraw club_player_detail_redraw(const GameState& g, const ClubPlayerDetailSelection& selection, + const LeImage& original, GameRandom& game, WatcomRandom& rand, + bool portrait_available) { + ClubPlayerDetailRedraw out; + out.context = club_player_detail_context(g, selection); + std::array feature_count{}; + for (size_t i = 0; i < feature_count.size(); ++i) { + feature_count[i] = original.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + uint32_t(i)); + if (feature_count[i] == 0) throw std::invalid_argument("player detail: empty Original portrait feature range"); + } + const uint32_t named_players = original.u32(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField); + out.portrait_available = portrait_available; + if (portrait_available) { + uint32_t seed = 0x14344; + if (uint32_t(selection.player_id) < named_players) + for (size_t i = 0; i < out.context.original_name.size(); ++i) + seed += uint32_t(int32_t(int8_t(out.context.original_name[i]))) * uint32_t(i) * 10; + game.set_seed(int32_t(seed)); + game.range(0, 100); + out.portrait_base = uint8_t(game.range(0, 3)); + for (size_t i = 0; i < out.portrait_features.size(); ++i) + out.portrait_features[i] = uint8_t(game.range(0, feature_count[i] - 1)); + const uint64_t before = game.calls(); + stir_random(game, rand); + out.portrait_burn_count = uint16_t(game.calls() - before); + } + if (!out.context.human_loan) { + uint32_t value = 0, salary = 0; + market_value(g, out.context.source_slot, 0, 100, value, salary, 0, 0, rand); + out.market_value = ((value + (value >> 2)) / 10000) * 10000; + } + return out; +} + +bool club_player_detail_national_action(GameState& g, const ClubPlayerDetailSelection& selection, + WatcomRandom& rand, MinuteReport& report) { + const auto context = club_player_detail_context(g, selection); + if (!context.national_action_available) + throw std::invalid_argument("player detail: national action is not offered by Source"); + const auto national = squad_range(kNoTeam); + bool applied = true; + if (context.national_mode == 1) + applied = add_to_squad(g, context.active_manager, context.source_slot, int(national.first), rand) >= 0; + else if (!g.memory.has(::bmh::layout::MatchEventsDisabled) || g.memory.u8(::bmh::layout::MatchEventsDisabled) == 0) + applied = remove_from_seller(g, kNoTeam, selection.player_id, report); + auto_lineup(g, kNoTeam, 0xe4); // ClubPlayerDetailFromGame follows either action with this call. + return applied; +} +} // namespace bmh diff --git a/src/game/club_player_detail.hpp b/src/game/club_player_detail.hpp new file mode 100644 index 0000000..b8a5126 --- /dev/null +++ b/src/game/club_player_detail.hpp @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +enum class ClubPlayerDetailOrigin : uint8_t { squad, market_pool }; + +// The list owns all row identities. A loan row has physical_row==-1 and its +// explicit Source Career_CareerManagersEnd_RuntimeField index. rendered_row is the visible list index, which +// may differ from a filtered/sorted market-pool entry. +struct ClubPlayerDetailSelection { + int runtime_team = -1; + int player_id = -1; + int rendered_row = -1; + int physical_row = -1; + int human_loan_index = -1; + ClubPlayerDetailOrigin origin = ClubPlayerDetailOrigin::squad; + int market_pool_slot = -1; // Actual Native CareerRuntimeField+entry identity, never a visible row. +}; + +struct ClubPlayerDetailContext { + ClubPlayerDetailSelection selection; + int source_slot = -1; // Resolved Source slot; national prelude may remap any origin. + int source_manager = -1; + int primary_club = -1; + int secondary_club = -1; + int loan_duration = 0; + int loan_record = -1; + // Literal local1c from ClubPlayerDetailFromGame:0 ordinary,1 national nomination candidate, + // 2 currently selected national player. + uint8_t national_mode = 0; + int active_manager = -1; + int active_offer = -1; // ResolvePendingOffer fallback; -1 for a direct national label. + Player attributes; + uint16_t displayed_slot = 0x0fff; + uint16_t cards = 0; + uint8_t bonus = 0; + std::string original_name; + std::optional> board; + bool human_loan = false; + bool market_pool = false; + bool national_action_available = false; +}; + +// OpenTransferEditor passes actual slots CareerRuntimeField + entry (0..39) for ordinary +// transfer-market pool cards. It never turns the entry into a squad row. +constexpr int kClubPlayerDetailMarketPoolFirst = 0xb70; +constexpr int kClubPlayerDetailMarketPoolCount = 40; + +// Resolves runtime club, explicit row and Source loan/national ownership without +// changing GameState or either random generator. Invalid/stale identities throw. +ClubPlayerDetailContext club_player_detail_context(const GameState&, + const ClubPlayerDetailSelection&); + +struct ClubPlayerDetailRedraw { + ClubPlayerDetailContext context; + bool portrait_available = false; + uint8_t portrait_base = 0; + std::array portrait_features{}; + uint16_t portrait_burn_count = 0; + // Human-loan fields2..5 use Source ClubPlayerDetail_Copy_TextPointer8 and do not compute a market value. + std::optional market_value; +}; + +// One actual ClubPlayerDetailFromGame card rebuild: Copy2/21213 portrait draws, followed +// by422ac/42307/PlayerCardMarketValue market valuation. Pure renderer calls consume this owned +// result repeatedly and never draw RNG. The caller passes Source heap gate. +ClubPlayerDetailRedraw club_player_detail_redraw(const GameState&, + const ClubPlayerDetailSelection&, + const LeImage& original, + GameRandom&, WatcomRandom&, + bool portrait_available = true); + +// ClubInfoFromGame temporarily uses (bbcde!=2), then restores its caller's value. +constexpr uint8_t club_player_detail_input_mode(uint8_t prior) { return prior != 2; } + +struct MinuteReport; +// The actual Source nomination/remove button. Returns false if the national +// squad is full; the Source lineup refresh still follows the attempted add. +bool club_player_detail_national_action(GameState&, const ClubPlayerDetailSelection&, + WatcomRandom&, MinuteReport&); + +} // namespace bmh diff --git a/src/game/cup.cpp b/src/game/cup.cpp new file mode 100644 index 0000000..766843f --- /dev/null +++ b/src/game/cup.cpp @@ -0,0 +1,782 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/cup.hpp" + +#include +#include +#include +#include +#include + +#include "game/driver.hpp" +#include "game/lineup.hpp" +#include "game/matchday.hpp" +#include "game/matchday_setup.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh { + +// After the fifth indoor tournament (the end of AdvanceCup for competition 0xb): the +// field of the Masters. +// MastersQualification2: the holders of the three titles of last season (Cup_AdvanceCup_RuntimeField6[0..2], +// u16 club ids) qualify directly, each once (list Cup_MastersQualification_RuntimeField, count CupRuntimeField); +// they head the team list (Teams). +// IndoorStandingsFromGame(0): the clubs 0-39 are sorted by their Masters points (Cup_AdvanceCup_ExecutableField, +// Games descending); IndoorTournamentDraw only resets the tournament (no draw while +// CupRuntimeField != 0); the best clubs not qualified yet fill the list up to eight, which +// is shuffled (PrepareEvent, one game draw per club). The strength class Cup_AdvanceCup_RuntimeField3 +// stays that of the last tournament. +// The test "qualified yet" (MastersQualification) scans Cup_MastersQualification_RuntimeField[0 .. CupRuntimeField), but +// CupRuntimeField also counts the clubs filled in from the points list, which never enter +// Cup_MastersQualification_RuntimeField: the scan runs over the stale entries 2 and 3 (0 unless an earlier Masters +// had three direct qualifiers) and from entry 4 into the invitation counters that follow +// (MatchdaySetup_IndoorTournamentDraw_RuntimeField, u16 per club). A club whose id equals one of those values (team 0 with a +// 0 there, small ids with an invitation count) is skipped although it has the points. +// The list is not in the savegame; the replay keeps it in memory, starting at 0. +void masters_qualification(GameState& g, GameRandom& game) { + StaticMemory& mem = g.memory; + constexpr uint32_t kTeams = ::bmh::layout::Teams, kDirect = ::bmh::layout::Cup_MastersQualification_RuntimeField; + if (!mem.has(kDirect)) mem.add_block(kDirect, 8); + // MastersQualification: whether club t is in Cup_MastersQualification_RuntimeField[0 .. count) + auto listed = [&](uint16_t t, size_t count) { + for (size_t k = 0; k < count; k++) + if (mem.u16(kDirect + uint32_t(k) * 2) == t) return true; + return false; + }; + size_t count = 0; // CupRuntimeField + for (uint32_t k = 0; k < 3; k++) { + const uint16_t t = mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6 + k * 2); + if (k == 0 || !listed(t, count)) mem.set16(kDirect + uint32_t(count++) * 2, t); + } + for (size_t k = 0; k < count; k++) mem.set16(kTeams + uint32_t(k) * 2, mem.u16(kDirect + uint32_t(k) * 2)); + int16_t order[0x28]; + uint32_t points[0x28]; + for (int i = 0; i < 0x28; i++) order[i] = int16_t(i), points[i] = mem.u16(::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(i) * 2); + quicksort_by_key(order, points, 0x28); + indoor_tournament_reset(g); + for (int i = 0; count < 8; i++) { + const uint16_t t = uint16_t(order[i]); + if (!listed(t, count)) mem.set16(kTeams + uint32_t(count++) * 2, t); + } + for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams) + const uint32_t j = uint32_t(game.range(0, 7)); + const uint16_t a = mem.u16(kTeams + i * 2); + mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2)); + mem.set16(kTeams + j * 2, a); + } + for (uint32_t k = 0; k < 8; k++) { + const int manager = g.manager_of(mem.u16(kTeams + k * 2)); + if (manager < 0) continue; + post_composed(g, manager, kMastersQualificationText); // MastersQualificationText + book_money(g, manager, -150000, true, true); + } + const std::string name = message_text(g, ::bmh::layout::Cup_MastersQualification_TextPointer); + if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0); + for (size_t i = 0; i <= name.size() && i < 0x24; i++) g.tournament_name[i] = i < name.size() ? uint8_t(name[i]) : 0; +} + +namespace { + +void put32(Bytes& b, size_t o, uint32_t v) { + for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i)); +} + +// Replays of postponed league matches: cup entry type 9 plays the matches whose replay day +// (table Postponed, 40 entries of 6 bytes: day, round, league, match) is today. +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; +constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; // team list of the type 9 entry (home, away) +constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; // its result array (u16 per match) + +// AddBlock: the fixtures of today's replays; the entry's team count (+0x1a) and played +// counter (+0x1d) restart. +void prepare_replays(GameState& g, uint32_t e, int day) { + StaticMemory& mem = g.memory; + mem.add_block(kReplayFixtures, 0x50); + mem.add_block(kReplayResults, 0x12); + mem.set8(e + 0x1d, 0); + mem.set8(e + 0x1a, 0); + for (uint32_t i = 0; i < 0x12; i++) mem.set8(kReplayResults + i, 0xcc); + int k = 0; + for (int n = 0; n < 0x28; n++) { + const uint32_t at = kPostponed + uint32_t(n) * 6; + if (mem.u16(at) != day) continue; + const int league = mem.u8(at + 3); + const std::vector fx = generate_fixtures(league_table_teams(league), mem.u8(at + 2) + 1, league_matchdays(league) / 2, + league_first_team(league)); + const Fixture& f = fx.at(mem.u8(at + 4)); + mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.home)); + mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.away)); + mem.set8(e + 0x1a, uint8_t(mem.u8(e + 0x1a) + 2)); + } +} + +// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors). +void remove_competition(StaticMemory& mem, int id) { + for (int i = 0; i < 8; i++) { + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + uint32_t(i))) != id) continue; + for (int j = i; j < 7; j++) mem.set8(::bmh::layout::ActiveSelectors + uint32_t(j), mem.u8(::bmh::layout::Cup_RemoveCompetition_RuntimeField + uint32_t(j))); + mem.set8(::bmh::layout::Cup_RemoveCompetition_RuntimeField2, 0x14); + return; + } +} + +// UndoReschedule(day, 0, 0): today's replay results go back into the league result table and +// their entries are freed; then EndCompetition(9) takes the competition off the list of +// running competitions (ActiveSelectors). +void store_replays(GameState& g, int day) { + StaticMemory& mem = g.memory; + int k = 0; + for (int n = 0; n < 0x28; n++) { + const uint32_t at = kPostponed + uint32_t(n) * 6; + if (mem.u16(at) != day) continue; + const uint16_t r = mem.u16(kReplayResults + uint32_t(k++) * 2); + const uint8_t result = uint8_t(((r >> 5) << 4) | (r & 0xf)); + g.results.at(size_t(mem.u8(at + 4)) + size_t(mem.u8(at + 2)) * 10 + size_t(mem.u8(at + 3)) * 0x17C) = result; + mem.set16(at, 0); + } + remove_competition(mem, 9); +} + +// Size of the round string table a cup group plays with (pointer at entry +8). +int group_table_teams(const StaticMemory& mem, uint32_t e) { + switch (mem.pointer(e + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: return 4; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: return 6; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: return 12; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: return 16; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: return 18; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: return 20; + } + return 0; +} + +// AddResult(entry, 0): the table of a cup group from its result array (u16 per match, +// 0xCCCC = not played), indexed by draw position. Bit 7 of the flags: three points for a +// win. The ranks are sorted like the league tables (AddResult2) after the last two rounds +// and after later rounds with results. +LeagueTable group_table(const StaticMemory& mem, uint32_t e) { + LeagueTable t; + const uint8_t flags = mem.u8(e + 0x14); + const int teams = mem.u8(e + 0x1a), rounds = mem.u8(e + 0x1b), played = mem.u8(e + 0x1d); + t.size = teams; + const int three_points = flags >> 7; + int last = played - 1, before_last = 0x80; + if (last > 1) before_last = played - 2; + if (last < 0) last = 0; + sort_table(t, 0); + const uint32_t results = mem.pointer(e + 0x0c); + for (int r = 0; r < rounds; r++) { + const std::vector fx = generate_fixtures(group_table_teams(mem, e), r + 1, rounds / ((flags & 1) + 1), 0); + bool counted = false; + for (int s = 0; s < teams; s += 2) { + const uint16_t u = mem.u16(results + uint32_t(s / 2 + r * teams / 2) * 2); + if (u == 0xcccc) continue; + const uint8_t goals[2] = {uint8_t((u >> 5) & 0x1f), uint8_t(u & 0x1f)}; + const int club[2] = {fx.at(size_t(s / 2)).home, fx.at(size_t(s / 2)).away}; + add_result(t, club, goals, 3, three_points); + counted = true; + } + if (before_last == r || last == r || (last < r && counted)) sort_table(t, 0); + } + return t; +} + +// The end of a group stage (AdvanceCup): the qualifiers place by place (all group +// winners, then the runners-up, ...) until the stage's quota (+0x1f) is reached; a place +// taken only partly keeps its best clubs by the table key. Group winner and runner-up are +// noted in +0x22 / +0x24 of every group. Returns the qualifiers and in `loser_pair` the +// first two clubs of the first group ordered by the last table's second place (for a final +// of two). +std::vector group_qualifiers(StaticMemory& mem, uint32_t e, std::array& loser_pair) { + const int groups = mem.u8(e + 0x1e) & 0xF; + int quota = int8_t(mem.u8(e + 0x1f)); + std::vector teams; + std::vector keys; + LeagueTable t; + for (int place = 0; quota > 0; place++) { + for (int grp = 0; grp < groups; grp++) { + uint32_t ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + t = group_table(mem, ge); + int idx = 0; + while (idx < mem.u8(ge + 0x1a) && t.rank(idx) != place) idx++; + const uint16_t team = mem.u16(mem.pointer(ge) + uint32_t(idx) * 2); + if (place == 0) mem.set16(ge + 0x22, team); + if (place == 1) mem.set16(ge + 0x24, team); + keys.push_back(sort_key(t, idx, 0)); + teams.push_back(team); + quota--; + } + } + const uint32_t list = mem.pointer(e); + loser_pair[0] = t.rank(0) == 1 ? mem.u16(list) : mem.u16(list + 2); + const int wanted = int8_t(mem.u8(e + 0x1f)); + const int cut = wanted - wanted % groups; + for (; quota < 0; quota++) { + uint32_t worst = keys.back(); + size_t at = 0; + for (int k = cut; k < wanted; k++) + if (keys[size_t(k)] < worst) at = size_t(k), worst = keys[size_t(k)]; + if (worst < keys.back()) { + std::swap(teams.back(), teams[at]); + std::swap(keys.back(), keys[at]); + } + teams.pop_back(); + keys.pop_back(); + } + return teams; +} + +} // namespace + +LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address) { + return group_table(mem, entry_address); +} + +int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address) { + return group_table_teams(mem, entry_address); +} + +void end_competition(StaticMemory& mem, int id) { remove_competition(mem, id); } + +void prepare_friendlies(GameState& g) { + StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams) || !mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24)) return; + const int today = g.season_day(); // DaysIntoSeason + int count = 0; // local_c: two teams per friendly + for (int i = 0; i < 0x1e; i++) { + if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i) * 2)) != int16_t(today)) continue; + for (int c = 0; c < 2; c++) + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24 + uint32_t(c + count) * 2, mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i * 2 + c) * 2)); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29 + uint32_t(count >> 1) * 2, 0xcccc); + mem.set16(::bmh::layout::FriendlyDays + uint32_t(i) * 2, 0); + count += 2; + if (i < 0x1d) { + // the planned ones after it move up (the last place keeps its copy) + for (int k = i; k < 0x1d; k++) { + mem.set32(::bmh::layout::FriendlyTeams + uint32_t(k) * 4, mem.u32(::bmh::layout::Cup_PrepareFriendlies_RuntimeField + uint32_t(k) * 4)); + mem.set16(::bmh::layout::FriendlyDays + uint32_t(k) * 2, mem.u16(::bmh::layout::Cup_PrepareFriendlies_RuntimeField2 + uint32_t(k) * 2)); + } + i--; + // the planner's entry 30 counts them (two per friendly); only decreased here, + // not for the last place (as in the original) + const uint32_t planned = cup_entry_address(30) + 0x1a; + mem.set8(planned, uint8_t(mem.u8(planned) - 2)); + } + } + mem.set8(cup_entry_address(24) + 0x1a, uint8_t(count)); // today's friendlies (CupRuntimeField2) +} + +int find_cup(const StaticMemory& mem, int id) { + for (int i = 0; i < kCupEntries; i++) + if (int16_t(mem.u16(cup_entry_address(i) + 0x18)) == id) return i; + return -1; +} + +int cup_round(const StaticMemory& mem, int entry) { + const uint32_t e = cup_entry_address(entry); + const uint8_t flags = mem.u8(e + 0x14), played = mem.u8(e + 0x1d); + if (!(flags & 4)) return played; + return played / ((flags & 1) + 1); +} + +int cup_round_offset(const StaticMemory& mem, int entry, int round) { + if (round == 0) return 0; + const int teams = mem.u8(cup_entry_address(entry) + 0x1a); + return teams * 2 - teams / (1 << (round - 1)); +} + +void rebuild_replay_lists(GameState& g, uint32_t competitions) { + for (int bit = 5; bit < 0x13; bit++) { + if (!((competitions >> bit) & 1)) continue; + const int entry = find_cup(g.memory, bit - 5); + if (entry >= 0 && int16_t(g.memory.u16(cup_entry_address(entry) + 0x18)) == 9) + prepare_replays(g, cup_entry_address(entry), g.season_day()); + } +} + +void setup_cup_groups(GameState& g, int id, std::vector& groups, MinuteReport& report) { + const StaticMemory& mem = g.memory; + int entry = find_cup(mem, id); + if (entry < 0) { + report.fail("cup " + std::to_string(id) + " not in the cup table"); + return; + } + const int type = int16_t(mem.u16(cup_entry_address(entry) + 0x18)); + if (type == 9) prepare_replays(g, cup_entry_address(entry), g.season_day()); + if (type == 10) prepare_friendlies(g); + if (type > 9 && mem.u8(cup_entry_address(entry) + 0x1a) != 0) { + // AddCompetition: onto the list of running competitions (ActiveSelectors, 0x14 = free) + for (uint32_t i = 0; i < 8; i++) { + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == type) break; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(type)); + break; + } + } + } + // (the friendlies 10, the promotion play-off 0xd and the indoor tournament 0xb only join + // the running list above) + if (type > 0xb && type != 0xd && mem.u8(cup_entry_address(entry) + 0x1a) != 0) { + report.fail("cup " + std::to_string(id) + ": preparation of this competition (AddBlock/2631b/26175)"); + return; + } + // skip the stages that are completed (bounded: a broken chain would loop for ever) + for (int steps = 0; cup_round(mem, entry) >= mem.u8(cup_entry_address(entry) + 0x1b); ++steps) { + const int next = int8_t(mem.u8(cup_entry_address(entry) + 0x16)); + if (steps > 0x24 || next < 0 || next >= 0x24) { + report.fail("cup " + std::to_string(id) + ": stage chain without an open stage (entry " + std::to_string(entry) + + ", round " + std::to_string(cup_round(mem, entry)) + " of " + + std::to_string(mem.u8(cup_entry_address(entry) + 0x1b)) + ", next " + std::to_string(next) + ")"); + return; + } + entry = next; + } + const int parallel = mem.u8(cup_entry_address(entry) + 0x1e) & 0xF; + if (mem.u32(cup_entry_address(entry)) == 0) return; + for (int k = 0; k < parallel; k++) { + const uint32_t e = cup_entry_address(entry); + const uint8_t flags = mem.u8(e + 0x14); + const int teams = mem.u8(e + 0x1a); + if (teams == 0) continue; // (the original then looks at the same entry again) + MatchGroup grp; + grp.desc = group_descriptor(g, groups.size()); + grp.desc.at(0) = uint8_t(type + 1); + grp.desc.at(1) = flags; + // competition 11 is the German indoor tournament; in the English game the same entry + // is the League Cup ("Koka Kola Cup"), an ordinary cup on grass (EN Put32) + if (type == 0xb && !kEnglishCompetitions) g.indoor = true; + put32(grp.desc, 0xcc, e); + // the first leg of a two-legged knockout tie is never decided on the day + if ((flags & 5) == 5 && mem.u8(e + 0x1d) % 2 == 0) grp.desc.at(1) &= 0xF7; + int matches = 0, first = 0; // local_1c; the result index is `first` / 2 + const uint32_t list = mem.pointer(e); + if (!(flags & 4)) { + // a group: GenerateFixtures on the cup's round strings (+8), round = played + 1, the + // draw positions index the group's team list; two-legged groups play the rounds + // of the string table twice, home and away swapped + matches = teams / 2; + const int played = mem.u8(e + 0x1d); + first = uint8_t(matches * played * 2); + const int rounds = mem.u8(e + 0x1b) / ((flags & 1) + 1); + int table_teams = 0; + switch (mem.pointer(e + 8)) { + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break; + case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break; + case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break; + } + if (table_teams == 0) { + report.fail("cup group with unknown round strings"); + return; + } + for (const Fixture& f : generate_fixtures(table_teams, played + 1, rounds, 0)) { + if (int(grp.fixtures.size()) >= matches * 2) break; + grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.home) * 2))); + grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.away) * 2))); + } + // the fixtures are kept in the descriptor itself (+0x88; +0x7c points there) + for (size_t i = 0; i < grp.fixtures.size(); i++) { + grp.desc.at(0x88 + i * 2) = uint8_t(grp.fixtures[i]); + grp.desc.at(0x89 + i * 2) = uint8_t(uint16_t(grp.fixtures[i]) >> 8); + } + } else { + const int round = cup_round(mem, entry); + matches = teams / (1 << (round + 1)); + first = cup_round_offset(mem, entry, round); + for (int i = 0; i < matches * 2; i++) grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(first + i) * 2))); + } + grp.desc.at(2) = uint8_t(matches); + if (type == 0 && matches == 1) grp.desc.at(1) &= 0xFD; // the national cup final + // MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a) + for (int i = 0; i < matches * 2; i++) + for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++) + if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * 0xB0C + 0x28a) = uint8_t(i % 2); + for (int leg = 0; leg < 2; leg++) { + if (leg == 1 && !(flags & 1)) break; + const uint32_t results = mem.pointer(e + 0x0c + uint32_t(leg) * 4); + if (results == 0) continue; + grp.cup_result_address[leg] = results + uint32_t(first / 2) * 2; + std::vector& r = leg == 0 ? grp.cup_results : grp.cup_other_leg; + for (int i = 0; i < matches; i++) r.push_back(mem.u16(grp.cup_result_address[leg] + uint32_t(i) * 2)); + } + groups.push_back(grp); + entry++; + } +} + +} // namespace bmh + +namespace bmh { + +void store_cup_results(GameState& g, const MatchGroup& grp) { + if (grp.desc.at(0) == 0 || grp.cup_result_address[0] == 0) return; + for (size_t i = 0; i < grp.cup_results.size(); i++) + g.memory.set16(grp.cup_result_address[0] + uint32_t(i) * 2, grp.cup_results[i]); +} + +namespace { + +// NationalTournamentEnd, at the end of the international tournament (competition type 4): the +// honours list of the tournaments (Placements, 4 bytes per tournament, newest first) +// moves one place on and gets the first four (final winner and loser Cup_NationalTournamentEnd_RuntimeField/2dce, +// third place match Cup_NationalTournamentEnd_RuntimeField3/2df6) as national team index | 0x80. A Bundestrainer's +// association (manager slot 0 holds team 0x165) pays 400000 for taking part and the +// premium of the place (CupRuntimeField3). +void national_tournament_end(GameState& g) { + StaticMemory& mem = g.memory; + const int teams[4] = {int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField2)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField3)), + int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField4))}; + static constexpr int32_t kPremium[4] = {1000000, 600000, 300000, 200000}; // CupRuntimeField3 + if (mem.has(::bmh::layout::Placements)) + for (int i = 0x4c - 1; i >= 0; i--) mem.set8(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField5 + uint32_t(i), mem.u8(::bmh::layout::Placements + uint32_t(i))); + const bool coach = !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam; + if (coach) book_money(g, 0, -400000, true, true); + for (int i = 0; i < 4; i++) { + if (teams[i] == kNoTeam && coach) book_money(g, 0, -kPremium[i], true, true); + // (0x8a + 0x1e + 0xbd = 0x165: CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3) + if (mem.has(::bmh::layout::Placements)) mem.set8(::bmh::layout::Placements + uint32_t(i), uint8_t((teams[i] - kNoTeam) | 0x80)); + } +} + +// cup_tie on the result arrays of a stage (CupTie(results0, results1, index, flags)) +int stage_tie(const StaticMemory& mem, uint32_t e, int index) { + MatchGroup grp; + grp.desc.assign(0xd0, 0); + grp.desc.at(1) = mem.u8(e + 0x14); + const uint32_t r0 = mem.pointer(e + 0x0c), r1 = mem.pointer(e + 0x10); + grp.cup_results.assign(size_t(index) + 1, 0); + grp.cup_results[size_t(index)] = mem.u16(r0 + uint32_t(index) * 2); + if (r1 != 0) { + grp.cup_other_leg.assign(size_t(index) + 1, 0); + grp.cup_other_leg[size_t(index)] = mem.u16(r1 + uint32_t(index) * 2); + } + return cup_tie(grp, index); +} + +void swap16(StaticMemory& mem, uint32_t a, uint32_t b) { + const uint16_t x = mem.u16(a); + mem.set16(a, mem.u16(b)); + mem.set16(b, x); +} + +// Getenv(teams, offset): Source home advantage followed by an unstable-free +// descending sort on each tie's combined league weight. Kept in this Core module so +// finish_cup can expose the Original draw before the inner sort and retain its outer sort. +void order_national_cup_ties(GameState& g, int teams, int offset) { + StaticMemory& mem = g.memory; + const uint32_t list = mem.pointer(cup_entry_address(0)) + uint32_t(offset) * 2; + static constexpr uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0}; + const int lower = league_first_team(2); + std::vector weights; + weights.reserve(size_t(teams / 2)); + auto team = [&](int i) { return int16_t(mem.u16(list + uint32_t(i) * 2)); }; + auto swap_pair = [&](int a, int b) { + swap16(mem, list + uint32_t(a) * 2, list + uint32_t(b) * 2); + swap16(mem, list + uint32_t(a + 1) * 2, list + uint32_t(b + 1) * 2); + }; + for (int i = 0; i < teams; i += 2) { + if (lower <= team(i + 1) && team(i) < lower) + swap16(mem, list + uint32_t(i) * 2, list + uint32_t(i + 1) * 2); + auto league = [](int t) { return t > 0x164 ? 0 : team_league(t); }; + const int la = league(team(i)), lb = league(team(i + 1)); + weights.push_back(uint8_t(kWeight[la < 10 ? la : 9] + kWeight[lb < 10 ? lb : 9])); + } + for (int i = 0; i < teams / 2 - 1; ++i) + for (int j = i + 1; j < teams / 2; ++j) + if (weights[size_t(i)] < weights[size_t(j)]) { + std::swap(weights[size_t(i)], weights[size_t(j)]); + swap_pair(i * 2, j * 2); + } +} + +bool source_cup_draw_enabled(const StaticMemory& mem, int competition) { + // CupDrawFromGame: outside leagues 4..7 the leagues must be enabled, then the + // competition's display option must be clear. The follow-up package targets comp0. + if (competition < 4 || competition > 7) { + if (!mem.has(::bmh::layout::CompetitionSelection) || (mem.u8(::bmh::layout::CompetitionSelection) & 1) == 0) return false; + } + const uint32_t option = ::bmh::layout::LeaguePresentationOptions + uint32_t(competition + 5) * 9; + return mem.has(option) && mem.u8(option) == 0; +} + +void observe_cup_draw(const GameState& g, int entry, SeasonCupDrawPhase phase, + const SeasonCupDrawHook& hook) { + if (!hook) return; + const StaticMemory& mem = g.memory; + const uint32_t address = cup_entry_address(entry); + SeasonCupDrawEvent event; + event.phase = phase; + event.entry_address = address; + event.competition = mem.u8(address + 0x18); + event.round = cup_round(mem, entry); + event.offset = cup_round_offset(mem, entry, event.round); + event.count = size_t(mem.u8(address + 0x1a)) >> event.round; + const uint32_t first = mem.pointer(address) + uint32_t(event.offset) * 2; + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) + event.participants.push_back(mem.u16(first + uint32_t(i) * 2)); + hook(g, event); +} + +} // namespace + +void advance_cup(GameState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game, + const SeasonCupDrawHook& cup_draw, const CompetitionWinnerHook& winner_display) { + StaticMemory& mem = g.memory; + int entry = find_cup(mem, id); + if (entry < 0) return; + const int type = int16_t(mem.u16(cup_entry_address(entry) + 0x18)); + if (type == 9) return store_replays(g, g.season_day()); + // EndCompetition(type), re-added at the next preparation; the English Put32 keeps its + // League Cup (type 0xb) running like the other cups + if (type == 0xb && !kEnglishCompetitions) remove_competition(mem, type); + if (type == 10) { + // the friendlies: off the running list, the day's calendar entry masked with 0xffe + // (0x4001 becomes 0) and no teams left in today's entry (CupRuntimeField2) + remove_competition(mem, type); + const uint32_t day = ::bmh::layout::CompetitionCalendar + uint32_t(g.season_day()) * 2; + if (mem.has(day)) mem.set16(day, uint16_t(mem.u16(day) & 0xffe)); + mem.set8(cup_entry_address(24) + 0x1a, 0); + return; + } + if (type > 8 && type != 0xd && type != 0xb) { + report.fail("cup " + std::to_string(id) + ": processing of this competition (AdvanceCup)"); + return; + } + while (cup_round(mem, entry) >= mem.u8(cup_entry_address(entry) + 0x1b)) + entry = int8_t(mem.u8(cup_entry_address(entry) + 0x16)); + uint32_t e = cup_entry_address(entry); + std::vector winners, losers; + std::array loser_pair{}; + if (!(mem.u8(e + 0x14) & 4)) { + // a group stage: every group (the consecutive entries up to the one without a + // parallel link, +0x17) counts the round + for (uint32_t ge = e;; ge += kCupEntrySize) { + mem.set8(ge + 0x1d, uint8_t(mem.u8(ge + 0x1d) + 1)); + if (mem.u8(ge + 0x17) == 0) break; + } + if (mem.u8(e + 0x1d) < mem.u8(e + 0x1b)) return; + winners = group_qualifiers(mem, e, loser_pair); + } else { + const int round = cup_round(mem, entry); + const int slots = mem.u8(e + 0x1a) / (1 << round); // local_3c: teams in this round + const int first = cup_round_offset(mem, entry, round); + mem.set8(e + 0x1d, uint8_t(mem.u8(e + 0x1d) + 1)); // (unless CupRuntimeField4) + const uint32_t list = mem.pointer(e); + if ((mem.u8(e + 0x14) & 1) && mem.u8(e + 0x1d) % 2 != 0) { + // after the first leg: the pairs turn round, the results go to the second array + for (int i = 0; i < slots; i += 2) { + swap16(mem, list + uint32_t(first + i) * 2, list + uint32_t(first + i + 1) * 2); + const uint32_t k = uint32_t((first + i) / 2) * 2; + swap16(mem, mem.pointer(e + 0x0c) + k, mem.pointer(e + 0x10) + k); + } + return; + } + for (int i = 0; i < slots; i += 2) { + int t = stage_tie(mem, e, (first + i) / 2); + if (t > 1) t = 1; + winners.push_back(mem.u16(list + uint32_t(first + i + t) * 2)); + losers.push_back(mem.u16(list + uint32_t(first + i + 1 - t) * 2)); + } + } + // CupRuntimeField5[type] < 5 (national cup and the three European cups): a human manager's + // club that goes through counts one more round in his season record (ManagerOf, + // record +0xda + season * 3 + 1 national / 2 European) + if (type >= 0 && type <= 3) + for (uint16_t t : winners) { + const int manager = g.manager_of(t); + if (manager < 0) continue; + const size_t at = size_t(manager) * 0xB0C + 0xda + size_t(std::min(g.season, 0x31)) * 3 + (type > 0 ? 2 : 1); + g.manager_records.at(at) = uint8_t(g.manager_records.at(at) + 1); + } + if (cup_round(mem, entry) == mem.u8(e + 0x1b)) { + // the stage is over + if (mem.u8(e + 0x16) == 0) { + // The last stage of the competition. A single final notes its winner (+0x22) and + // loser (+0x24); competition 0xc leaves the running list. + if (winners.size() == 1) { + mem.set16(e + 0x22, winners[0]); + if (!losers.empty()) mem.set16(e + 0x24, losers[0]); + } + if (type == 0xc) remove_competition(mem, 0xc); + // CupRuntimeField5: the title of the competition (0xFF: none) + static constexpr uint8_t kTitle[14] = {1, 2, 3, 4, 5, 0xff, 6, 0xff, 8, 0xff, 0xff, 0xff, 0xff, 0xff}; + const uint8_t title = type >= 0 && type < 14 ? kTitle[type] : 0xff; + if (title != 0xff && !winners.empty()) { + if (type == 4) national_tournament_end(g); // NationalTournamentEnd + // CompetitionWinnerScreen(0, title, winner): the winner screen (unless switched off, + // Cup_AdvanceCup_RuntimeField; no draws) clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2. A human manager's club counts + // the title in his record: +0x8a6 national cup, +0x8a8 European cups. + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display) + winner_display(g, {title, winners[0]}); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + const int manager = g.manager_of(winners[0]); + if (manager >= 0 && type >= 0 && type < 4) { + const size_t at = size_t(manager) * 0xB0C + (type == 0 ? 0x8a6 : 0x8a8); + const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + g.manager_records.at(at) = uint8_t(n + 1), g.manager_records.at(at + 1) = uint8_t((n + 1) >> 8); + } + // ListTitleHoldersAf(winner, title): the list of title holders (Titles) + mem.set16(::bmh::layout::Titles + uint32_t(title) * 100 + uint32_t(std::min(g.season, 0x31)) * 2, winners[0]); + } + if (type == 0 && !winners.empty()) { + // the national cup: winner (Cup_AdvanceCup_RuntimeField5) and the previous holder + // (Career_CompetitionPointersEnglish_ExecutableField28 = Cup_AdvanceCup_RuntimeField6); Cup_AdvanceCup_RuntimeField2 = 0 if the holder won again, else 2 + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, winners[0]); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6)); + if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc); + if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField2)) mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField2, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6) == winners[0] ? 0 : 2); + } + // a linked stage (+0x17) takes the runner-up (the indoor tournament's final group + // notes it in the group for third place) + if (mem.u8(e + 0x17) != 0 && winners.size() > 1) + mem.set16(cup_entry_address(mem.u8(e + 0x17)) + 0x22, winners[1]); + // (the indoor tournament only: the English League Cup has no Masters; its winner + // would go to EN CupRuntimeField6 for Europe - not ported, see docs/fltd.md) + if (type != 0xb || kEnglishCompetitions) return; + // the indoor tournament: the four places (CupRuntimeField7 picks them from the list + // champion..fourth) earn points for the Masters (CupRuntimeField8 x strength class + // Cup_AdvanceCup_RuntimeField3, clubs of the first two leagues only), then the next tournament is + // drawn; after five tournaments the Masters follow + int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4); + if (held > 4) { + // the end of the Masters: CompetitionWinnerScreen(0, 7, winner) shows the winner (unless + // switched off, Cup_AdvanceCup_RuntimeField; no draws) and clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2; + // ListTitleHoldersAf(winner, 7) enters it in the list of title holders (Titles, + // 50 seasons per competition); Cup_AdvanceCup_RuntimeField7 = winner; a human manager's club + // gets a message and 250 000; EndCompetition removes the competition + const uint16_t winner = mem.u16(e + 0x22); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display) + winner_display(g, {7, winner}); + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + mem.set16(::bmh::layout::Titles + 7 * 100 + uint32_t(std::min(g.season, 0x31)) * 2, winner); + if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField7)) mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField7, winner); + const int manager = g.manager_of(winner); + if (manager >= 0) { + post_composed(g, manager, kMastersWinnerText); // MastersWinnerText + book_money(g, manager, -250000, true, true); + } + remove_competition(mem, type); + return; + } + static constexpr uint8_t kPlaceOrder[4] = {0, 2, 1, 3}; // CupRuntimeField7 + static constexpr uint8_t kPlacePoints[5] = {0, 6, 4, 2, 1}; // CupRuntimeField8 + for (int i = 0; i < 4 && size_t(kPlaceOrder[i]) < winners.size(); i++) { // Uint32T + const int team = winners[kPlaceOrder[i]]; + if (team < kLeagueSizes[0] + kLeagueSizes[1]) { + const uint32_t at = ::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(team) * 2; + mem.set16(at, uint16_t(mem.u16(at) + kPlacePoints[i + 1] * mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField3))); + } + } + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, uint8_t(++held)); + if (!game) { + report.fail("indoor tournament: the next draw needs the game generator"); + return; + } + if (held >= 5) { + masters_qualification(g, *game); + return; + } + indoor_tournament_draw(g, *game, rand); // (CupRuntimeField = 0) + return; + } + uint32_t last = e; + const int seeded = mem.u8(e + 0x20); + if (seeded != 0) { + // clubs seeded directly into the next stage stand before the team lists + const int groups = mem.u8(e + 0x1e) & 0xF; + int left = seeded; + for (int k = 0; left != 0; k++) + for (int grp = 0; grp < groups; grp++) { + uint32_t ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + last = ge; + if (left != 0) { + winners.push_back(mem.u16(mem.pointer(ge) - 2 - uint32_t(k) * 2)); + left--; + } + } + } + entry = int8_t(mem.u8(last + 0x16)); + e = cup_entry_address(entry); + } + const int count = int(winners.size()); // local_14 + if (mem.u8(e + 0x14) & 0x20) { + // the draw + for (int i = 0; i < count; i++) { + const int a = rand.range(0, count - 1); + const int b = rand.range(0, count - 1); + std::swap(winners[size_t(b)], winners[size_t(a)]); + } + } + if (!(mem.u8(e + 0x14) & 4)) { + // a group stage: the teams go round the groups, taken from the end + // groups of two (third place and final): the losers of the ties are added (local_88) + if (mem.u8(e + 0x1a) == 2) + for (int i = 0; i < 2 && size_t(i) < losers.size(); i++) winners.push_back(losers[size_t(i)]); + const int groups = mem.u8(e + 0x1e) & 0xF; + int left = int(winners.size()); + uint32_t ge = e; + for (int slot = 0; slot < mem.u8(e + 0x1a); slot++) + for (int grp = 0; grp < groups; grp++) { + ge = e; + while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize; + mem.set16(mem.pointer(ge) + uint32_t(slot) * 2, winners.at(size_t(--left))); + } + // AdvanceCup leaves any entrants beyond the regular group slots in the reserved + // list immediately before the final linked group's team list (entry +0x20 is the + // source guard). The Source consumes the remaining local list backwards. + if (mem.u8(ge + 0x20) != 0) { + for (int slot = 0; left > 0; ++slot) + for (int grp = 0; grp < groups; ++grp) + if (left > 0) + mem.set16(mem.pointer(ge) - 2 - uint32_t(slot) * 2, winners.at(size_t(--left))); + } + if (mem.u8(e + 0x1a) == 2) { + // the first club of this group and the second of the linked group change places + const uint32_t a = mem.pointer(e), b = mem.pointer(cup_entry_address(mem.u8(e + 0x17))) + 2; + const uint16_t x = mem.u16(a); + mem.set16(a, mem.u16(b)); + mem.set16(b, x); + } + } else { + const int next_round = cup_round(mem, entry); + const int offset = cup_round_offset(mem, entry, next_round); + const uint32_t to = mem.pointer(e); + int first_pair = 0; + if (next_round == mem.u8(e + 0x1b) && mem.u8(e + 0x20) != 0) { + first_pair = mem.u8(e + 0x20); + for (int i = 0; i < first_pair; ++i) + mem.set16(to - 2 - uint32_t(i) * 2, winners.at(size_t(i))); + } + for (int i = first_pair; i < count / 2; i++) { + mem.set16(to + uint32_t(offset + i * 2) * 2, winners[size_t(i)]); + mem.set16(to + uint32_t(offset + i * 2 + 1) * 2, winners[size_t(count - 1 - i)]); + } + if (e == cup_entry_address(0)) { + const bool eligible = type == 0 && count > 2 && (mem.u8(e + 0x14) & 0x20) != 0 && + source_cup_draw_enabled(mem, type); + if (eligible) { + // CupDrawFromGame displays the just-written shuffled order first. + observe_cup_draw(g, entry, SeasonCupDrawPhase::draw, cup_draw); + // It then performs Getenv and CupGroupOverviewEffects before returning. + order_national_cup_ties(g, count, offset); + cup_overview_effects(g); // simulation effects occur even without an observer + observe_cup_draw(g, entry, SeasonCupDrawPhase::overview, cup_draw); + } + // AdvanceCup performs this outer sort after CupDrawFromGame returns (including + // its hidden-display early return). It is idempotent after the inner sort. + order_national_cup_ties(g, count, offset); + } + } + // Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3: clubs left in the European cups + const uint32_t left_at[4] = {0, ::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3}; + if (type >= 1 && type <= 3 && mem.has(left_at[type])) mem.set8(left_at[type], uint8_t(count)); +} + +} // namespace bmh diff --git a/src/game/cup.hpp b/src/game/cup.hpp new file mode 100644 index 0000000..bac0933 --- /dev/null +++ b/src/game/cup.hpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// Cup competitions (BMH.exe V2.24 + supported rule profile patch). +// +// All cups are described by the table at CupTable: 36 entries of 0x28 bytes, one per stage +// (knockout rounds of a cup, a group of a group stage, a final, ...). Entries of the same +// cup share the id at +0x18 and are linked: +// +0x00 pointer to the team list (u16 team ids; for knockout stages the pairs of each +// round follow each other, round r starting at cup_round_offset(r)) +// +0x08 pointer to the round strings of group stages (fixture tables, see schedule.hpp) +// +0x0c pointer to the results of the first/only leg, +0x10 of the second leg (u16 per +// match: bits 0-4 away goals, 5-9 home goals, 10-15 phase; 0xCCCC not played) +// +0x14 flags: bit 0 two legs, bit 2 knockout, bit 3 the tie is decided on the day +// (extra time), bit 1 away-side penalty for league-style chances, ... +// +0x16 index of the next stage, +0x17 index of the parallel group of this stage +// +0x18 cup id (0 national cup, 1-3 European cups, 4.. further competitions) +// +0x1a number of teams, +0x1b number of rounds (legs), +0x1d legs played so far +// +0x1e low nibble: number of parallel groups, high nibble: index of this group +// Match group descriptors of cups have type = cup id + 1 and point to their table entry +// (descriptor +0xcc) instead of holding a league number. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/table.hpp" +#include "game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/state.hpp" + +namespace bmh { + +constexpr uint32_t kCupTable = ::bmh::layout::CupTable; +constexpr int kCupEntries = 36; +constexpr uint32_t kCupEntrySize = 0x28; + +inline uint32_t cup_entry_address(int index) { return kCupTable + uint32_t(index) * kCupEntrySize; } +inline int cup_entry_index(uint32_t address) { return int((address - kCupTable) / kCupEntrySize); } + +// FindCup(id, 0): the first table entry of a cup, -1 if there is none. +int find_cup(const StaticMemory& mem, int id); +// CupRound: the current round of a stage (legs played, halved for two-legged ties). +int cup_round(const StaticMemory& mem, int entry); +// CupRoundOffset: index of the first team of knockout round `round` in the team list. +int cup_round_offset(const StaticMemory& mem, int entry, int round); + +// AddResult's group-table calculation. Exposes the existing Core projection +// as a read-only value for Source overview observers and renderers. +LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address); +// Team count selected by the Source group round-schedule pointer at entry +8. +int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address); + +// SetupCupGroups: the match groups of cup `id` for today, appended to `groups`. +void setup_cup_groups(GameState& g, int id, std::vector& groups, MinuteReport& report); +// The lists of today's postponed-match replays (blocks ReplayFixtures/ReplayResults, not in the savegame) as +// the preparation of the matchday built them (prepare_replays, no draws): needed when a game +// saved at the pre-match desk of a replay day is continued. +void rebuild_replay_lists(GameState& g, uint32_t competitions); + +// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors). +void end_competition(StaticMemory& mem, int id); + +// PrepareFriendlies: the friendlies (competition 10, cup table entry 24) of today: the planned ones +// (entry 30: team pairs FriendlyTeams, season days FriendlyDays, 30 places) of this season day +// go into the day's fixture list (Career_CompetitionPointersEnglish_ExecutableField24) with an open result (0xcccc) and leave the plan. +void prepare_friendlies(GameState& g); + +} // namespace bmh + +namespace bmh { + +// Writes the results of a cup group (current leg) back into the result array in memory. +void store_cup_results(GameState& g, const MatchGroup& grp); + +// AdvanceCup for knockout stages: after a matchday of cup `id` the legs played go up; +// after the first leg of a two-legged tie the pairs turn round (home and away swapped, +// the results moved to the other leg's array). After a complete round the winners +// (cup_tie) meet in the next round - drawn if the stage has flag 0x20 (WatcomRandom) - +// or, when the stage is over, fill the next linked stage, including qualifiers and direct +// seeds for group and knockout formats; group match simulation and competition-specific +// finals remain outside this routine. +// The indoor tournament draws its next tournament at the end (game generator, `game`). +void advance_cup(GameState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr, + const SeasonCupDrawHook& cup_draw = {}, const CompetitionWinnerHook& winner = {}); + +// The end of the fifth indoor tournament: the field of the Masters (MastersQualification2, +// IndoorStandingsFromGame(0)), see cup.cpp. +void masters_qualification(GameState& g, GameRandom& game); + +} // namespace bmh diff --git a/src/game/desk.cpp b/src/game/desk.cpp new file mode 100644 index 0000000..eac27e6 --- /dev/null +++ b/src/game/desk.cpp @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/desk.hpp" + +#include +#include +#include +#include + +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/prediction.hpp" +#include "game/schedule.hpp" +#include "game/week.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecord = 0xB0C; + +// DeskRuntimeField: which of the 0x36 desk buttons exist, for the pseudo club 0x165 and per +// game mode (GameMode; the table for mode m starts at DeskRuntimeField + m * 0x36). +constexpr uint8_t kButtons[0xa2] = { + 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, + 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, + 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, + 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0}; + +int16_t rd16(const std::vector& v, size_t o) { return int16_t(v.at(o) | v.at(o + 1) << 8); } + +} // namespace + +void update_prestige(GameState& g, int manager) { + static const uint8_t kWeight[4] = {25, 50, 15, 10}; // DeskRuntimeField2 + std::vector& r = g.manager_records; + const size_t rec = size_t(manager) * kRecord; + r.at(rec + 0x211) = 0; + for (int k = 0; k < 4; k++) { + int value = 0; // local_c + switch (k) { + case 0: value = (rd16(r, rec + 0x8b2) * 100) / 0x44c; break; + case 1: value = (rd16(r, rec + 0x8aa) * 100) / 0x44c; break; + case 2: { + const int32_t balance = int32_t(r.at(rec + 0x314) | r.at(rec + 0x315) << 8 | r.at(rec + 0x316) << 16 | + uint32_t(r.at(rec + 0x317)) << 24); + value = std::clamp(balance / 50000 + 0x32, 0, 100); + break; + } + case 3: value = r.at(rec + 0x26f); break; + } + r.at(rec + 0x211) = uint8_t(r.at(rec + 0x211) + int8_t((kWeight[k] * value) / 100)); + } +} + +void save_game_draws(WatcomRandom& rand) { + const int high = rand.range(0, 0x8fff), low = rand.range(0, 0x8fff); + (void)high, (void)low; // the savegame id high * layout field + low + 1 (DeskRuntimeField3, list ab790) + rand.range(0, 0xff); // DeskRuntimeField4 = r + 'n', the check byte at the end of the file + rand.range(0, 0xff); // the key byte of the header +} + +void enter_desk(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, + const DeskAutosaveHook& autosave) { + const int team = g.manager_teams.at(size_t(manager)); + // HasNoEquivalentCondition: button states (block Desktops, 0x10 bytes per button, 0x360 per manager) + const int mode = g.memory.has(::bmh::layout::GameMode) ? g.memory.u8(::bmh::layout::GameMode) : 0; + const int mode2 = g.memory.has(::bmh::layout::CareerDuration) ? g.memory.u8(::bmh::layout::CareerDuration) : 0; + if (g.memory.has(::bmh::layout::Desktops)) + for (int b = 1; b < 0x36; b++) { + const uint32_t at = ::bmh::layout::Desktops + uint32_t(b) * 0x10 + uint32_t(manager) * 0x360 + 1; + uint8_t v = uint8_t(g.memory.u8(at) & 0xf); + // EN AlwaysHidesRecordIndoorTableIncluding always hides record 10 (IndoorTable), including + // Modus III. DE HasNoEquivalentCondition has no equivalent condition. + if ((kEnglishCompetitions && b == 10) || + (team == kNoTeam && kButtons[b] == 0) || (mode < 3 && kButtons[mode * 0x36 + b] == 0) || + (b == 0x16 && mode2 == 1 && g.date < 0x16e)) + v |= 0x10; + g.memory.set8(at, v); + } + stir_random(game, rand); // StirRandom + if (team != kNoTeam) { + std::array buf; + table_prediction(g, team, 1, buf); + } + // The autosave: at the first manager's desk a new month code (CareerSession_PairingsRuntimeDraw_ExecutableField5) counts one + // more month (DeskRuntimeField5); every Desk_EnterDesk_RuntimeField months (a setting, byte 0x61 of block + // LeaguePresentationOptions, 0 = off) the game saves itself as AUTOSAVE (MakeSavegame) + if (manager == 0) { + const int month = month_code(g.date); + if (g.autosave_month != month) g.autosave_month = month, g.autosave_months++; + } + const int period = g.memory.has(::bmh::layout::LeaguePresentationOptions) ? g.memory.u8(::bmh::layout::Desk_EnterDesk_RuntimeField) : 0; + if (period != 0 && g.autosave_months != 0 && g.autosave_months % period == 0) { + if (autosave) autosave(g, rand); + else save_game_draws(rand); // unpresented/headless legacy model + g.autosave_months = 0; + } + // (the warnings of Fill are display only) + update_prestige(g, manager); + // At the "Saisonende" desk (CareerSession_RuntimeError_RuntimeField4): the main sponsor's minimal goal (record + // +0x176, a table place). Missed: "Ihnen entgehen Sponsorgelder, da Sie das Minimalziel + // (. Platz) nicht erreicht haben." Reached: (4 - league) * 50000 per place better + // than the goal plus one (the third divisions count as the second), booked as income. + std::vector& r = g.manager_records; + const size_t rec = size_t(manager) * 0xB0C; + const int goal = r.at(rec + 0x176); + if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0 && goal != 0) { + const int place = int16_t(table_position(g, team)) + 1; // TablePosition + std::string text; + if (goal < place) { + text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer5) + format_number(g, goal, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer6); + } else { + int league = int8_t(r.at(rec + 0x210)); // CareerSession_BeginFriendlyOpponentTable_RuntimeField2 + if (league > 2) league--; + const int32_t amount = (4 - league) * 50000 * (goal - place + 1); + book_money(g, manager, -amount, true, true); // BookMoney2 with FinanceStatisticsEnabled + text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer2) + format_number(g, amount, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) + + format_number(g, place, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer3) + format_number(g, goal, 1) + + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer4); + } + post_composed(g, manager, text); + r.at(rec + 0x176) = 0; + } +} + +} // namespace bmh diff --git a/src/game/desk.hpp b/src/game/desk.hpp new file mode 100644 index 0000000..54a3d7b --- /dev/null +++ b/src/game/desk.hpp @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Entering a human manager's desk (DeskDate, the part before the desk screen). + +#include "game/random.hpp" +#include "game/state.hpp" +#include + +namespace bmh { + +// DeskDate up to the screen: the desk buttons (HasNoEquivalentCondition), the random stir when a +// screen is entered (StirRandom), the table prediction with its season goal messages +// (Void5 mode 1), the autosave every Desk_EnterDesk_RuntimeField months and the manager's +// prestige (UpdatePrestige). +// Source save operation at the desk boundary. A successful writer owns exactly +// the normal four Save draws; failure before opening the file owns none. +using DeskAutosaveHook = std::function; +void enter_desk(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, + const DeskAutosaveHook& autosave = {}); + +// The draws of saving a game (MakeSavegame): the savegame id (two WatcomRandom(0, 0x8fff)) +// and two bytes WatcomRandom(0, 0xff). Everything else the save writes is not saved itself. +void save_game_draws(WatcomRandom& rand); + +// UpdatePrestige: prestige of a human manager (record +0x211), a weighted sum of his two +// manager ratings (+0x8b2 25 %, +0x8aa 50 %), his money (15 %) and record +0x26f (10 %). +void update_prestige(GameState& g, int manager); + +} // namespace bmh diff --git a/src/game/desk_actions.cpp b/src/game/desk_actions.cpp new file mode 100644 index 0000000..e1fed7c --- /dev/null +++ b/src/game/desk_actions.cpp @@ -0,0 +1,2248 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/desk_actions.hpp" + +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/month.hpp" +#include "game/transfer_bid.hpp" +#include "game/weekly.hpp" +#include "game/week.hpp" + +namespace bmh { + +namespace { + +int32_t rd32(const std::vector& v, size_t o) { + return int32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, int32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(uint32_t(x) >> (8 * i)); +} + +// Manager record (ManagerRecords + manager * 0xb0c) offsets used here. +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kTeam = 0x290; // club of the manager (low byte used) +constexpr size_t kFocus = 0xc1; // four training camp sliders 0..15 +constexpr size_t kStays = 0x21f; // bits 0-6 stays, bit 7 "in a camp this week" +constexpr size_t kCampExpenses = 0x890; // money spent on training camps +constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; +constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; +constexpr uint32_t kFriendlyPlanEntries = 30; +constexpr uint32_t kFriendlyPlanCount = ::bmh::layout::FriendlyPlanCount; // cup entry 30, +0x1a; counts two teams per booking +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; +constexpr const char* kOrdinarySellerBoundary = + "seller is outside the Original ordinary club squads (clubs 0..137 or free agents only)"; + +// DeskActions_ConfigureTrainingCampData_RuntimeField: four quality grades per resort (1..5). The sliders use grade +// kSliderGrade[u] (DeskActionsRuntimeField), the morale grade 2 (DeskActionsRuntimeField2), the freshness grade +// 3 (DeskActionsRuntimeField3). +constexpr int kSliderGrade[4] = {1, 0, 0, 3}; +// DeskActionsRuntimeField4: step by drawn index (0..23); indices 0..7 lower a value, 8.. raise it. +constexpr int8_t kStep[24] = {-3, -2, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1, + 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5}; +// DeskActionsRuntimeField5: direction per value (familiarity counts the other way round). +constexpr int8_t kDirection[5] = {1, 1, 1, -1, 1}; + +// Scaled: a * b * 20 / 100 with unsigned byte arguments. +int scaled(int a, int b) { return (a & 0xff) * (b & 0xff) * 20 / 100; } + +FriendlyBookingQuote make_friendly_quote(const GameState& g, int manager, int opponent, + bool manager_home) { + FriendlyBookingQuote out; + out.manager = manager; + out.opponent = opponent; + out.manager_home = manager_home; + if (!g.memory.has(kFriendlyPlanCount)) { + out.status = FriendlyQuoteStatus::invalid_state; + return out; + } + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) { + out.status = FriendlyQuoteStatus::invalid_manager; + return out; + } + const int own_team = g.manager_teams[size_t(manager)]; + if (own_team < 0 || own_team >= 168 || opponent < 0 || opponent >= 168 || opponent == own_team) { + out.status = FriendlyQuoteStatus::invalid_opponent; + return out; + } + out.manager_team = own_team; + out.planner_count = g.memory.u8(kFriendlyPlanCount); + out.home_team = manager_home ? own_team : opponent; + out.away_team = manager_home ? opponent : own_team; + out.payer_manager = g.manager_of(out.home_team); + out.opponent_manager = g.manager_of(opponent); + const int first_rating = team_average(g, own_team, 0xff).value; + const int second_rating = team_average(g, opponent, 0xff).value; + const uint32_t combined = uint32_t(first_rating + second_rating) * 1000; + // DeskDate uses integer arithmetic in this order: (sum * (sum / 13000) / 7000) * 1000. + out.cost = int32_t((uint64_t(combined) * (combined / 13000) / 7000) * 1000); + out.status = FriendlyQuoteStatus::quoted; + return out; +} + +int national_opponent_manager(const GameState& g, const NationalFriendlyOwner& owner, + int opponent) { + const int ordinary = g.manager_of(opponent); + if (ordinary >= 0) return ordinary; + // FindManagerForClub's second lookup: spare manager record 4 represents the + // Bundestrainer's own association only for the first human national coach. + if (owner.manager == 0 && !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam && + g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) && int(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)) == opponent && + 5 * kRecordSize <= g.manager_records.size()) return 4; + return -1; +} + +NationalFriendlyQuote make_national_friendly_quote(const GameState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, WatcomRandom& rand) { + NationalFriendlyQuote out; + out.owner = owner; + out.watcom_seed_before = rand.seed(); + out.watcom_calls_before = rand.calls(); + out.terms.manager = owner.manager; + out.terms.manager_team = owner.runtime_team; + out.terms.opponent = opponent; + out.terms.manager_home = manager_home; + if (!g.memory.has(kFriendlyPlanCount)) { + out.terms.status = FriendlyQuoteStatus::invalid_state; + return out; + } + if (!owner.request_id || owner.menu_kind != 6 || owner.runtime_team != kNoTeam || owner.manager < 0 || + size_t(owner.manager) >= g.manager_teams.size() || + (size_t(owner.manager) + 1) * kRecordSize > g.manager_records.size() || + g.manager_teams[size_t(owner.manager)] != kNoTeam) { + out.terms.status = FriendlyQuoteStatus::invalid_manager; + return out; + } + // Page 4 cannot return Germany (0); the engine boundary repeats that gate. + if (opponent <= kNoTeam || opponent > 0x1a2 || opponent == kNoTeam) { + out.terms.status = FriendlyQuoteStatus::invalid_opponent; + return out; + } + + out.terms.planner_count = g.memory.u8(kFriendlyPlanCount); + out.terms.home_team = manager_home ? kNoTeam : opponent; + out.terms.away_team = manager_home ? opponent : kNoTeam; + out.terms.opponent_manager = national_opponent_manager(g, owner, opponent); + out.terms.payer_manager = manager_home ? owner.manager : out.terms.opponent_manager; + const auto own = team_average(g, kNoTeam, 0xff, &rand); + const auto opposing = team_average(g, opponent, 0xff, &rand); + out.own_rating = own.value; + out.opponent_rating = opposing.value; + const uint32_t combined = uint32_t(out.own_rating + out.opponent_rating) * 1000; + out.terms.cost = int32_t((uint64_t(combined) * (combined / 13000) / 7000) * 1000); + out.terms.status = FriendlyQuoteStatus::quoted; + out.watcom_seed_after = rand.seed(); + out.watcom_calls_after = rand.calls(); + return out; +} + +bool same_national_friendly_quote(const NationalFriendlyQuote& supplied, + const NationalFriendlyQuote& fresh) { + const auto& a = supplied.terms; + const auto& b = fresh.terms; + if (supplied.watcom_calls_after < supplied.watcom_calls_before || + fresh.watcom_calls_after < fresh.watcom_calls_before) return false; + return supplied.owner == fresh.owner && a.status == FriendlyQuoteStatus::quoted && + fresh.watcom_seed_before == supplied.watcom_seed_before && + fresh.watcom_seed_after == supplied.watcom_seed_after && + fresh.watcom_calls_after - fresh.watcom_calls_before == + supplied.watcom_calls_after - supplied.watcom_calls_before && + supplied.own_rating == fresh.own_rating && supplied.opponent_rating == fresh.opponent_rating && + a.manager == b.manager && a.opponent == b.opponent && a.manager_team == b.manager_team && + a.manager_home == b.manager_home && a.home_team == b.home_team && a.away_team == b.away_team && + a.payer_manager == b.payer_manager && a.opponent_manager == b.opponent_manager && + a.cost == b.cost && a.planner_count == b.planner_count; +} + +bool same_friendly_quote(const FriendlyBookingQuote& left, const FriendlyBookingQuote& right) { + return left.status == FriendlyQuoteStatus::quoted && right.status == FriendlyQuoteStatus::quoted && + left.manager == right.manager && left.opponent == right.opponent && + left.manager_team == right.manager_team && left.manager_home == right.manager_home && + left.home_team == right.home_team && left.away_team == right.away_team && + left.payer_manager == right.payer_manager && left.opponent_manager == right.opponent_manager && + left.cost == right.cost && + left.planner_count == right.planner_count; +} + +FriendlyDateStatus friendly_date_fields_unchecked(const GameState& g, + const FriendlyBookingQuote& quote, + uint16_t day) { + if (quote.status != FriendlyQuoteStatus::quoted) return FriendlyDateStatus::invalid_quote; + if (day >= 0x16e || !g.memory.has(::bmh::layout::DaysIntoSeason)) return FriendlyDateStatus::invalid_date; + // DaysIntoSeason (today); g.memory keeps only the value of the loaded savegame + if (int(day) <= g.season_day()) return FriendlyDateStatus::current_or_past; + // A friendly on the next July 1 is never dispatched: TurnDriver emits the + // season-end desk before preparing that day's competitions (is_season_end). + // CalendarCell likewise stops its calendar loop at the next July 1. The + // leap-year June 30 at season_day 365 remains playable; the same index in a + // regular year is already the next season boundary. + const uint32_t absolute_day = g.season_start + day; + if (absolute_day > 0 && month_code(absolute_day) == 7 && + month_code(absolute_day - 1) != 7) + return FriendlyDateStatus::invalid_date; + const uint32_t calendar_at = kCalendar + uint32_t(day) * 2; + if (!g.memory.has(calendar_at + 1) || !g.memory.has(kFriendlyDays + 0x3b) || + !g.memory.has(kFriendlyTeams + 0x77)) return FriendlyDateStatus::invalid_date; + const uint16_t calendar_word = g.memory.u16(calendar_at); + // DayConflict applies this gate to the selected day as well as its neighbors. + // Calendar class bits alone (0x40/0x100/0x1c0) do not authorize a choice; only the + // transient UI projection bit 15 can make such a word pass. This API never invents it. + if (calendar_word != 0 && calendar_word != 0x4001 && (calendar_word & 0x8000) == 0) + return FriendlyDateStatus::unavailable; + // The saved count is a byte and Max adds two. Refuse malformed values that + // would wrap rather than charging the manager and corrupting the planner counter. + if (quote.planner_count > 253) return FriendlyDateStatus::plan_full; + + // CalendarCell tests the selected day and neighbors with DayConflict. Its temporary + // calendar eligibility bit 15 is UI-local and absent from the saved GameState, so only + // unambiguous empty/0x4001 neighbors are accepted here. + for (int probe = std::max(0, int(day) - 1); probe <= std::min(0x16d, int(day) + 1); ++probe) { + const uint32_t probe_at = kCalendar + uint32_t(probe) * 2; + if (!g.memory.has(probe_at + 1)) return FriendlyDateStatus::invalid_date; + if (probe != day) { + const uint16_t neighbor_word = g.memory.u16(probe_at); + if (neighbor_word != 0 && neighbor_word != 0x4001) return FriendlyDateStatus::unavailable; + } + for (size_t i = 0; i < kFriendlyPlanEntries; ++i) { + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(probe)) continue; + const uint32_t teams_at = kFriendlyTeams + uint32_t(i) * 4; + const int first = int16_t(g.memory.u16(teams_at)); + const int second = int16_t(g.memory.u16(teams_at + 2)); + if (first == quote.manager_team || second == quote.manager_team || + first == quote.opponent || second == quote.opponent || + first == kNoTeam || second == kNoTeam) return FriendlyDateStatus::unavailable; + } + } + size_t insertion = 0; + size_t used_entries = 0; + for (size_t i = 0; i < kFriendlyPlanEntries; ++i) + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != 0) ++used_entries; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = g.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= day) break; + ++insertion; + } + // The original insertion would overwrite the last slot if all 30 were occupied. + // Refuse that case rather than silently dropping a previously booked fixture. + if (insertion == kFriendlyPlanEntries || used_entries == kFriendlyPlanEntries) + return FriendlyDateStatus::plan_full; + return (calendar_word & 0x01c0) != 0 ? FriendlyDateStatus::available_with_calendar_event + : FriendlyDateStatus::available; +} + +FriendlyDateStatus friendly_date_unchecked(const GameState& g, const FriendlyBookingQuote& quote, + uint16_t day) { + if (!same_friendly_quote(quote, make_friendly_quote(g, quote.manager, quote.opponent, + quote.manager_home))) + return FriendlyDateStatus::invalid_quote; + return friendly_date_fields_unchecked(g, quote, day); +} + +} // namespace + +FriendlyBookingQuote quote_friendly_match(const GameState& g, int manager, int opponent, + bool manager_home) { + return make_friendly_quote(g, manager, opponent, manager_home); +} + +NationalFriendlyQuote quote_national_friendly_match(const GameState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, WatcomRandom& rand) { + WatcomRandom staged = rand; + NationalFriendlyQuote result = make_national_friendly_quote(g, owner, opponent, + manager_home, staged); + if (result.terms.status == FriendlyQuoteStatus::quoted) rand = staged; + return result; +} + +NationalFriendlyQuote preview_national_friendly_match(const GameState& g, + const NationalFriendlyOwner& owner, int opponent, bool manager_home, + const WatcomRandom& rand) { + WatcomRandom staged = rand; + return make_national_friendly_quote(g, owner, opponent, manager_home, staged); +} + +FriendlyDateStatus national_friendly_match_date_status(const GameState& g, + const NationalFriendlyQuote& quote, const NationalFriendlyOwner& owner, + const WatcomRandom& rand, uint16_t season_day) { + if (quote.owner != owner || owner.menu_kind != 6 || owner.runtime_team != kNoTeam || + owner.manager < 0 || size_t(owner.manager) >= g.manager_teams.size() || + g.manager_teams[size_t(owner.manager)] != kNoTeam || + rand.seed() != quote.watcom_seed_after || rand.calls() != quote.watcom_calls_after) + return FriendlyDateStatus::invalid_quote; + WatcomRandom verify(quote.watcom_seed_before); + const NationalFriendlyQuote fresh = make_national_friendly_quote(g, owner, + quote.terms.opponent, quote.terms.manager_home, verify); + if (!same_national_friendly_quote(quote, fresh)) return FriendlyDateStatus::invalid_quote; + return friendly_date_fields_unchecked(g, quote.terms, season_day); +} + +NationalFriendlyBookingResult book_national_friendly_match(GameState& g, + const NationalFriendlyBookingRequest& request, const WatcomRandom& watcom, + GameRandom& game_random) { + NationalFriendlyBookingResult out; + const auto& quote = request.quote; + if (quote.terms.status != FriendlyQuoteStatus::quoted || quote.owner != request.owner || + watcom.seed() != quote.watcom_seed_after || watcom.calls() != quote.watcom_calls_after) { + out.status = quote.terms.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : quote.terms.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : quote.terms.status == FriendlyQuoteStatus::invalid_state + ? FriendlyBookingStatus::invalid_request + : FriendlyBookingStatus::stale_quote; + return out; + } + WatcomRandom verify(quote.watcom_seed_before); + const NationalFriendlyQuote fresh = make_national_friendly_quote(g, request.owner, + quote.terms.opponent, quote.terms.manager_home, verify); + if (!same_national_friendly_quote(quote, fresh)) { + out.status = fresh.terms.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : fresh.terms.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : FriendlyBookingStatus::stale_quote; + return out; + } + static_cast(out) = quote.terms; + + GameState staged = g; + const FriendlyDateStatus date_status = friendly_date_fields_unchecked( + staged, quote.terms, request.season_day); + if (date_status == FriendlyDateStatus::current_or_past || + date_status == FriendlyDateStatus::invalid_date) { + out.status = FriendlyBookingStatus::invalid_date; + return out; + } + if (date_status == FriendlyDateStatus::plan_full) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + if (date_status != FriendlyDateStatus::available && + date_status != FriendlyDateStatus::available_with_calendar_event) { + out.status = date_status == FriendlyDateStatus::invalid_quote + ? FriendlyBookingStatus::stale_quote + : FriendlyBookingStatus::date_unavailable; + return out; + } + if (out.opponent_manager >= 0 && out.opponent_manager != out.manager) { + if (!request.accept_opponent) { + out.status = FriendlyBookingStatus::opponent_declined; + return out; + } + if (request.consenting_manager != out.opponent_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + } + if (out.payer_manager >= 0) { + if (!request.accept_cost) { + out.status = FriendlyBookingStatus::declined; + return out; + } + if (request.approving_manager != out.payer_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + if (out.cost < 0 || !book_money(staged, out.payer_manager, out.cost, false, true)) { + out.status = FriendlyBookingStatus::insufficient_funds; + return out; + } + } + + size_t insertion = 0; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = staged.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= request.season_day) break; + ++insertion; + } + if (insertion == kFriendlyPlanEntries) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + for (size_t i = kFriendlyPlanEntries - 1; i > insertion; --i) { + staged.memory.set16(kFriendlyDays + uint32_t(i) * 2, + staged.memory.u16(kFriendlyDays + uint32_t(i - 1) * 2)); + staged.memory.set32(kFriendlyTeams + uint32_t(i) * 4, + staged.memory.u32(kFriendlyTeams + uint32_t(i - 1) * 4)); + } + staged.memory.set16(kFriendlyDays + uint32_t(insertion) * 2, request.season_day); + staged.memory.set16(kFriendlyTeams + uint32_t(insertion) * 4, uint16_t(out.home_team)); + staged.memory.set16(kFriendlyTeams + uint32_t(insertion) * 4 + 2, uint16_t(out.away_team)); + const uint32_t calendar_at = kCalendar + uint32_t(request.season_day) * 2; + staged.memory.set16(calendar_at, uint16_t(staged.memory.u16(calendar_at) | 0x4001)); + staged.memory.set8(kFriendlyPlanCount, + uint8_t(staged.memory.u8(kFriendlyPlanCount) + 2)); + + GameRandom staged_game = game_random; + out.national_bonus_awarded = staged_game.range(0x3c, 0x5a) < quote.opponent_rating; + if (out.national_bonus_awarded) { + const size_t record_byte = size_t(out.manager) * kRecordSize + 0x210; + if (record_byte >= staged.manager_records.size()) { + out.status = FriendlyBookingStatus::invalid_manager; + out.national_bonus_awarded = false; + return out; + } + staged.manager_records[record_byte] = uint8_t(staged.manager_records[record_byte] + 1); + } + out.status = FriendlyBookingStatus::booked; + g = std::move(staged); + game_random = staged_game; + return out; +} + +FriendlyDateStatus friendly_match_date_status(const GameState& g, + const FriendlyBookingQuote& quote, + uint16_t season_day) { + return friendly_date_unchecked(g, quote, season_day); +} + +FriendlyBookingResult book_friendly_match(GameState& g, const FriendlyBookingRequest& request) { + FriendlyBookingResult out; + const FriendlyBookingQuote fresh = make_friendly_quote(g, request.quote.manager, + request.quote.opponent, + request.quote.manager_home); + if (!same_friendly_quote(request.quote, fresh)) { + out.status = request.quote.status == FriendlyQuoteStatus::invalid_manager + ? FriendlyBookingStatus::invalid_manager + : request.quote.status == FriendlyQuoteStatus::invalid_opponent + ? FriendlyBookingStatus::invalid_opponent + : request.quote.status == FriendlyQuoteStatus::invalid_state + ? FriendlyBookingStatus::invalid_request + : FriendlyBookingStatus::stale_quote; + return out; + } + static_cast(out) = fresh; + const FriendlyDateStatus date_status = friendly_date_unchecked(g, fresh, request.season_day); + if (date_status == FriendlyDateStatus::current_or_past || + date_status == FriendlyDateStatus::invalid_date) { + out.status = FriendlyBookingStatus::invalid_date; + return out; + } + if (date_status == FriendlyDateStatus::plan_full) { + out.status = FriendlyBookingStatus::plan_full; + return out; + } + if (date_status != FriendlyDateStatus::available && + date_status != FriendlyDateStatus::available_with_calendar_event) { + out.status = date_status == FriendlyDateStatus::invalid_quote + ? FriendlyBookingStatus::stale_quote + : FriendlyBookingStatus::date_unavailable; + return out; + } + + if (out.opponent_manager >= 0 && out.opponent_manager != out.manager) { + if (!request.accept_opponent) { + out.status = FriendlyBookingStatus::opponent_declined; + return out; + } + if (request.consenting_manager != out.opponent_manager) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + } + + const int payer = out.payer_manager; + if (payer >= 0) { + if (!request.accept_cost) { + out.status = FriendlyBookingStatus::declined; + return out; + } + if (request.approving_manager != payer) { + out.status = FriendlyBookingStatus::invalid_request; + return out; + } + if (out.cost < 0 || !book_money(g, payer, out.cost, false, true)) { + out.status = FriendlyBookingStatus::insufficient_funds; + return out; + } + } + + size_t insertion = 0; + while (insertion < kFriendlyPlanEntries) { + const uint16_t planned_day = g.memory.u16(kFriendlyDays + uint32_t(insertion) * 2); + if (planned_day == 0 || planned_day >= request.season_day) break; + ++insertion; + } + for (size_t i = kFriendlyPlanEntries - 1; i > insertion; --i) { + g.memory.set16(kFriendlyDays + uint32_t(i) * 2, + g.memory.u16(kFriendlyDays + uint32_t(i - 1) * 2)); + const uint32_t dest = kFriendlyTeams + uint32_t(i) * 4; + const uint32_t src = kFriendlyTeams + uint32_t(i - 1) * 4; + g.memory.set32(dest, g.memory.u32(src)); + } + const uint32_t day_at = kFriendlyDays + uint32_t(insertion) * 2; + const uint32_t teams_at = kFriendlyTeams + uint32_t(insertion) * 4; + g.memory.set16(day_at, request.season_day); + g.memory.set16(teams_at, uint16_t(out.home_team)); + g.memory.set16(teams_at + 2, uint16_t(out.away_team)); + const uint32_t calendar_at = kCalendar + uint32_t(request.season_day) * 2; + g.memory.set16(calendar_at, uint16_t(g.memory.u16(calendar_at) | 0x4001)); + g.memory.set8(kFriendlyPlanCount, uint8_t(g.memory.u8(kFriendlyPlanCount) + 2)); + + out.status = FriendlyBookingStatus::booked; + return out; +} + +void configure_training_camp_data(GameState& g, const LeImage& exe) { + auto prices = g.training_camp_base_prices; + auto quality = g.training_camp_quality; + for (size_t resort = 0; resort < prices.size(); ++resort) { + prices[resort] = std::bit_cast(exe.u32(::bmh::layout::DeskActions_ConfigureTrainingCampData_RuntimeField2 + uint32_t(resort * 4))); + if (prices[resort] < 0) throw FormatError("training camp: negative resort base price"); + for (size_t grade = 0; grade < quality[resort].size(); ++grade) { + const uint8_t value = exe.u8(::bmh::layout::DeskActions_ConfigureTrainingCampData_RuntimeField + uint32_t(resort * 4 + grade)); + if (value < 1 || value > 5) throw FormatError("training camp: resort quality outside 1..5"); + quality[resort][grade] = value; + } + } + g.training_camp_base_prices = prices; + g.training_camp_quality = quality; +} + +int32_t training_camp_price(const GameState& g, int manager, int resort) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || resort < 0 || resort >= kTrainingCampResorts) + throw FormatError("training camp: invalid manager or resort"); + const int team = int8_t(g.manager_records.at(size_t(manager) * kRecordSize + kTeam)); + return g.training_camp_base_prices[size_t(resort)] + team_average(g, team, 0xff).players * 5000; +} + +bool set_training_camp_focus(GameState& g, int manager, const std::array& focus) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size() || + std::any_of(focus.begin(), focus.end(), [](uint8_t v) { return v > 15; }) || + focus[3] != uint8_t(15 - (unsigned(focus[0]) + focus[1] + focus[2]) / 3)) return false; + std::copy(focus.begin(), focus.end(), g.manager_records.begin() + size_t(manager) * kRecordSize + kFocus); + return true; +} + +TransferActionResult list_manager_player(GameState& g, int manager, int squad_row, WatcomRandom& rand, + MinuteReport& report) { + TransferActionResult out; + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + const SquadRange range = squad_range(g.manager_teams[size_t(manager)]); + if (squad_row < 0 || size_t(squad_row) >= range.count) return out; + const int slot = int(range.first) + squad_row; + const int player = g.squad_slots.at(size_t(slot)) & 0xfff; + if (player == 0xfff) { + out.status = TransferActionStatus::invalid_player; + return out; + } + if (!list_transfer_player(g, slot, rand, report)) { + out.status = report.unsupported ? TransferActionStatus::invalid_request : TransferActionStatus::blocked_by_board; + return out; + } + out.status = TransferActionStatus::accepted; + out.player = player; + // The transfer-list slot follows the new pool slot. The engine uses 40 entries + // for the normal list; entries 40-43 are reserved for matchday approaches. + for (int i = 0; i < 40; ++i) + if ((g.squad_slots.at(0xb70u + size_t(i)) & 0xfff) == player) { out.list_entry = i; break; } + return out; +} + +namespace { + +TransferActionResult submit_transfer_bid_impl(GameState& g, const TransferBidRequest& request, + WatcomRandom& rand, const HumanBuyerSaleHooks* source_hooks, MinuteReport* source_report) { + TransferActionResult out; + if (source_report && source_report->unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + if (request.manager < 0 || size_t(request.manager) >= g.manager_teams.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + if (request.list_entry < 0 || request.list_entry >= 40 || request.player < 0 || request.fee <= 0 || request.annual_salary <= 0 || + request.contract_years < 1 || request.contract_years > 4) return out; + const uint32_t entry = ::bmh::layout::EditorListUnsigned + uint32_t(request.list_entry) * 0x58; + const int player = g.squad_slots.at(0xb70u + size_t(request.list_entry)) & 0xfff; + if (player == 0xfff) { + out.status = TransferActionStatus::invalid_player; + return out; + } + if (player != request.player) { + out.status = TransferActionStatus::invalid_request; + return out; + } + const uint16_t seller_word = g.memory.u16(entry + 8); + if (seller_word != 0xffff && (seller_word & 0x7fff) == uint16_t(g.manager_teams[size_t(request.manager)])) return out; + const size_t rec = size_t(request.manager) * kRecordSize; + const int32_t balance = rd32(g.manager_records, rec + 0x314); + const int32_t credit = rd32(g.manager_records, rec + 0x31c); + if (int64_t(balance) + credit < request.fee) { + out.status = TransferActionStatus::blocked_by_board; + out.player = player; + return out; + } + const int buyer = g.manager_teams[size_t(request.manager)]; + const SquadRange buyer_range = squad_range(buyer); + if (squad_count(g, buyer, 3) >= int(buyer_range.count) - 1) { + out.status = TransferActionStatus::no_squad_room; + out.player = player; + return out; + } + const uint16_t team = uint16_t(buyer); + for (int b = 0; b < 4; ++b) + if (g.memory.u16(entry + uint32_t(b) * 2) == team) { + out.status = TransferActionStatus::pending; + out.player = player; + return out; + } + int bid = 0; + while (bid < 4 && g.memory.u16(entry + uint32_t(bid) * 2) != 0xffff) bid++; + if (bid == 4) { + out.status = TransferActionStatus::blocked_by_board; + return out; + } + const uint32_t fee_base = (g.memory.u32(entry + 0x2c) / 10000) * 0x30d4; + const uint32_t salary_base = ((uint32_t((request.contract_years - 1) * 20 + 100) * g.memory.u32(entry + 0x30)) / 10000) * 100; + if (fee_base == 0 || salary_base == 0) { + out.status = TransferActionStatus::offer_too_low; + out.player = player; + return out; + } + const uint32_t fee_pct = uint32_t(uint64_t(uint32_t(request.fee)) * 100 / fee_base); + const uint32_t salary_pct = uint32_t(uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base); + const int seller = seller_word == 0xffff ? -1 : int(seller_word & 0x7fff); + const int seller_manager = seller < 0 ? -1 : g.manager_of(seller); + // This opt-in adapter starts only after the existing ordinary bid quote + // qualifies. It ports the exact SettleHumanBuyerSale/Fail settlement and direct + // caller tail; the earlier SubmitTransferBidSourceHumanBuyer ProjectTransferOfferList/GameMode/W negotiation itself + // remains the existing approximation and is not claimed as Source parity. + const bool source_direct_candidate = source_hooks && seller_manager < 0 && + fee_pct >= 110 && salary_pct >= g.memory.u8(entry + 0x55); + if (source_direct_candidate) { + if (request.list_entry >= 40 || seller < 0 || (seller >= 0x8a && seller != 0x0fff) || seller == buyer || + request.manager < 0 || size_t(request.manager) >= g.manager_teams.size() || + !g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != request.manager || + source_hooks->direct_mode != HumanBuyerSaleDirectMode::ordinary_ai_purchase || + (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2) != 0) || + (source_hooks->allocator_gate != HumanBuyerSaleAllocatorGate::zero && + source_hooks->allocator_gate != HumanBuyerSaleAllocatorGate::blocked) || + !source_hooks->notice || source_hooks->before_accounts || + source_hooks->after_paid_accounts || buyer_range.count != 24) { + if (source_report) source_report->fail("SubmitTransferBidSourceHumanBuyer: unsupported human-buyer direct sale runtime/context"); + out.status = TransferActionStatus::unsupported; + out.player = player; + return out; + } + } + if (uint64_t(uint32_t(request.fee)) * 100 / fee_base < uint32_t(rand.range(0x5a, 100)) || + uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base < g.memory.u8(entry + 0x55)) { + out.status = TransferActionStatus::offer_too_low; + out.player = player; + return out; + } + const uint32_t checked_fee_pct = uint32_t(uint64_t(uint32_t(request.fee)) * 100 / fee_base); + const uint32_t checked_salary_pct = uint32_t(uint64_t(uint32_t(request.annual_salary)) * 100 / salary_base); + g.memory.set16(entry + uint32_t(bid) * 2, team); + g.memory.set32(entry + 0x1c + uint32_t(bid) * 4, uint32_t(request.fee)); + g.memory.set32(entry + 0x0c + uint32_t(bid) * 4, uint32_t(request.annual_salary)); + g.memory.set8(entry + 0x34 + uint32_t(bid), uint8_t(request.contract_years * 12)); + for (size_t i = 0; i < request.bonuses.size(); ++i) + g.memory.set8(entry + 0x38 + uint32_t(bid) * 7 + uint32_t(i), uint8_t(std::min(request.bonuses[i], 100))); + out.status = TransferActionStatus::pending; + out.player = player; + out.list_entry = request.list_entry; + out.fee = request.fee; + out.annual_salary = request.annual_salary; + if (seller_manager < 0 && checked_fee_pct >= 110 && checked_salary_pct >= g.memory.u8(entry + 0x55)) { + if (source_direct_candidate) { + HumanBuyerSaleRequest sale; + sale.list_entry = request.list_entry; + sale.bid_slot = bid; + sale.list_address = entry; + sale.source_pool_slot = 0xb70u + size_t(request.list_entry); + sale.expected_seller = seller; + sale.expected_buyer = buyer; + sale.expected_active_manager = request.manager; + sale.raw_offer_slot = -1; + if (!source_report) { + out.status = TransferActionStatus::unsupported; + return out; + } + HumanBuyerSaleHooks direct_hooks = *source_hooks; + direct_hooks.before_accounts = [&](const GameState& state, const HumanBuyerSaleRequest& context) { + // SubmitTransferBidSourceHumanBuyer enters with the active buyer and presents Original DeskActions_SubmitTransferBidImpl_ExecutableField + // before SettleHumanBuyerSale. This runs only after the shared preflight succeeds. + direct_hooks.notice(state, {request.manager, context.list_entry, -1, + ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField, message_text(state, ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField), 0x80}); + }; + const HumanBuyerSaleResult settled = settle_human_buyer_sale(g, sale, direct_hooks, rand, *source_report); + if (source_report->unsupported || settled.status == HumanBuyerSaleStatus::unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + // SubmitTransferBidSourceHumanBuyer's ordinary-list tail. No blanket bid-row or pool cleanup: + // ReleasePlayer owns matching-pool removal on an actual move. + // OpenTransferEditor established DeskActions_EditorFail_RuntimeField2=0 in the unsaved runtime before this + // ordinary AI-seller branch. Do not synthesize transient EXE globals + // in Native memory; a present marker was validated above. + // Actual EXE VA1c447/1c7c5 clears a WORD at CareerSession_BeginFriendlyOpponentTable_ExecutableField2, not a dword. + // Honor an explicitly represented full word without adding BSS. + if (g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2) && g.memory.has(::bmh::layout::DeskActions_SubmitTransferBidImpl_RuntimeField)) + g.memory.set16(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + switch (settled.status) { + case HumanBuyerSaleStatus::moved: out.status = TransferActionStatus::accepted; break; + case HumanBuyerSaleStatus::funds_refused: out.status = TransferActionStatus::insufficient_funds; break; + case HumanBuyerSaleStatus::allocator_blocked: out.status = TransferActionStatus::allocator_blocked; break; + case HumanBuyerSaleStatus::no_room: out.status = TransferActionStatus::no_squad_room; break; + case HumanBuyerSaleStatus::unsupported: out.status = TransferActionStatus::unsupported; break; + } + } else { + MinuteReport legacy_report; + if (accept_transfer_bid_immediately(g, request.list_entry, bid, rand, legacy_report)) + out.status = TransferActionStatus::accepted; + else + out.status = TransferActionStatus::no_squad_room; + } + } + return out; +} + +TransferActionResult submit_transfer_bid_source_impl(GameState& g, const TransferBidRequest& request, + WatcomRandom& rand, const HumanBuyerSaleHooks& hooks, MinuteReport& report) { + TransferActionResult out; + const auto unsupported = [&](const char* reason) { + report.fail(std::string("SubmitTransferBidSourceHumanBuyer: ") + reason); + out.status = TransferActionStatus::unsupported; + out.player = request.player; + out.list_entry = request.list_entry; + return out; + }; + if (report.unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + if (request.manager < 0 || size_t(request.manager) >= g.manager_teams.size() || + (size_t(request.manager) + 1) * kRecordSize > g.manager_records.size()) { + out.status = TransferActionStatus::invalid_manager; + return out; + } + const bool ordinary_entry = request.list_entry >= 0 && request.list_entry < 40 && + !request.poach && !request.loan_return_entry; + const bool poach_entry = request.list_entry >= 40 && request.list_entry < 44 && + request.poach && !request.loan_return_entry; + const bool return_entry = request.list_entry >= 40 && request.list_entry < 44 && + request.loan_return_entry && !request.poach; + if ((!ordinary_entry && !poach_entry && !return_entry) || + request.player < 0 || request.player >= 0x0fff || + request.fee < 0 || request.annual_salary < 0 || request.contract_years < 1 || request.contract_years > 4 || + std::any_of(request.bonuses.begin(), request.bonuses.end(), [](uint32_t value) { return value > 255; })) { + out.status = TransferActionStatus::invalid_request; + return out; + } + if (return_entry) { + const uint32_t marker_address = ::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4; + const uint32_t expected_marker = uint32_t(request.player) * 0x400u + uint32_t(request.manager); + if (!g.memory.has(marker_address + 3) || g.memory.u32(marker_address) != expected_marker) { + out.status = TransferActionStatus::invalid_request; + return out; + } + } + + const int buyer = g.manager_teams[size_t(request.manager)]; + const SquadRange buyer_range = squad_range(buyer); + const size_t buyer_record = size_t(request.manager) * kRecordSize; + if (buyer < 0 || buyer >= 90 || buyer_range.count != 24 || + (uint16_t(g.manager_records.at(buyer_record + kTeam)) | + (uint16_t(g.manager_records.at(buyer_record + kTeam + 1)) << 8)) != uint16_t(buyer)) + return unsupported("unsupported ordinary human-buyer record or 24-slot squad"); + + const uint32_t list = ::bmh::layout::EditorListUnsigned + uint32_t(request.list_entry) * 0x58; + const size_t expected_pool_slot = 0xb70u + size_t(request.list_entry); + if (!g.memory.has(list + 0x57) || request.source_slot < 0 || + size_t(request.source_slot) != expected_pool_slot || size_t(request.source_slot) >= g.squad_slots.size()) + return unsupported("missing or mismatched explicit ordinary Source pool slot"); + const int player = int(g.squad_slots[size_t(request.source_slot)] & 0x0fff); + if (player == 0x0fff || player != request.player || + int(g.squad_slots[0xb70u + size_t(request.list_entry)] & 0x0fff) != player) + return unsupported("ordinary Source list/player identity mismatch"); + + if (!g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != request.manager || + !g.memory.has(::bmh::layout::GameMode) || (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2) != 0) || + hooks.direct_mode != HumanBuyerSaleDirectMode::ordinary_ai_purchase || !hooks.notice) + return unsupported("missing ordinary-entry, active-manager, mode, or notice ownership"); + const uint8_t career_mode = g.memory.u8(::bmh::layout::GameMode); + if (career_mode < 1 || career_mode > 3) + return unsupported("unsupported saved career negotiation mode"); + + const uint16_t seller_word = g.memory.u16(list + 8); + const int seller = int(seller_word & 0x7fff); + if (seller_word == 0xffff || seller == buyer) + return unsupported("invalid ordinary seller identity"); + // Seller words name runtime squad owners (SlotTeam), not club-name + // offsets. The four foreign leagues are already runtime clubs90..137; + // season initialization can reorder SSC Neapel within that range. + // SquadRange4: clubs0..89 have24 slots, clubs90..137 have16. The + // ordinary settlement already removes players using that actual range. + // Higher club IDs have no ordinary squad; do not invent their settlement + // or let ReleasePlayer reach its missing-player/internal-error21 boundary. + if (seller != 0x0fff && seller >= 138) { + report.fail(kOrdinarySellerBoundary); + out.status = TransferActionStatus::unsupported; + out.player = player; out.list_entry = request.list_entry; + return out; + } + const int seller_manager = seller == 0x0fff ? -1 : g.manager_of(seller); + if (seller_manager >= 4 || seller_manager == request.manager) + return unsupported("unsupported seller manager identity"); + if (request.loan && seller == 0x0fff) + return unsupported("Fail/DayStepRest2: free-agent loan return destination is not represented"); + + const auto source_notice = [&](uint32_t address, std::string message, uint16_t flags) { + hooks.notice(g, {request.manager, request.list_entry, -1, address, std::move(message), flags}); + }; + if (request.fee == 0 || request.annual_salary == 0) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_TextPointer, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_TextPointer), 0x40); + out.status = TransferActionStatus::rejected; + out.player = player; out.list_entry = request.list_entry; + return out; + } + const uint32_t team = uint32_t(buyer); + int bid_slot = -1; + for (int slot = 0; slot < 4; ++slot) { + const uint16_t bidder = g.memory.u16(list + uint32_t(slot) * 2); + if (bidder == uint16_t(team)) { + if (bid_slot >= 0) return unsupported("duplicate own buyer bid words"); + bid_slot = slot; + } + } + + const auto apply_editor_values = [&](int slot, uint32_t fee) { + const uint32_t b = uint32_t(slot); + g.memory.set32(list + 0x1c + b * 4, fee); + g.memory.set32(list + 0x0c + b * 4, uint32_t(request.annual_salary)); + g.memory.set8(list + 0x34 + b, uint8_t(request.contract_years * 12) | + uint8_t(request.loan ? 0x80 : 0)); + for (size_t n = 0; n < request.bonuses.size(); ++n) + g.memory.set8(list + 0x38 + b * 7 + uint32_t(n), uint8_t(request.bonuses[n])); + }; + const uint32_t available = uint32_t(rd32(g.manager_records, buyer_record + 0x314)) + + uint32_t(rd32(g.manager_records, buyer_record + 0x31c)); + + // SubmitTransferBidSourceHumanBuyer is reached only for a new buyer word. An existing own offer is + // an editor-only update: preserve its row, apply the changed fields, and do + // not consume any qualification W values a second time. + if (bid_slot >= 0) { + const uint8_t old_term = g.memory.u8(list + 0x34 + uint32_t(bid_slot)); + if ((old_term & 0x80) != uint8_t(request.loan ? 0x80 : 0)) + return unsupported("OpenTransferEditor: changing the loan class of an existing offer is unsupported"); + const uint32_t fee = uint32_t(request.fee) <= available ? uint32_t(request.fee) : 0u; + apply_editor_values(bid_slot, fee); + if (fee == 0) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField), 0x40); + out.status = TransferActionStatus::insufficient_funds; + } else { + out.status = TransferActionStatus::pending; + } + out.player = player; out.list_entry = request.list_entry; + out.fee = int32_t(fee); out.annual_salary = request.annual_salary; + return out; + } + + for (int slot = 0; slot < 4; ++slot) { + if (g.memory.u16(list + uint32_t(slot) * 2) == 0xffff) { bid_slot = slot; break; } + } + if (bid_slot < 0) { + out.status = TransferActionStatus::blocked_by_board; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // OpenTransferEditor checks funds before entering SubmitTransferBidSourceHumanBuyer. Keep that parent gate + // ahead of the inner capacity check and qualification RNG. + if (uint32_t(request.fee) > available) { + source_notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField, message_text(g, ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField), 0x40); + out.status = TransferActionStatus::insufficient_funds; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // SubmitTransferBidSourceHumanBuyer uses equality here. Weekly decisions can legitimately move this + // count past23 while outgoing loans still reserve places (M139/#114). + // Reject the higher counts too: accepting more players would consume the + // returning player's slot and stop the next season. Keep Source's notice, + // signed manager byte and refusal before bid writes or qualification RNG. + if (!g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeFieldUnsigned + uint32_t(request.manager))) + return unsupported("missing bbcc8 buyer-manager capacity byte"); + const int capacity = int(int8_t(g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeFieldUnsigned + uint32_t(request.manager)))) + + int(uint8_t(squad_count(g, buyer, 3))); + if (capacity >= 0x17) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField, message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField), 0x40); + out.status = TransferActionStatus::no_squad_room; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + apply_editor_values(bid_slot, uint32_t(request.fee)); + g.memory.set16(list + uint32_t(bid_slot) * 2, uint16_t(team)); + const TransferBidRatingRequest rating_request{request.source_slot, request.list_entry, bid_slot, + buyer, player}; + const TransferBidRating rating = rate_transfer_bid_source(g, rating_request, rand, report); + if (!rating.supported || report.unsupported) { + out.status = TransferActionStatus::unsupported; + out.player = player; out.list_entry = request.list_entry; + return out; + } + + // Poaching (rows 40..43) is decided at once: a refusal is final (rejected), the player + // is easier to convince in mode III (W90..96 instead of W120..190), a human seller is + // asked (PresentManagerDialog: yes 0xa0, no 0) and the club refuses less often (W92..98). + if (request.poach && !hooks.confirm) return unsupported("missing poaching PresentManagerDialog question owner"); + uint32_t salary_threshold = 0; + switch (career_mode) { + case 1: salary_threshold = 100; break; + case 2: salary_threshold = uint32_t(rand.range(90, 110)); break; + case 3: salary_threshold = uint32_t(request.poach ? rand.range(90, 96) : rand.range(120, 190)); break; + default: return unsupported("unsupported saved career negotiation mode"); + } + if (rating.salary_pct < salary_threshold) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField3, g.player_name(player) + message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField3), 0x80); + out.status = request.poach ? TransferActionStatus::rejected : TransferActionStatus::pending; + out.player = player; out.list_entry = request.list_entry; + out.fee = request.fee; out.annual_salary = request.annual_salary; + return out; + } + + uint32_t fee_pct = career_mode == 3 ? rating.fee_pct : 200u; + if (request.poach && seller_manager >= 0) { + // "Sind Sie mit dem Angebot von einverstanden?" to the selling manager + const std::string question = message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer) + + format_amount(g, std::bit_cast(g.memory.u32(list + 0x1c + uint32_t(bid_slot) * 4))) + + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer2); + fee_pct = hooks.confirm(g, seller_manager, question) ? 0xa0u : 0u; + } + bool dfb_fee = false; + if (uint32_t(rand.range(92, request.poach ? 98 : 150)) >= fee_pct) { + if (request.poach) { + // The club refuses; as the player agreed, the DFB sets the fee to 188 % of his + // market value (AddToSquad with 0xbc) and the buyer may pay it (PresentManagerDialog). + uint32_t fee = 0, salary = 0; + const bool loan = (g.memory.u8(list + 0x34 + uint32_t(bid_slot)) & 0x80) != 0; + market_value(g, request.source_slot, loan ? 1 : 0, 0xbc, fee, salary, 1, 0, rand); + g.memory.set32(list + 0x1c + uint32_t(bid_slot) * 4, fee); + const std::string question = message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer4) + format_amount(g, std::bit_cast(fee)) + + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer5); + out.player = player; out.list_entry = request.list_entry; + out.fee = std::bit_cast(fee); out.annual_salary = request.annual_salary; + if (!hooks.confirm(g, request.manager, question)) { + out.status = TransferActionStatus::rejected; + return out; + } + dfb_fee = true; + } else { + if (seller_word == 0x0fff) { + source_notice(::bmh::layout::DeskActions_Unsupported_ExecutableField2, message_text(g, ::bmh::layout::DeskActions_Unsupported_ExecutableField2), 0x80); + } else { + source_notice(::bmh::layout::DeskActions_Unsupported_TextPointer3, g.club_name(seller) + message_text(g, ::bmh::layout::DeskActions_Unsupported_TextPointer3), 0x80); + } + out.status = TransferActionStatus::pending; + out.player = player; out.list_entry = request.list_entry; + out.fee = request.fee; out.annual_salary = request.annual_salary; + return out; + } + } + + out.player = player; out.list_entry = request.list_entry; + out.fee = std::bit_cast(g.memory.u32(list + 0x1c + uint32_t(bid_slot) * 4)); + out.annual_salary = request.annual_salary; + if ((hooks.allocator_gate != HumanBuyerSaleAllocatorGate::zero && + hooks.allocator_gate != HumanBuyerSaleAllocatorGate::blocked) || + hooks.before_accounts || hooks.after_paid_accounts) { + return unsupported("unknown direct allocator gate or caller-owned settlement hook"); + } + HumanBuyerSaleRequest sale; + sale.list_entry = request.list_entry; + sale.bid_slot = bid_slot; + sale.list_address = list; + sale.source_pool_slot = size_t(request.source_slot); + sale.expected_seller = seller; + sale.expected_buyer = buyer; + sale.expected_active_manager = request.manager; + sale.raw_offer_slot = -1; + sale.poach = request.poach; + sale.loan_return_entry = request.loan_return_entry; + HumanBuyerSaleHooks direct_hooks = hooks; + // "Sie einigen sich mit dem Spieler..." (DeskActions_SubmitTransferBidImpl_ExecutableField); a poached player: "Ihr erstes Angebot wird + // angenommen!" (DeskActions_SubmitTransferOfferEditorSource_ExecutableField); after the DFB fee the original goes to the accounts directly + const uint32_t accepted_text = request.poach ? ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_ExecutableField : ::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField; + if (!dfb_fee) + direct_hooks.before_accounts = [&](const GameState& state, const HumanBuyerSaleRequest& context) { + direct_hooks.notice(state, {request.manager, context.list_entry, -1, + accepted_text, message_text(state, accepted_text), 0x80}); + }; + const HumanBuyerSaleResult settled = settle_human_buyer_sale(g, sale, direct_hooks, rand, report); + if (report.unsupported || settled.status == HumanBuyerSaleStatus::unsupported) { + out.status = TransferActionStatus::unsupported; + return out; + } + + // SubmitTransferBidSourceHumanBuyer's normal direct tail: matching-pool removal is performed only + // by ReleasePlayer on a move; clear only already represented transient storage. + if (g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2) && g.memory.has(::bmh::layout::DeskActions_SubmitTransferBidImpl_RuntimeField)) g.memory.set16(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + if (g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2)) g.memory.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2, 0); + switch (settled.status) { + case HumanBuyerSaleStatus::moved: out.status = TransferActionStatus::accepted; break; + case HumanBuyerSaleStatus::funds_refused: out.status = TransferActionStatus::insufficient_funds; break; + case HumanBuyerSaleStatus::allocator_blocked: out.status = TransferActionStatus::allocator_blocked; break; + case HumanBuyerSaleStatus::no_room: out.status = TransferActionStatus::no_squad_room; break; + case HumanBuyerSaleStatus::unsupported: out.status = TransferActionStatus::unsupported; break; + } + return out; +} + +} // namespace + +std::optional transfer_market_snapshot_preview( + const GameState& g,int manager,int runtime_club,int index) { + if(manager<0||manager>=4||size_t(manager)>=g.manager_teams.size()|| + g.manager_teams[size_t(manager)]!=runtime_club||runtime_club<0||runtime_club>=138||index<0||index>=12) + return std::nullopt; + const auto owner=squad_range(runtime_club); + int count=0,ordinal=-1; + for(int i=0;i<12;++i) { + const uint32_t id=::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(i)*2,who=::bmh::layout::ClubInfo_FormatError_RuntimeField2+uint32_t(i); + if(!g.memory.has(id)||!g.memory.has(id+1)||!g.memory.has(who))return std::nullopt; + if(g.memory.u16(id)!=0x0fff&&g.memory.u8(who)==manager) { + if(i==index)ordinal=count; + ++count; + } + } + if(ordinal<0||size_t(count)>owner.count)return std::nullopt; + const int player=g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(index)*2); + if(player<0||size_t(player)>=g.players.size()||player==0x0fff)return std::nullopt; + for(int i=0;i<12;++i)if(i!=index&&g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(i)*2)==player)return std::nullopt; + const uint32_t board=::bmh::layout::ClubInfo_FormatError_RuntimeField+uint32_t(index)*0x58; + for(uint32_t n=0;n<0x58;++n)if(!g.memory.has(board+n))return std::nullopt; + int borrower=-1; + for(int i=0;i<200;++i) { + const uint32_t at=::bmh::layout::Career_RemoveJoinLoans_RuntimeField+uint32_t(i)*4; + if(!g.memory.has(at)||!g.memory.has(at+3))return std::nullopt; + const uint32_t loan=g.memory.u32(at); + if(!loan||int(loan&0xfff)!=player)continue; + // Require exactly one genuine ledger and its authenticated owner. + if(borrower!=-1||int(loan>>12&0x3ff)!=runtime_club)return std::nullopt; + borrower=int(loan>>22&0x3ff); + if(borrower<0||borrower>=138||borrower==runtime_club)return std::nullopt; + } + if(borrower<0)return std::nullopt; + const auto range=squad_range(borrower); + if(!range.count||range.first+range.count>g.squad_slots.size())return std::nullopt; + int source=-1; + for(size_t row=0;row=g.manager_teams.size()||request.manager>=4|| + !g.memory.has(::bmh::layout::ActiveManager)||g.memory.u8(::bmh::layout::ActiveManager)!=request.manager) + return unsupported("market preview: stale active manager"); + const size_t record=size_t(request.manager)*kRecordSize; + if(record+0x318>g.manager_records.size()||request.runtime_club<0|| + g.manager_teams[size_t(request.manager)]!=request.runtime_club) + return unsupported("market preview: stale runtime club/record"); + const uint16_t native_team=uint16_t(g.manager_records[record+0x290])| + uint16_t(uint16_t(g.manager_records[record+0x291])<<8); + if(native_team!=request.runtime_club) + return unsupported("market preview: Native record disagrees with runtime club"); + if(request.source_slot<0||size_t(request.source_slot)>=g.squad_slots.size()|| + request.expected_player<0||request.expected_player==0x0fff|| + size_t(request.expected_player)>=g.players.size()|| + (g.squad_slots[size_t(request.source_slot)]&0x0fff)!=request.expected_player) + return unsupported("market preview: stale Source player/slot"); + if(request.purchase) { + if(request.snapshot_index!=-1)return unsupported("market preview: snapshot is not a purchase row"); + if(request.source_slot<2928||request.source_slot>=2928+40) + return unsupported("market preview: purchase is not an ordinary market row"); + const uint32_t seller_at=::bmh::layout::EditorList+uint32_t(request.source_slot-2928)*0x58+8; + if(!g.memory.has(seller_at)||!g.memory.has(seller_at+1)) + return unsupported("market preview: missing Source seller word"); + const uint16_t raw=g.memory.u16(seller_at); + // Existing UI's -1 identity represents only an observed FULLWORD FFFF. + // Canonical0FFF remains4095; a high-bit seller flag is masked by18c22. + const int seller=raw==0xffff?-1:int(raw&0x7fff); + if(request.seller!=seller)return unsupported("market preview: stale Source seller"); + } else if(request.snapshot_index>=0) { + const auto identity=transfer_market_snapshot_preview(g,request.manager,request.runtime_club,request.snapshot_index); + if(!identity||identity->source_slot!=request.source_slot||identity->player!=request.expected_player||request.seller!=request.runtime_club) + return unsupported("market preview: stale lender snapshot/borrower identity"); + // Intentional correction: Original19c1c/TransferMarketScreen uses the displayed tail + // row, which can be empty0FFF. Value the authenticated borrower slot + // with the unchanged42307 formula; do not synthesize a Native slot. + } else { + if(request.snapshot_index!=-1)return unsupported("market preview: invalid snapshot index"); + if(request.seller!=request.runtime_club||request.runtime_club>=138) + return unsupported("market preview: outgoing club is not an ordinary owned squad"); + const auto range=squad_range(request.runtime_club); + if(range.count==0||range.first+range.count>g.squad_slots.size()|| + !g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+23)||!g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2+11)) + return unsupported("market preview: incomplete outgoing/loan roster"); + size_t borrowed=0; + for(uint32_t n=0;n<12;++n) { + if(!g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2)||!g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2+1)||!g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2+n)) + return unsupported("market preview: incomplete outgoing loan ownership"); + if(g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+n*2)!=0x0fff&&g.memory.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2+n)==request.manager)++borrowed; + } + if(borrowed>range.count||size_t(request.source_slot)=range.first+range.count-borrowed) + return unsupported("market preview: outgoing Source slot is not an ordinary roster row"); + } + // EXE raw23922 (MarketValue): NEG32; 2393a IDIV ecx(10000), + // 2393c IMUL32, 23959 ADD32. Salary is computed before42307's loan quarter. + market_value(g,request.source_slot,int(request.loan),100,result.fee,result.salary,1,0,rand); + const uint32_t sign=request.purchase?0u-result.fee:result.fee; + const int32_t quotient=std::bit_cast(sign)/10000; + const uint32_t rounded=uint32_t(quotient)*10000u; + result.delta=std::bit_cast(rounded); + result.projected_balance=std::bit_cast(std::bit_cast(rd32(g.manager_records,record+0x314))+rounded); + result.supported=true; + return result; +} + +namespace { +constexpr uint32_t kEditorList=::bmh::layout::EditorList; +uint32_t editor_list(const TransferOfferEditorRequest& r){return kEditorList+uint32_t(r.list_entry)*0x58;} +int editor_slot(const GameState& g,const TransferOfferEditorRequest& r) { + const uint32_t at=editor_list(r); + for(int slot=0;slot<4;++slot) { + const uint16_t buyer=g.memory.u16(at+uint32_t(slot)*2); + if(buyer==0xffff||buyer==r.runtime_club)return slot; + } + return -1; +} +std::string editor_identity(const GameState& g,const TransferOfferEditorRequest& r) { + if(r.manager<0||r.manager>=4||size_t(r.manager)>=g.manager_teams.size()|| + !g.memory.has(::bmh::layout::ActiveManager)||g.memory.u8(::bmh::layout::ActiveManager)!=r.manager|| + g.manager_teams[size_t(r.manager)]!=r.runtime_club||r.runtime_club<0||r.runtime_club>=138) + return "OpenTransferEditor: stale ordinary manager/team"; + const size_t record=size_t(r.manager)*kRecordSize; + if(record+kRecordSize>g.manager_records.size()|| + (uint16_t(g.manager_records[record+0x290])|uint16_t(uint16_t(g.manager_records[record+0x291])<<8))!=r.runtime_club) + return "OpenTransferEditor: inconsistent Native buyer record"; + // ordinary rows 0..39; poaching uses the special rows 40..43 (and only those) + const bool ordinary_entry = r.list_entry >= 0 && r.list_entry < 40 && !r.poach && !r.loan_return_entry; + const bool poach_entry = r.list_entry >= 40 && r.list_entry < 44 && r.poach && !r.loan_return_entry; + const bool return_entry = r.list_entry >= 40 && r.list_entry < 44 && r.loan_return_entry && !r.poach; + if((!ordinary_entry&&!poach_entry&&!return_entry)||r.source_slot!=2928+r.list_entry|| + size_t(r.source_slot)>=g.squad_slots.size()||r.expected_player<0||r.expected_player>=0x0fff|| + size_t(r.expected_player)>=g.players.size()|| + int(g.squad_slots[size_t(r.source_slot)]&0x0fff)!=r.expected_player) + return "OpenTransferEditor: stale ordinary Source slot/player"; + if(return_entry) { + const uint32_t marker=::bmh::layout::OfferSlots+uint32_t(r.list_entry-40)*4; + if(!g.memory.has(marker+3)||g.memory.u32(marker)!=uint32_t(r.expected_player)*0x400u+uint32_t(r.manager)) + return "OpenTransferEditor: stale DayStepRest2 return-offer marker"; + } + const uint32_t list=editor_list(r); + for(uint32_t n=0;n<0x58;++n)if(!g.memory.has(list+n))return "OpenTransferEditor: missing Native list row"; + if(g.memory.u16(list+8)!=r.expected_seller_word)return "OpenTransferEditor: stale raw seller word"; + const int seller=int(r.expected_seller_word&0x7fff); + if(r.expected_seller_word==0xffff||seller==r.runtime_club) + return "OpenTransferEditor: targeted/invalid seller is outside ordinary editor"; + if(seller!=0x0fff&&seller>=138)return kOrdinarySellerBoundary; + // OpenTransferEditor: the original refuses a loan from a free agent (seller 0x0fff) with the message + // DeskActionsRuntimeField6 (SDLFlushEvents3) - a rule of the game, not a gap: the code names it + if(r.loan&&r.expected_seller_word==0x0fff)return "free_agent_loan_refused"; + const int seller_manager=seller==0x0fff?-1:g.manager_of(seller); + if(seller_manager>=0) { + const auto range=squad_range(seller);bool found=false; + if(range.first+range.count>g.squad_slots.size())return "OpenTransferEditor: incomplete human seller squad"; + for(size_t n=range.first;n3) + return "OpenTransferEditor: missing supported Native negotiation mode"; + return {}; +} +TransferOfferEditorState editor_fail(TransferOfferEditorState state,const std::string& reason) { + state.supported=false;state.reason=reason;return state; +} +TransferOfferInputProfile editor_profile(uint32_t minimum,uint32_t encoded_max,uint32_t first, + uint32_t multiplier,uint32_t increment,uint32_t initial,uint32_t text) { + TransferOfferInputProfile p;p.minimum=minimum;p.currency=(encoded_max&0x40000000u)!=0; + uint32_t maximum=encoded_max^(p.currency?0x40000000u:0u); + const auto signed32=[](uint32_t n){return std::bit_cast(n);}; + if(signed32(maximum)99999999)initial=99999999; + if(signed32(maximum)>99999999)maximum=99999999; + if(signed32(maximum)=0&&g.memory.u16(list+uint32_t(state.bid_slot)*2)==state.request.runtime_club; + state.editable=state.bid_slot>=0; + if(state.editable) { + const uint32_t bid=uint32_t(state.bid_slot); + state.fee=g.memory.u32(list+0x1c+bid*4);state.salary=g.memory.u32(list+0x0c+bid*4); + state.term=g.memory.u8(list+0x34+bid);state.years=uint8_t((int(state.term&127)-1)/12+1); + for(uint32_t n=0;n<7;++n)state.bonuses[n]=g.memory.u8(list+0x38+bid*7+n); + } else {state.years=1;state.term=0;state.fee=0;state.salary=0;state.bonuses.fill(0);} + // RateTransferBidSource: explicit byte years and Source32 unsigned products. + const uint8_t year_index=state.editable?uint8_t((int(state.term&127)-1)/12):uint8_t(1); + state.asking_fee=(g.memory.u32(list+0x2c)/10000u)*12500u; + if(state.editable&&(state.term&128))state.asking_fee>>=2; + state.asking_salary=((uint32_t(year_index)*20u+100u)*g.memory.u32(list+0x30)/10000u)*100u; + state.money_profiles[0]=editor_profile(0,state.asking_fee*2u|0x40000000u,0xffffffffu,10000,0,state.asking_fee,::bmh::layout::DeskActions_EditorProject_RuntimeField); + state.money_profiles[1]=editor_profile(0,0x40030d40u,0xffffffffu,500,0,state.asking_salary,::bmh::layout::DeskActions_EditorProject_ExecutableField2); + state.mode3_profiles[0]=editor_profile(1,state.request.loan?2u:4u,1,1,1,state.years,::bmh::layout::DeskActions_EditorProject_ExecutableField); + for(size_t n=0;n<7;++n) { + const uint32_t first=n<3?1u:50u-uint32_t(n-3)*10u; + state.mode3_profiles[n+1]=editor_profile(0,n<3?20u:1000u,first,1,first,state.bonuses[n],::bmh::layout::Contracts_Out_ExecutableField4+uint32_t(n)*4); + } + for(uint32_t n=0;n<0x58;++n)state.native_entry[n]=g.memory.u8(list+n); +} +std::string editor_current(const GameState& g,const TransferOfferEditorState& state) { + if(!state.supported||state.closed)return "OpenTransferEditor: editor is unsupported or closed"; + if(const auto reason=editor_identity(g,state.request);!reason.empty())return reason; + if(g.memory.u8(::bmh::layout::GameMode)!=state.mode)return "OpenTransferEditor: Native mode changed during editor"; + const uint32_t list=editor_list(state.request); + for(uint32_t n=0;n<0x58;++n)if(g.memory.u8(list+n)!=state.native_entry[n])return "OpenTransferEditor: stale Native editor entry"; + return {}; +} +void editor_initialize_empty_bid(GameState& g,TransferOfferEditorState& state) { + if(state.initialized_empty_bid||state.bid_slot<0)return; + const uint32_t list=editor_list(state.request),bid=uint32_t(state.bid_slot); + if(g.memory.u16(list+bid*2)!=0xffff)return; + // BacLocalFirstEmptySelectionOnlyBuyer..1bac7 / local1c: the first empty selection only. Buyer and + // all seven stale bonus bytes remain unchanged; loan is the original action. + g.memory.set32(list+0x0c+bid*4,0);g.memory.set32(list+0x1c+bid*4,0); + g.memory.set8(list+0x34+bid,uint8_t(24|(state.request.loan?128:0))); + state.initialized_empty_bid=true; +} +void editor_quote(const GameState& g,TransferOfferEditorState& state,WatcomRandom& rand) { + uint32_t fee=0,salary=0; + market_value(g,state.request.source_slot,int(state.quote_loan),state.percent,fee,salary,state.years,0,rand); + // OpenBMH deviates from the original: uses the supported transfer-fee arithmetic and designated set-piece fields. +// supported rule profile MakeRequest ->PlayerCardMarketValue ->422f4; unsigned Source32 fee addition. + state.quoted_fee=((fee+(fee>>2))/10000u)*10000u; + state.quoted_salary=(salary/100u)*100u; +} +} // namespace + +TransferOfferEditorState open_transfer_offer_editor_source(GameState& g, + const TransferOfferEditorRequest& request,GameRandom& game,WatcomRandom& rand) { + TransferOfferEditorState state;state.request=request;state.quote_loan=request.loan; + if(const auto reason=editor_identity(g,request);!reason.empty())return editor_fail(state,reason); + state.bid_slot=editor_slot(g,request); + if(state.bid_slot!=request.expected_bid_slot)return editor_fail(state,"OpenTransferEditor: stale first free/own raw bid slot"); + if(!g.memory.has(::bmh::layout::CareerSession_Invalid_RuntimeField2)||!g.memory.has(::bmh::layout::DeskActions_OpenTransferOfferEditorSource_RuntimeField)) + return editor_fail(state,"OpenTransferEditor: missing saved opening G seed"); + state.mode=g.memory.u8(::bmh::layout::GameMode);state.supported=true; + // InitializesOrdinaryEntryMarkerAbsenceStaysAbsent initializes the ordinary entry marker; absence stays absent. + if(g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2))g.memory.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2,0); + const uint32_t seed=g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2); + // CareerSession_Save_RuntimeField is the Source transient G state, not a serialized Native field. + // GameRandom owns it; mirror only when an explicit memory block exists. + const bool mirror_g=g.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)&&g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField); + game.set_seed(std::bit_cast(seed)); + if(mirror_g)g.memory.set32(::bmh::layout::CareerSession_Save_RuntimeField,seed); + state.percent=uint8_t(game.range(92,108)); + if(mirror_g)g.memory.set32(::bmh::layout::CareerSession_Save_RuntimeField,std::bit_cast(game.seed())); + editor_initialize_empty_bid(g,state); + editor_project(g,state); + state.player_info_selection=transfer_offer_player_info_selection_source(g,state); + editor_quote(g,state,rand);return state; +} +TransferOfferEditorState edit_transfer_offer_editor_source(GameState& g, + const TransferOfferEditorState& previous,const TransferOfferEditorEvent& event,GameRandom& game,WatcomRandom& rand) { + (void)game;auto state=previous; + if(const auto reason=editor_current(g,state);!reason.empty())return editor_fail(state,reason); + if(event.field==TransferOfferEditorField::toggle_quote_loan) { + state.quote_loan=!state.quote_loan;editor_quote(g,state,rand);return state; + } + const unsigned field=unsigned(event.field); + if(!state.editable||field>unsigned(TransferOfferEditorField::bonus6))return editor_fail(state,"OpenTransferEditor: noneditable field"); + if(field>=2&&state.mode!=3)return editor_fail(state,"OpenTransferEditor: years/bonuses require Native mode3"); + if(!event.accepted) { + if(field<2)editor_quote(g,state,rand); + return state; + } + const auto& profile=field<2?state.money_profiles[field]:state.mode3_profiles[field-2]; + if(!profile.supported||event.valueprofile.maximum) + return editor_fail(state,"OpenTransferEditor: calculator value outside Source field bounds"); + const uint32_t list=editor_list(state.request),bid=uint32_t(state.bid_slot); + if(field==0)g.memory.set32(list+0x1c+bid*4,event.value); + else if(field==1)g.memory.set32(list+0x0c+bid*4,event.value); + else if(field==2)g.memory.set8(list+0x34+bid,uint8_t(event.value*12u)|(state.request.loan?128:0)); + else {const unsigned bonus=field-3;g.memory.set8(list+0x38+bid*7+bonus,uint8_t(bonus<3?event.value:event.value/5u));} + editor_project(g,state);editor_quote(g,state,rand);return state; +} +TransferOfferEditorState resume_transfer_offer_team_info_source(GameState& g, + const TransferOfferEditorState& previous,WatcomRandom& rand) { + auto state=previous; + if(!state.supported||state.closed)return editor_fail(state,"OpenTransferEditor: closed TeamInfo owner"); + if(const auto reason=editor_identity(g,state.request);!reason.empty())return editor_fail(state,reason); + if(g.memory.u8(::bmh::layout::GameMode)!=state.mode)return editor_fail(state,"OpenTransferEditor: TeamInfo changed Native negotiation mode"); + // 1c18b rescans first FFFF/own. local1c may still be zero after an + // existing-own/read-only opening; initialize the first empty choice once. + // This resume never repeats CareerSession_Save_RuntimeField reset or the opening G draw. + state.bid_slot=editor_slot(g,state.request); + state.request.expected_bid_slot=state.bid_slot; + editor_initialize_empty_bid(g,state); + editor_project(g,state);editor_quote(g,state,rand); + return state; +} +ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const GameState& g, + const TransferOfferEditorState& owner) { + if(const auto reason=editor_current(g,owner);!reason.empty())throw std::invalid_argument(reason); + const auto& r=owner.request; + const int seller=r.expected_seller_word&0x7fff; + // Literal68ca0 count and Nationalcoach special owner4, independently of + // buyer identity and of any retained pending offer for the same player. + if(!g.memory.has(::bmh::layout::ManagerCount))throw std::invalid_argument("OpenTransferEditor: missing Source manager count"); + const size_t count=g.memory.u8(::bmh::layout::ManagerCount); + if(count>4||count>g.manager_teams.size())throw std::invalid_argument("OpenTransferEditor: invalid Source manager count"); + int manager=-1; + for(size_t m=0;mg.manager_records.size())throw std::invalid_argument("OpenTransferEditor: missing Nationalcoach owner4"); + if((uint16_t(g.manager_records[at])|(uint16_t(g.manager_records[at+1])<<8))==seller)manager=4; + } + if(owner.player_info_selection) { + const auto& retained=*owner.player_info_selection; + if(retained.player_id!=r.expected_player|| + (manager<0&&!r.poach&&(retained.origin!=ClubPlayerDetailOrigin::market_pool||retained.market_pool_slot!=r.source_slot))|| + ((manager>=0||r.poach)&&(retained.origin!=ClubPlayerDetailOrigin::squad||retained.runtime_team!=seller))) + throw std::invalid_argument("OpenTransferEditor: retained local40 owner changed"); + (void)club_player_detail_context(g,retained); + return retained; + } + ClubPlayerDetailSelection selection; + selection.player_id=r.expected_player; + // A poaching row (40..43) is outside the market pool the detail screen knows; its + // player is shown at his club instead, like a managed seller's player. + if(manager<0&&!r.poach&&!r.loan_return_entry) { + selection.origin=ClubPlayerDetailOrigin::market_pool; + selection.market_pool_slot=r.source_slot; + selection.rendered_row=r.list_entry; // Logical entry only; Native identity is explicit. + } else { + const auto range=squad_range(seller); + if(range.first+range.count>g.squad_slots.size())throw std::invalid_argument("OpenTransferEditor: truncated seller squad"); + size_t row=0; + while(rowavailable) { + notice(::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField);if(own_exists){g.memory.set32(list+0x1c+bid*4,0);editor_project(g,state);} + action.status=TransferActionStatus::insufficient_funds;return result; + } + if(own_exists) {action.status=TransferActionStatus::pending;action.fee=std::bit_cast(state.fee);action.annual_salary=std::bit_cast(state.salary);return result;} + // Editor writes may retain Source stale bonuses outside their interactive + // controls; qualifier reads all7 as bytes, without a <=100 clamp. + TransferBidRequest request;request.manager=state.request.manager;request.list_entry=state.request.list_entry; + request.player=state.request.expected_player;request.source_slot=state.request.source_slot; + request.fee=int32_t(state.fee);request.annual_salary=int32_t(state.salary);request.contract_years=state.years; + request.poach=state.request.poach;request.loan=state.request.loan; + request.loan_return_entry=state.request.loan_return_entry; + for(size_t n=0;n<7;++n)request.bonuses[n]=state.bonuses[n]; + bool entered_accounts=false;const auto present=hooks.notice;auto owned=hooks; + owned.notice=[present,&entered_accounts](const GameState& staged,const HumanBuyerSaleNotice& event){ + if(event.source_text_address==::bmh::layout::DeskActions_SubmitTransferBidImpl_ExecutableField||event.source_text_address==::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_ExecutableField)entered_accounts=true; + present(staged,event); + }; + action=submit_transfer_bid_source_human_buyer(g,request,rand,owned,report); + if(report.unsupported||action.status==TransferActionStatus::unsupported)return unsupported(report.reason.empty()?"OpenTransferEditor: unsupported Source qualification/settlement":report.reason); + if(entered_accounts)state.closed=true; + // a poaching offer is decided at once: SubmitTransferBidSourceHumanBuyer never leaves a pending row behind + else if(state.request.poach&&action.status!=TransferActionStatus::insufficient_funds&& + action.status!=TransferActionStatus::no_squad_room)state.closed=true; + else if(action.status==TransferActionStatus::pending){editor_project(g,state);editor_quote(g,state,rand);} + return result; +} + +TransferActionResult submit_transfer_bid(GameState& g, const TransferBidRequest& request, WatcomRandom& rand) { + return submit_transfer_bid_impl(g, request, rand, nullptr, nullptr); +} + +TransferActionResult submit_transfer_bid_source_human_buyer(GameState& g, + const TransferBidRequest& request, WatcomRandom& rand, + const HumanBuyerSaleHooks& hooks, MinuteReport& report) { + return submit_transfer_bid_source_impl(g, request, rand, hooks, report); +} + +TrainingCampBookingBlock training_camp_booking_block(const GameState& g, int manager) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) + return TrainingCampBookingBlock::invalid_request; + const uint8_t stays = g.manager_records.at(size_t(manager) * kRecordSize + kStays); + if (stays & 0x80) return TrainingCampBookingBlock::booked_this_week; + if ((stays & 0x7f) >= 3) return TrainingCampBookingBlock::visit_limit; + return TrainingCampBookingBlock::none; +} + +bool book_training_camp(GameState& g, int manager, int resort, WatcomRandom& rand) { + if (resort < 0 || resort >= kTrainingCampResorts || + training_camp_booking_block(g, manager) != TrainingCampBookingBlock::none) return false; + const int32_t cost = training_camp_price(g, manager, resort); + if (!book_money(g, manager, cost, false)) return false; + const size_t rec = size_t(manager) * kRecordSize; + wr32(g.manager_records, rec + kCampExpenses, rd32(g.manager_records, rec + kCampExpenses) + cost); + uint8_t& stays = g.manager_records.at(rec + kStays); + stays = uint8_t((stays + 1) | 0x80); + training_camp_effect(g, manager, resort, rand); + return true; +} + +void training_camp_effect(GameState& g, int manager, int resort, WatcomRandom& rand) { + const size_t rec = size_t(manager) * kRecordSize; + const int team = int8_t(g.manager_records.at(rec + kTeam)); + const auto& grade = g.training_camp_quality[size_t(resort)]; + + // Morale (bits 0-5) + 12 * grade * 20 %, clamped to 0..0x2f (ClampSignedWord with a word + // sum of the sign extended byte); the flag bits 6-7 are kept. + uint8_t& tm = g.team_morale.at(size_t(team)); + const int morale = std::clamp(int(tm & 0x3f) + int(int16_t(scaled(12, grade[2]))), 0, 0x2f); + tm = uint8_t((tm & 0xc0) | uint8_t(morale)); + + // The maximum step of each value: the slider times its grade (stored as a byte), the + // familiarity one 7 lower, the freshness one from the fourth grade. + int8_t delta[5]; + for (int u = 0; u < 4; u++) + delta[u] = int8_t(scaled(g.manager_records.at(rec + kFocus + size_t(u)), grade[kSliderGrade[u]])); + delta[3] = int8_t(delta[3] - 7); + delta[4] = int8_t(scaled(12, grade[3])); + + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t id = g.squad_slots.at(s) & 0x0fff; + if (id == kEmptySlot) continue; + Player& p = g.players.at(id); + uint8_t* board = &g.tactics.at(size_t(manager) * 0x840 + (s - range.first) * 0x58); + // Chance to train: 100 % up to age 29 (raw age 13), then 10 % less per year - + // computed in 8 bits, so from raw age 25 on the value wraps above 100 (always). + const uint8_t age = uint8_t(p.w364 >> 21 & 0x1f); + const uint8_t chance = age < 14 ? 100 : uint8_t(100 - uint8_t((age - 14) * 10)); + int8_t v[5] = {int8_t(p.w35c >> 14 & 0x7f), int8_t(p.w35c >> 7 & 0x7f), int8_t(p.w35c & 0x7f), + int8_t(board[0xf]), int8_t(board[0xe] & 0x3f)}; + for (int i = 0; i < 5; i++) { + const int lo = delta[i] < 0 ? 0 : 8; + if (rand.range(0, 100) <= chance) { + // values below 83..87 (88 in the better resorts 6 and 7) can still improve + const int limit = rand.range(0x53, 0x57) + (resort >= 6 ? 1 : 0); + if (v[i] < limit) { + const int k = rand.range(lo, delta[i] + 8); + v[i] = int8_t(v[i] + int8_t(kStep[k] * kDirection[i])); + } + } + v[i] = std::clamp(v[i], 0, 0x63); // Int8T + } + p.w35c = (p.w35c & 0xffe00000u) | uint32_t(v[0]) << 14 | uint32_t(v[1]) << 7 | uint32_t(v[2]); + board[0xf] = uint8_t(v[3]); + board[0xe] = uint8_t((board[0xe] & 0xc0) | std::min(uint8_t(v[4]), 0x3f)); + } +} + +} // namespace bmh + +namespace bmh { + +namespace { + +constexpr size_t kStockSize = 0x5c; +constexpr size_t kMoney = 0x314, kCredit = 0x31c, kStockBalance = 0x324; + +uint16_t rd16(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16(std::vector& v, size_t o, int x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} + +} // namespace + +int max_shares_to_buy(const GameState& g, int manager, int stock) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + const int price = rd16(g.stocks, s + 0x4e); + int n = (rd32(g.manager_records, rec + kMoney) + rd32(g.manager_records, rec + kCredit)) / price; + const int held = rd16(g.stocks, s + 0x50 + size_t(manager) * 2); + if (n + held > 9999) n = 9999 - held; + return n; +} + +bool buy_shares(GameState& g, int manager, int stock, int count) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + // the paid amounts of all shares the manager holds (computed when the screen is drawn) + int32_t portfolio = 0; + for (int k = 0; k < kStocks; k++) + if (rd16(g.stocks, size_t(k) * kStockSize + 0x50 + size_t(manager) * 2) != 0) + portfolio += rd32(g.stocks, size_t(k) * kStockSize + 4 + size_t(manager) * 4); + int32_t cost = rd16(g.stocks, s + 0x4e) * count; + if (portfolio + cost >= rd32(g.manager_records, rec + kMoney) / 20) return false; + wr16(g.stocks, s + 0x50 + size_t(manager) * 2, rd16(g.stocks, s + 0x50 + size_t(manager) * 2) + count); + cost += cost * 15 / 1000; + book_money(g, manager, cost, false); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) - cost); + const size_t paid = s + 4 + size_t(manager) * 4; + wr32(g.stocks, paid, rd32(g.stocks, paid) + cost); + return true; +} + +void sell_shares(GameState& g, int manager, int stock, int count) { + const size_t rec = size_t(manager) * kRecordSize, s = size_t(stock) * kStockSize; + const size_t paid = s + 4 + size_t(manager) * 4, held = s + 0x50 + size_t(manager) * 2; + wr32(g.stocks, paid, int32_t(uint32_t(rd32(g.stocks, paid)) - uint32_t(rd32(g.stocks, paid)) / rd16(g.stocks, held) * uint32_t(count))); + wr16(g.stocks, held, rd16(g.stocks, held) - count); + const int32_t income = count * rd16(g.stocks, s + 0x4e); + book_money(g, manager, -income, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) + income); +} + +int stock_tip(GameState& g, int manager, int stock, WatcomRandom& rand) { + const size_t s = size_t(stock) * kStockSize; + int tip = int(g.stocks.at(s + 0x16)) - 1; + if (g.stocks.at(s + 0x59) < 3) tip = 0; + const int value = int16_t(uint32_t(rd32(g.stocks, s)) / 100); + const int price = rd16(g.stocks, s + 0x4e); + if (price < value - 5) tip++; + if (value + 5 < price) tip--; + if (price < value - 30) tip = 2; + if (value + 30 < price) tip = -2; + tip += 2; + if (rand.range(0, 2) == 0) tip += rand.range(0, 2) * 2 - 2; + tip = std::clamp(tip, 0, 4); + book_money(g, manager, 5000, true, true); + return tip; +} + +} // namespace bmh + +namespace bmh { + +namespace { + +// StadiumPriceTable: base price of the 14 periphery objects. +constexpr int32_t kPeripheryPrice[14] = {2500000, 1700000, 2200000, 1000000, 1100000, 1500000, 280000, + 280000, 280000, 280000, 350000, 350000, 350000, 350000}; +// CareerSession_DispatchStadium_RuntimeField2[object * 5]: construction time in days. +constexpr uint8_t kPeripheryDays[14] = {45, 30, 28, 40, 30, 20, 6, 6, 6, 6, 5, 5, 5, 5}; + +} // namespace + +int construction_price_percent(const GameState& g, int manager, GameRandom& game) { + game.set_seed(int32_t(g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + const int r = int16_t(rd16(g.manager_records, size_t(manager) * kRecordSize + 0x8b4)) / 100; + return 100 - game.range(r, r + 5); +} + +int32_t periphery_offer(const GameState& g, int object, GameRandom& game) { + game.set_seed(int32_t(g.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + for (int i = 0; i < object; i++) game.range(0, 100); + const int percent = game.range(0x55, 0x73); + return kPeripheryPrice[object] * percent / 1000000 * 10000; +} + +bool pay_construction(GameState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + const size_t rec = size_t(manager) * kRecordSize; + uint8_t& share = g.manager_records.at(rec + 0x171); + ConstructionNotice details{manager, ConstructionNoticeKind::InsufficientFunds, price, 0, 0}; + if (sponsor && price <= uint32_t(rd32(g.manager_records, rec + kMoney)) && share != 0) { + if (price < uint32_t((share >> 2) & 7) * 0x4f588 + 26000) { + details.kind = ConstructionNoticeKind::SponsorContribution; + details.percent = int((share >> 5) + 3) * 10; + details.subsidy = uint32_t(details.percent) * price / 100; + } else { + details.kind = ConstructionNoticeKind::SponsorExploited; + const int sponsor_roll = rand.range(2, 4); + details.percent = sponsor_roll * 5; + details.subsidy = price * uint32_t(sponsor_roll) * 5 / 100; + } + price -= details.subsidy; + // PayConstruction waits for the notice while the original share is still live. + if (notice) notice(g, details); + share = 0; + } + const bool paid = book_money(g, manager, int32_t(price), false, true); + if (!paid && notice) { + details.kind = ConstructionNoticeKind::InsufficientFunds; + notice(g, details); + } + return paid; +} + +bool build_periphery(GameState& g, int manager, int object, uint32_t price, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + if (!pay_construction(g, manager, price, true, rand, notice)) return false; + g.manager_records.at(size_t(manager) * kRecordSize + 0x1e + size_t(object)) = kPeripheryDays[object]; + return true; +} + +StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand) { + const int percent = rand.range(6, 14); // PrepareStandBlockOffer draws before showing the prompt + const uint32_t offered = uint32_t(uint64_t(base_price) * uint32_t(100 + percent) / 100); + return {percent, base_price, offered, base_price, construction_days, construction_days, + StandBlockOfferDecision::Pending}; +} + +bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand) { + if (offer.decision != StandBlockOfferDecision::Pending || offer.percent < 6 || offer.percent > 14 || + offer.construction_days < 0 || offer.construction_days > 255 || offer.base_days != offer.construction_days || + offer.price != offer.base_price || offer.offered_price != + uint32_t(uint64_t(offer.base_price) * uint32_t(100 + offer.percent) / 100)) + return false; + offer.decision = accept ? StandBlockOfferDecision::Accepted : StandBlockOfferDecision::Declined; + if (!accept) return false; + offer.price = offer.offered_price; + offer.construction_days -= rand.range(offer.base_days >> 3, offer.base_days >> 1); + return true; +} + +std::vector stadium_investment_options_source( + const GameState& g, int manager, StadiumInvestment investment, int construction_percent, + const StadiumInvestmentConstants& constants) { + const size_t choice = size_t(investment); + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size() || choice >= 8 || + construction_percent < 1 || construction_percent > 427 || constants.price[choice] == 0 || + constants.weeks[choice] == 0) + throw FormatError("stadium: invalid investment owner or constants"); + const size_t rec = size_t(manager) * kRecordSize; + if (g.manager_teams[size_t(manager)] < 0 || g.manager_teams[size_t(manager)] == kNoTeam || + rd16(g.manager_records, rec + kTeam) != g.manager_teams[size_t(manager)]) + throw FormatError("stadium: investment manager club differs from record"); + if (g.manager_records.at(rec + 0x2c + choice) != 0) return {}; + const uint8_t status = g.manager_records.at(rec + 0x3c + choice); + const uint8_t current = status & 7; + const bool binary = choice == 2 || choice == 3; + if ((status & 0xf0) != 0) + throw FormatError("stadium: invalid idle investment level"); + std::vector options; + // ConstructionPricePercent tests the masked terminal level, but its ordinary sprite loop + // starts at the full raw byte. Bit3 cannot manufacture an ordinary tier. + const int count = binary ? (current == 2 ? 0 : 1) : std::max(0, std::min(3, 4 - int(status))); + for (int increment = 1; increment <= count; ++increment) { + // ConstructionPricePercent uses a 32-bit multiplied base/discount before /100. The + // authentic tables fit; reject malformed constants instead of wrapping. + const uint64_t multiplied = uint64_t(constants.price[choice]) * uint32_t(increment) * + uint32_t(construction_percent); + if (multiplied > std::numeric_limits::max()) + throw FormatError("stadium: investment price multiplication overflows Native width"); + const uint32_t price = uint32_t(multiplied) / 100; + if (price == 0 || price > uint32_t(INT32_MAX)) + throw FormatError("stadium: investment price outside Native money range"); + options.push_back({status, current, uint8_t(increment), uint8_t((status + increment) & 7), + price, constants.weeks[choice]}); + } + return options; +} + +bool build_stadium_investment_source(GameState& g, int manager, StadiumInvestment investment, + int construction_percent, const StadiumInvestmentConstants& constants, + const StadiumInvestmentOption& option, const StandBlockOffer& offer, WatcomRandom& rand, + const ConstructionNoticeHook& notice) { + try { + const auto options = stadium_investment_options_source( + g, manager, investment, construction_percent, constants); + if (std::find(options.begin(), options.end(), option) == options.end() || + offer.base_price != option.base_price || offer.base_days != option.base_weeks || + offer.percent < 6 || offer.percent > 14 || + offer.offered_price != uint32_t(uint64_t(option.base_price) * uint32_t(100 + offer.percent) / 100) || + offer.price > uint32_t(INT32_MAX) || + (offer.decision != StandBlockOfferDecision::Declined && + offer.decision != StandBlockOfferDecision::Accepted) || + (offer.decision == StandBlockOfferDecision::Declined && + (offer.price != option.base_price || offer.construction_days != option.base_weeks)) || + (offer.decision == StandBlockOfferDecision::Accepted && + (offer.price != offer.offered_price || + offer.construction_days > option.base_weeks - (option.base_weeks >> 3) || + offer.construction_days < option.base_weeks - (option.base_weeks >> 1)))) + return false; + } catch (const FormatError&) { + return false; + } + // Validation alone converts FormatError into a neutral rejection. Payment + // and presenters must remain outside that catch so App can roll back a + // failed notice instead of acknowledging it as a consumed funds refusal. + if (!pay_construction(g, manager, offer.price, true, rand, notice)) return false; + const size_t rec = size_t(manager) * kRecordSize; + const size_t choice = size_t(investment); + g.manager_records.at(rec + 0x2c + choice) = uint8_t(offer.construction_days); + uint8_t& status = g.manager_records.at(rec + 0x3c + choice); + status = uint8_t(status | uint8_t(uint8_t(status + option.increment) << 4)); + return true; +} + +} // namespace bmh + +namespace bmh { + +namespace { + +constexpr uint32_t kFundBlock = ::bmh::layout::FundBlock; +constexpr uint32_t kFundSize = 0x1c; +constexpr size_t kAssets = 0x30c, kDeposit = 0x318; + +} // namespace + +int max_fund_units(const GameState& g, int manager, int fund) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t price = g.memory.u32(e); + const uint32_t each = price + price / 20; + // (unsigned division as in the original) + int n = int(uint32_t(rd32(g.manager_records, rec + kMoney) + rd32(g.manager_records, rec + kCredit)) / each); + const int room = 10 - g.memory.u16(e + 0x14 + uint32_t(manager) * 2); + return std::min(n, room); +} + +int32_t buy_fund_units(GameState& g, int manager, int fund, int count, GameRandom& game) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t held = e + 0x14 + uint32_t(manager) * 2, paid = e + 4 + uint32_t(manager) * 4; + auto add = [&](size_t o, int32_t x) { wr32(g.manager_records, rec + o, rd32(g.manager_records, rec + o) + x); }; + g.memory.set16(held, uint16_t(g.memory.u16(held) + count)); + const int32_t price = int32_t(g.memory.u32(e)); + const int32_t fee = count * price / 20; + add(kAssets, fee); + const int32_t total = count * price + fee; + add(kStockBalance, -total); + book_money(g, manager, total, false); + add(kAssets, count * price / 9); + g.memory.set32(paid, g.memory.u32(paid) + uint32_t(total)); + if (fund == 0) return 0; + const int32_t surcharge = count * game.range(price / 40, price / 10); + add(kAssets, surcharge); + book_money(g, manager, surcharge, true); + return surcharge; +} + +void sell_fund_units(GameState& g, int manager, int fund, int count) { + const size_t rec = size_t(manager) * kRecordSize; + const uint32_t e = kFundBlock + uint32_t(fund) * kFundSize; + const uint32_t held = e + 0x14 + uint32_t(manager) * 2, paid = e + 4 + uint32_t(manager) * 4; + g.memory.set32(paid, g.memory.u32(paid) - g.memory.u32(paid) / g.memory.u16(held) * uint32_t(count)); + g.memory.set16(held, uint16_t(g.memory.u16(held) - count)); + const int32_t income = count * int32_t(g.memory.u32(e)); + book_money(g, manager, -income, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) + income); + wr32(g.manager_records, rec + kAssets, rd32(g.manager_records, rec + kAssets) - income / 9); +} + +void move_to_deposit(GameState& g, int manager, int32_t amount) { + const size_t rec = size_t(manager) * kRecordSize; + book_money(g, manager, amount, true); + wr32(g.manager_records, rec + kStockBalance, rd32(g.manager_records, rec + kStockBalance) - amount); + wr32(g.manager_records, rec + kDeposit, rd32(g.manager_records, rec + kDeposit) + amount); +} + +void open_lineup_screen(GameState& g, int manager) { + uint8_t* rec = &g.manager_records.at(size_t(manager) * 0xb0c); + if ((rec[0xb0a] | rec[0xb0b] << 8) == 0x3253) return; + for (int i = 0; i < 4; i++) rec[0xafc + i] = 0; + rec[0xb08] = 0, rec[0xb09] = 0, rec[0xb0a] = 0x53, rec[0xb0b] = 0x32; +} + +} // namespace bmh + +namespace bmh { + +bool submit_pools_coupon(GameState& g, int manager, uint32_t stake, + const std::array& tips) { + constexpr size_t kRecord = 0xb0c; + constexpr uint32_t kCoupon = ::bmh::layout::Coupon; + constexpr uint32_t kCouponBytes = 5 * 0x14; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecord > g.manager_records.size() || + !g.memory.has(kCoupon) || !g.memory.has(kCoupon + kCouponBytes - 1) || + !g.memory.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField) || !g.memory.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + 43) || + g.memory.u8(::bmh::layout::CareerSession_DispatchToto_RuntimeField) != 11 || + (stake != 0 && (stake < 10'000 || stake > 400'000)) || + std::any_of(tips.begin(), tips.end(), [](uint8_t pick) { return pick > 2; })) + return false; + + const uint32_t at = kCoupon + uint32_t(manager) * 0x14; + g.memory.set32(at, stake); + for (uint32_t i = 0; i < tips.size(); ++i) g.memory.set8(at + 8 + i, tips[i]); + return true; +} + +} // namespace bmh + +namespace bmh { +namespace { +constexpr size_t kAdRecord = 0xb0c; +constexpr size_t kAdPool = 0x8cc; +constexpr size_t kAdContracts = 0xa34; +constexpr size_t kAdContractBytes = 0x0c; +constexpr uint32_t kAdGroupId = ::bmh::layout::AdGroupId; + +uint32_t ad_u32(const std::vector& bytes, size_t at) { + return uint32_t(bytes.at(at)) | uint32_t(bytes.at(at + 1)) << 8 | + uint32_t(bytes.at(at + 2)) << 16 | uint32_t(bytes.at(at + 3)) << 24; +} + +bool ad_replaceable(const std::vector& bytes, size_t at) { + return ad_u32(bytes, at) == 0 || (bytes.at(at + 6) & 0x80) != 0; +} + +struct AdBoardOrder { + std::array keys{}; + std::array slots{}; +}; + +void ad_sort_order(AdBoardOrder& order, int first, int count) { + while (count > 1) { + const uint32_t pivot = order.keys[size_t(first + count / 2)]; + int left = -1; + int right = count; + do { + do { ++left; } while (pivot < order.keys[size_t(first + left)]); + do { --right; } while (order.keys[size_t(first + right)] < pivot); + if (right <= left) break; + std::swap(order.keys[size_t(first + left)], order.keys[size_t(first + right)]); + std::swap(order.slots[size_t(first + left)], order.slots[size_t(first + right)]); + } while (true); + ad_sort_order(order, first, left); + first += left; + count -= left; + } +} + +AdBoardOrder ad_board_order(const std::vector& records, size_t rec) { + AdBoardOrder order; + for (int slot = 0; slot < 14; ++slot) { + const size_t at = rec + kAdContracts + size_t(slot) * kAdContractBytes; + const uint32_t amount = ad_u32(records, at); + uint32_t key = amount; + if (amount != 0 && (records.at(at + 6) & 0x80) == 0) key += 1'000'000u; + order.keys[size_t(slot)] = key; + order.slots[size_t(slot)] = slot; + } + ad_sort_order(order, 0, 14); + return order; +} + +bool ad_manager_record_valid(const GameState& g, int manager) { + return manager >= 0 && size_t(manager) < g.manager_teams.size() && + (size_t(manager) + 1) * kAdRecord <= g.manager_records.size(); +} + +bool ad_extension_requires_unsupported_prompt(const std::vector& records, size_t at) { + return (records.at(at + 6) & 0x7f) != 0 && records.at(at + 5) == 0; +} +} // namespace + +AdvertisingOfferList advertising_offers(const GameState& g, int manager, int display_slot) { + AdvertisingOfferList out; + out.manager = manager; + out.display_slot = display_slot; + if (!ad_manager_record_valid(g, manager)) { + out.status = AdvertisingOfferStatus::invalid_manager; + return out; + } + if (display_slot < 0 || display_slot > 15) { + out.status = AdvertisingOfferStatus::invalid_display_slot; + return out; + } + const size_t rec = size_t(manager) * kAdRecord; + const int pool_group = display_slot < 14 ? 0 : (display_slot == 14 ? 1 : 2); + const int pool_count = pool_group == 2 ? 5 : 10; + const size_t pool = rec + kAdPool + size_t(pool_group) * 0x78; + if (pool + size_t(pool_count) * kAdContractBytes > rec + kAdRecord || + rec + kAdContracts + 16 * kAdContractBytes > g.manager_records.size()) { + out.status = AdvertisingOfferStatus::invalid_state; + return out; + } + out.pool_group = pool_group; + + const AdBoardOrder order = ad_board_order(g.manager_records, rec); + if (display_slot < 14) { + out.contract_slot = order.slots[size_t(display_slot)]; + for (int slot = 0; slot < 14; ++slot) { + const size_t at = rec + kAdContracts + size_t(slot) * kAdContractBytes; + if (ad_replaceable(g.manager_records, at)) ++out.free_boards; + } + } else { + out.contract_slot = display_slot; + } + const size_t target = rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(target), kAdContractBytes, + out.contract_bytes.begin()); + if (ad_extension_requires_unsupported_prompt(g.manager_records, target)) { + out.status = AdvertisingOfferStatus::unsupported_extension; + } else if (pool_group != 0 && !ad_replaceable(g.manager_records, target)) { + out.status = AdvertisingOfferStatus::unavailable_target; + } else { + out.status = AdvertisingOfferStatus::available; + } + + bool has_offer = false; + const bool selected_target_available = pool_group == 0 || + ad_replaceable(g.manager_records, rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes); + for (int raw = 0; raw < pool_count; ++raw) { + const size_t at = pool + size_t(raw) * kAdContractBytes; + AdvertisingOfferCandidate candidate; + candidate.raw_slot = raw; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(at), kAdContractBytes, + candidate.bytes.begin()); + candidate.monthly_amount = ad_u32(g.manager_records, at); + candidate.bundle_units = g.manager_records.at(at + 4); + candidate.months = g.manager_records.at(at + 5); + candidate.sponsor_id = g.manager_records.at(at + 7); + candidate.present = candidate.monthly_amount != 0; + has_offer |= candidate.present; + const bool valid_offer = candidate.sponsor_id < 10 && + (pool_group != 0 || (candidate.bundle_units > 0 && candidate.bundle_units <= 14)); + const bool enough_boards = pool_group != 0 || candidate.bundle_units <= out.free_boards; + bool insertion_targets_available = true; + if (pool_group == 0 && candidate.bundle_units <= 14) { + for (int i = 0; i < candidate.bundle_units; ++i) { + const int raw_target = order.slots[size_t(13 - i)]; + const size_t at = rec + kAdContracts + size_t(raw_target) * kAdContractBytes; + if (!ad_replaceable(g.manager_records, at)) insertion_targets_available = false; + } + } + candidate.can_accept = candidate.present && valid_offer && enough_boards && + selected_target_available && insertion_targets_available && + out.status == AdvertisingOfferStatus::available; + out.offers.push_back(candidate); + } + if (out.status == AdvertisingOfferStatus::available && !has_offer) + out.status = AdvertisingOfferStatus::no_offers; + return out; +} + +AdvertisingOfferResult accept_advertising_offer(GameState& g, + const AdvertisingOfferRequest& request) { + AdvertisingOfferResult result; + result.manager = request.manager; + result.display_slot = request.display_slot; + result.contract_slot = request.contract_slot; + result.raw_slot = request.raw_slot; + if (!ad_manager_record_valid(g, request.manager)) { + result.status = AdvertisingOfferStatus::invalid_manager; + return result; + } + const AdvertisingOfferList view = advertising_offers(g, request.manager, request.display_slot); + if (view.status != AdvertisingOfferStatus::available) { + result.status = view.status; + return result; + } + if (view.contract_slot != request.contract_slot || request.contract_slot < 0 || + request.contract_slot > 15 || request.raw_slot < 0) { + result.status = AdvertisingOfferStatus::invalid_request; + return result; + } + const size_t rec = size_t(request.manager) * kAdRecord; + const size_t target = rec + kAdContracts + size_t(request.contract_slot) * kAdContractBytes; + const auto order = ad_board_order(g.manager_records, rec); + if (request.display_slot < 14 && order.slots[size_t(request.display_slot)] != request.contract_slot) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + if (request.expected_contract != [&] { + std::array bytes{}; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(target), kAdContractBytes, bytes.begin()); + return bytes; + }()) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + + const int pool_group = view.pool_group; + const int pool_count = pool_group == 2 ? 5 : 10; + if (request.raw_slot >= pool_count) { + result.status = AdvertisingOfferStatus::invalid_request; + return result; + } + const size_t pool = rec + kAdPool + size_t(pool_group) * 0x78 + size_t(request.raw_slot) * kAdContractBytes; + std::array offer{}; + std::copy_n(g.manager_records.begin() + std::ptrdiff_t(pool), kAdContractBytes, offer.begin()); + if (offer != request.expected_offer || ad_u32(g.manager_records, pool) == 0) { + result.status = AdvertisingOfferStatus::stale_offer; + return result; + } + const uint8_t sponsor = offer[7]; + const uint8_t bundle = offer[4]; + if (sponsor >= 10 || (pool_group == 0 && (bundle == 0 || bundle > 14))) { + result.status = AdvertisingOfferStatus::malformed_offer; + return result; + } + if (pool_group == 0 && bundle > view.free_boards) { + result.status = AdvertisingOfferStatus::insufficient_boards; + return result; + } + if (pool_group == 0 && !g.memory.has(kAdGroupId)) { + result.status = AdvertisingOfferStatus::invalid_state; + return result; + } + + // Prepare all writes in owned bytes first. Source AdBoardOrder sorts descending and + // moves option-marked rows without the +1,000,000 active-contract priority. + std::vector next = g.manager_records; + { + const auto staged_order = ad_board_order(next, rec); + std::array, 14> sorted{}; + for (int i = 0; i < 14; ++i) { + const size_t from = rec + kAdContracts + size_t(staged_order.slots[size_t(i)]) * kAdContractBytes; + std::copy_n(next.begin() + std::ptrdiff_t(from), kAdContractBytes, sorted[size_t(i)].begin()); + } + for (int i = 0; i < 14; ++i) { + const size_t to = rec + kAdContracts + size_t(i) * kAdContractBytes; + std::copy(sorted[size_t(i)].begin(), sorted[size_t(i)].end(), next.begin() + std::ptrdiff_t(to)); + } + } + const size_t sorted_target = rec + kAdContracts + size_t(request.display_slot) * kAdContractBytes; + if (pool_group != 0 && !ad_replaceable(next, sorted_target)) { + result.status = AdvertisingOfferStatus::unavailable_target; + return result; + } + if (ad_extension_requires_unsupported_prompt(next, sorted_target)) { + result.status = AdvertisingOfferStatus::unsupported_extension; + return result; + } + if (pool_group == 0) { + const uint8_t group_id = g.memory.u8(kAdGroupId); + for (int i = 0; i < bundle; ++i) { + const size_t to = rec + kAdContracts + size_t(13 - i) * kAdContractBytes; + if (!ad_replaceable(next, to)) { + result.status = AdvertisingOfferStatus::unavailable_target; + return result; + } + std::copy(offer.begin(), offer.end(), next.begin() + std::ptrdiff_t(to)); + next[to + 4] = group_id; + } + std::vector before_resort = next; + const auto final_order = ad_board_order(before_resort, rec); + std::array, 14> sorted{}; + for (int i = 0; i < 14; ++i) { + const size_t from = rec + kAdContracts + size_t(final_order.slots[size_t(i)]) * kAdContractBytes; + std::copy_n(before_resort.begin() + std::ptrdiff_t(from), kAdContractBytes, sorted[size_t(i)].begin()); + } + for (int i = 0; i < 14; ++i) { + const size_t to = rec + kAdContracts + size_t(i) * kAdContractBytes; + std::copy(sorted[size_t(i)].begin(), sorted[size_t(i)].end(), next.begin() + std::ptrdiff_t(to)); + } + } else { + std::copy(offer.begin(), offer.end(), next.begin() + std::ptrdiff_t(sorted_target)); + } + for (size_t i = 0; i < 4; ++i) next[pool + i] = 0; // Source clears the offer amount only. + + std::copy(next.begin() + std::ptrdiff_t(rec), next.begin() + std::ptrdiff_t(rec + kAdRecord), + g.manager_records.begin() + std::ptrdiff_t(rec)); + if (pool_group == 0) g.memory.set8(kAdGroupId, uint8_t(g.memory.u8(kAdGroupId) + 1)); + result.status = AdvertisingOfferStatus::accepted; + return result; +} + +AdvertisingSpendingView advertising_spending(const GameState& g, int manager, int target_slot) { + AdvertisingSpendingView view; + view.manager = manager; + view.target_slot = target_slot; + if (!ad_manager_record_valid(g, manager)) return view; + if (target_slot < 16 || target_slot > 18) return view; + const size_t rec = size_t(manager) * kAdRecord; + const size_t field = rec + (target_slot == 16 ? 0x850 : target_slot == 17 ? 0x854 : 0x858); + if (field + 4 > g.manager_records.size() || !g.memory.has(::bmh::layout::ActiveManager) || + int(g.memory.u8(::bmh::layout::ActiveManager)) != manager) return view; + view.current_amount = ad_u32(g.manager_records, field); + view.maximum_amount = target_slot == 16 ? 350000u : 35000u; + if (target_slot == 16) view.delivery_weeks = g.manager_records.at(rec + 0x287); + // BalanceFromGame clamps a legacy current value to the widget maximum; it does + // not make an otherwise available field uneditable. + view.available = target_slot != 16 || view.delivery_weeks == 0; + return view; +} + +AdvertisingSpendingResult set_advertising_spending(GameState& g, + const AdvertisingSpendingRequest& request, + WatcomRandom& rand) { + AdvertisingSpendingResult result; + const auto reject = [&](AdvertisingSpendingStatus status) { + result.status = status; + return result; + }; + if (!ad_manager_record_valid(g, request.manager) || !g.memory.has(::bmh::layout::ActiveManager) || + int(g.memory.u8(::bmh::layout::ActiveManager)) != request.manager) + return reject(AdvertisingSpendingStatus::invalid_manager); + if (request.target_slot < 16 || request.target_slot > 18) + return reject(AdvertisingSpendingStatus::invalid_target); + const size_t rec = size_t(request.manager) * kAdRecord; + const size_t field = rec + (request.target_slot == 16 ? 0x850 : + request.target_slot == 17 ? 0x854 : 0x858); + if (field + 4 > g.manager_records.size()) return reject(AdvertisingSpendingStatus::invalid_state); + const uint32_t current = ad_u32(g.manager_records, field); + uint8_t delivery = 0; + if (request.target_slot == 16) { + if (rec + 0x288 > g.manager_records.size()) return reject(AdvertisingSpendingStatus::invalid_state); + delivery = g.manager_records.at(rec + 0x287); + } + if (current != request.expected_amount || delivery != request.expected_delivery_weeks) + return reject(AdvertisingSpendingStatus::stale_request); + const uint32_t maximum = request.target_slot == 16 ? 350000u : 35000u; + if (request.amount > maximum) + return reject(AdvertisingSpendingStatus::invalid_amount); + if (request.target_slot == 16 && delivery != 0) + return reject(AdvertisingSpendingStatus::delivery_pending); + + if (request.target_slot == 16) { + // BalanceFromGame may return zero; the merchandise branch then performs no writes. + if (request.amount == 0) return reject(AdvertisingSpendingStatus::no_change); + GameState staged = g; + WatcomRandom staged_rand = rand; + if (!book_money(staged, request.manager, int32_t(request.amount), false, true)) { + // CheckAdvertisingRenewal clears +0x850 on insufficient funds but does not draw delivery RNG. + wr32(staged.manager_records, field, 0); + g.manager_records = std::move(staged.manager_records); + result.status = AdvertisingSpendingStatus::insufficient_funds; + result.changed = current != 0; + result.message_address = ::bmh::layout::Advertising_FormatError_TextPointer18; + return result; + } + wr32(staged.manager_records, field, int32_t(request.amount)); + staged.manager_records.at(rec + 0x287) = uint8_t(staged_rand.range(6, 9)); + g.manager_records = std::move(staged.manager_records); + rand = staged_rand; + result.status = AdvertisingSpendingStatus::accepted; + result.changed = true; + result.message_address = ::bmh::layout::DeskActions_Reject_ExecutableField; + return result; + } + + if (current == request.amount) return reject(AdvertisingSpendingStatus::no_change); + wr32(g.manager_records, field, int32_t(request.amount)); + result.status = AdvertisingSpendingStatus::accepted; + result.changed = true; + return result; +} + +namespace { + +void wr32_ad(std::vector& b, size_t at, uint32_t v) { + for (int i = 0; i < 4; ++i) b.at(at + size_t(i)) = uint8_t(v >> (8 * i)); +} + +// The end of a renewal (CheckAdvertisingRenewal): byte +6 cleared, the other boards of the same +// bundle (group byte +4, non-empty) take a copy of the contract (renewed or freed). +void settle_advertising_renewal(GameState& g, size_t rec, int contract_slot) { + std::vector& r = g.manager_records; + const size_t at = rec + kAdContracts + size_t(contract_slot) * kAdContractBytes; + r.at(at + 6) = 0; + if (contract_slot >= 14) return; + for (int other = 0; other < 14; ++other) { + if (other == contract_slot) continue; + const size_t o = rec + kAdContracts + size_t(other) * kAdContractBytes; + if (r.at(o + 4) == r.at(at + 4) && ad_u32(r, o) != 0) + std::copy_n(r.begin() + std::ptrdiff_t(at), kAdContractBytes, r.begin() + std::ptrdiff_t(o)); + } +} + +} // namespace + +AdvertisingRenewal check_advertising_renewal(GameState& g, int manager, int display_slot, WatcomRandom& rand) { + AdvertisingRenewal out; + if (!ad_manager_record_valid(g, manager) || display_slot < 0 || display_slot > 15) return out; + const size_t rec = size_t(manager) * kAdRecord; + out.contract_slot = display_slot < 14 ? ad_board_order(g.manager_records, rec).slots[size_t(display_slot)] : display_slot; + const size_t at = rec + kAdContracts + size_t(out.contract_slot) * kAdContractBytes; + std::vector& r = g.manager_records; + if (!ad_extension_requires_unsupported_prompt(r, at)) { + out.status = AdvertisingRenewal::Status::not_expired; + return out; + } + // the sponsor name: board/shirt firms from Advertising_FormatError_ExecutableField3, TV stations ten entries later + const uint32_t name = ::bmh::layout::Advertising_FormatError_ExecutableField3 + uint32_t((out.contract_slot == 15 ? 10 : 0) + std::min(r.at(at + 7), 9)) * 4; + const int demand = int(uint32_t(r.at(at + 8)) | uint32_t(r.at(at + 9)) << 8); + const int scaled = demand * int(rand.range(0x5f, 0x69)) / 100; + if (scaled < club_attraction(g, g.manager_teams.at(size_t(manager)))) { + out.status = AdvertisingRenewal::Status::offered; + out.question = message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer) + message_text(g, name) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer2); + return out; + } + out.status = AdvertisingRenewal::Status::declined_by_sponsor; + out.notice = message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer3) + message_text(g, name) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer4) + message_text(g, ::bmh::layout::DeskActions_CheckAdvertisingRenewal_TextPointer5); + post_composed(g, manager, out.notice); + wr32_ad(r, at, 0); + settle_advertising_renewal(g, rec, out.contract_slot); + return out; +} + +bool answer_advertising_renewal(GameState& g, int manager, int contract_slot, bool renew) { + if (!ad_manager_record_valid(g, manager) || contract_slot < 0 || contract_slot > 15) return false; + const size_t rec = size_t(manager) * kAdRecord; + const size_t at = rec + kAdContracts + size_t(contract_slot) * kAdContractBytes; + std::vector& r = g.manager_records; + if (!ad_extension_requires_unsupported_prompt(r, at)) return false; + if (renew) r.at(at + 5) = uint8_t(r.at(at + 6) & 0x7f); + else wr32_ad(r, at, 0); + settle_advertising_renewal(g, rec, contract_slot); + return true; +} + +} // namespace bmh diff --git a/src/game/desk_actions.hpp b/src/game/desk_actions.hpp new file mode 100644 index 0000000..2bc1fef --- /dev/null +++ b/src/game/desk_actions.hpp @@ -0,0 +1,616 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// Actions a human manager can take at his desk that change the game state and draw random +// numbers (BMH.exe V2.24 + supported rule profile patch). The screens themselves belong to the UI; these +// functions are what happens when the manager confirms. + +#include +#include +#include +#include +#include +#include + +#include "game/random.hpp" +#include "game/state.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/club_player_detail.hpp" + +namespace bmh { + +struct MinuteReport; +class LeImage; + +// The eight training camp resorts of BookTrainingCamp (names DeskActionsRuntimeField7). +constexpr int kTrainingCampResorts = 8; + +// Resort names, qualities and prices are edition content, not shared rules. +// Install the loaded executable's tables after creating or loading a GameState. +void configure_training_camp_data(GameState&, const LeImage&); + +// DeskDate / menu 6 friendship booking. `manager_home` selects which team is first in +// the saved pair; the manager of the home team pays the source cost. The national-team +// source-qualified overload below handles pseudo-team ratings and their W/G RNG separately. +enum class FriendlyQuoteStatus : uint8_t { quoted, invalid_manager, invalid_opponent, invalid_state }; +enum class FriendlyDateStatus : uint8_t { + available, available_with_calendar_event, current_or_past, unavailable, + plan_full, invalid_quote, invalid_date +}; +enum class FriendlyBookingStatus : uint8_t { + booked, declined, opponent_declined, insufficient_funds, invalid_manager, invalid_opponent, + invalid_date, date_unavailable, plan_full, stale_quote, invalid_request +}; + +struct FriendlyBookingQuote { + FriendlyQuoteStatus status = FriendlyQuoteStatus::invalid_opponent; + int manager = -1; + int opponent = -1; + int manager_team = -1; + bool manager_home = true; + int home_team = -1; + int away_team = -1; + int payer_manager = -1; + int opponent_manager = -1; + int32_t cost = 0; + uint8_t planner_count = 0; + bool operator==(const FriendlyBookingQuote&) const = default; +}; + +struct FriendlyBookingRequest { + FriendlyBookingQuote quote; + uint16_t season_day = 0; + bool accept_opponent = false; + int consenting_manager = -1; + bool accept_cost = false; + int approving_manager = -1; +}; + +struct FriendlyBookingResult : FriendlyBookingQuote { + FriendlyBookingStatus status = FriendlyBookingStatus::invalid_request; +}; + +// Source-qualified menu-6 national friendly owner. The UI/session supplies the +// revision and request identity; the engine binds them to the selected runtime nation. +struct NationalFriendlyOwner { + uint64_t request_id = 0; + uint64_t revision = 0; + int manager = -1; + int runtime_team = kNoTeam; + int menu_kind = -1; + bool operator==(const NationalFriendlyOwner&) const = default; +}; + +struct NationalFriendlyQuote { + FriendlyBookingQuote terms; + NationalFriendlyOwner owner; + int own_rating = 0; + int opponent_rating = 0; + uint32_t watcom_seed_before = 0; + uint32_t watcom_seed_after = 0; + uint64_t watcom_calls_before = 0; + uint64_t watcom_calls_after = 0; + bool operator==(const NationalFriendlyQuote&) const = default; +}; + +struct NationalFriendlyBookingRequest { + NationalFriendlyQuote quote; + NationalFriendlyOwner owner; + uint16_t season_day = 0; + bool accept_opponent = false; + int consenting_manager = -1; + bool accept_cost = false; + int approving_manager = -1; + bool operator==(const NationalFriendlyBookingRequest&) const = default; +}; + +struct NationalFriendlyBookingResult : FriendlyBookingResult { + bool national_bonus_awarded = false; +}; + +// Pure source-derived quote for the pre-calendar price/venue prompt. It performs no writes +// or RNG draws. Bind this quote to the UI request ID/revision until the user chooses a day. +FriendlyBookingQuote quote_friendly_match(const GameState& g, int manager, int opponent, + bool manager_home); + +// Original menu-6 national quote. A successful accepted quote advances W exactly for +// QuoteNationalFriendlyMatch's ratings. Preview runs the same calculation on a copy and never advances W. +NationalFriendlyQuote quote_national_friendly_match(const GameState& g, + const NationalFriendlyOwner&, int opponent, bool manager_home, WatcomRandom& rand); +NationalFriendlyQuote preview_national_friendly_match(const GameState& g, + const NationalFriendlyOwner&, int opponent, bool manager_home, const WatcomRandom& rand); +FriendlyDateStatus national_friendly_match_date_status(const GameState&, + const NationalFriendlyQuote&, const NationalFriendlyOwner&, const WatcomRandom&, + uint16_t season_day); +NationalFriendlyBookingResult book_national_friendly_match(GameState&, + const NationalFriendlyBookingRequest&, const WatcomRandom&, GameRandom&); + +// Conservative saved-state projection for days 0..365. `available_with_calendar_event` is +// the source color class for a selectable day whose calendar word has 0x1c0 set. The +// original calendar also carries a transient, sequentially projected bit 15 that is not in +// GameState; dates with ambiguous neighboring calendar flags may therefore be over-rejected. +FriendlyDateStatus friendly_match_date_status(const GameState& g, + const FriendlyBookingQuote& quote, + uint16_t season_day); + +// Book the accepted quote on the chosen day atomically. The quote is recomputed and must +// still match; approval is explicit. A successful home booking permanently debits the fee +// and records expense-other (+0x8a0). No RNG is used for club-vs-club bookings. +FriendlyBookingResult book_friendly_match(GameState& g, const FriendlyBookingRequest& request); + +// UI-free human transfer actions (menu 17). List-entry indices address the 44-entry +// transfer table; money and contracts are stored in the normal engine state. +enum class TransferActionStatus : uint8_t { + accepted, pending, rejected, offer_too_low, blocked_by_board, insufficient_funds, no_squad_room, + invalid_manager, invalid_player, invalid_request, allocator_blocked, unsupported +}; + +struct TransferBidRequest { + int manager = -1; + int list_entry = -1; + int player = -1; // expected player identity; rejects a recycled list slot + int32_t fee = 0; + int32_t annual_salary = 0; + uint8_t contract_years = 1; + std::array bonuses{}; + // Exact absolute SquadSlots player-pool index observed by the selected market row. + // The Source-qualified submit requires this explicitly; the legacy overload + // ignores it and preserves its historical request contract. + int source_slot = -1; + // Poaching: list entries 40..43 and the SubmitTransferBidSourceHumanBuyer branches for them (immediate + // decision, a human seller is asked, the DFB fee on a refusal; src/game/poach.hpp). + bool poach = false; + // OpenTransferEditor's loan checkbox is encoded in the high bit of the submitted + // offer term, independently of its 1..4 year duration. + bool loan = false; + // DayStepRest2's buy-back row from Range2 is a distinct 40..43 Source entry; + // it uses ordinary fee/qualification rules and is not poaching. + bool loan_return_entry = false; +}; + +struct TransferActionResult { + TransferActionStatus status = TransferActionStatus::invalid_request; + int player = -1; + int list_entry = -1; + int32_t fee = 0; + int32_t annual_salary = 0; +}; + +// Authenticated lender snapshot -> real borrower squad identity. This is preview +// only; the snapshot never becomes a listing/sale row. +struct TransferMarketSnapshotPreview { + int snapshot_index=-1,displayed_row=-1,source_slot=-1,player=-1; + bool operator==(const TransferMarketSnapshotPreview&) const = default; +}; +std::optional transfer_market_snapshot_preview( + const GameState&,int manager,int runtime_club,int snapshot_index); +// TransferMarketScreen quote identity: ordinary Native slot, or an explicitly authenticated +// lender snapshot mapped by the read-only resolver above. +struct TransferMarketPreviewRequest { + int manager=-1,runtime_club=-1,source_slot=-1,expected_player=-1,seller=-1; + bool purchase=false,loan=false; + int snapshot_index=-1; +}; +struct TransferMarketPreviewResult { + bool supported=false; + uint32_t fee=0,salary=0; + int32_t delta=0,projected_balance=0; + std::string reason; +}; +// No Native writes or G draws. W is0 or1 (42307 fallback). The owner stages W +// and rolls it back on unsupported/exception; repeated-hover caching belongs +// to that owner, not to this primitive or a render method. +TransferMarketPreviewResult quote_transfer_market_preview_source( + const GameState& g,const TransferMarketPreviewRequest& request,WatcomRandom& rand); + +// Exact ordinary OpenTransferEditor/KB31 state owner. UI events contain calculator +// results in Native units; all quotes and Native row writes belong here. +struct TransferOfferEditorRequest { + int manager=-1,runtime_club=-1,list_entry=-1,source_slot=-1,expected_player=-1; + uint16_t expected_seller_word=0xffff; + int expected_bid_slot=-1; // Source's first FFFF or matching own word; -1 if full. + bool loan=false; + // Poaching (Abwerben, Reset button 4): the special list entry 40..43 that + // Range2 prepared for the player (src/game/poach.hpp); SubmitTransferBidSourceHumanBuyer then decides at once. + bool poach=false; + // Explicit owner for DayStepRest2 -> Range2 return offers in entries40..43. + // This does not select the poaching branch or its DFB/188% rules. + bool loan_return_entry=false; +}; +struct TransferOfferInputProfile { + uint32_t minimum=0,maximum=0,initial=0,source_text_address=0; + std::array,8> presets{}; + bool supported=false,currency=false; +}; +struct TransferOfferEditorState { + bool supported=false,closed=false,existing=false,editable=false,quote_loan=false; + // OpenTransferEditor local1c: set only after initializing a selected FFFF row. + // Existing-own and full read-only openings keep it false until needed. + bool initialized_empty_bid=false; + std::string reason; + TransferOfferEditorRequest request; + int bid_slot=-1; + std::optional player_info_selection; // Source local40 retained at opening. + uint8_t percent=0,term=0,years=1,mode=0; + uint32_t fee=0,salary=0,asking_fee=0,asking_salary=0,quoted_fee=0,quoted_salary=0; + std::array bonuses{}; + std::array money_profiles{}; + std::array mode3_profiles{}; // years, seven bonuses + std::array native_entry{}; // stale event guard, owned copy +}; +enum class TransferOfferEditorField : uint8_t { fee,salary,years,bonus0,bonus1,bonus2,bonus3,bonus4,bonus5,bonus6,toggle_quote_loan }; +struct TransferOfferEditorEvent { + TransferOfferEditorField field=TransferOfferEditorField::fee; + uint32_t value=0; + bool accepted=true; // calculator Cancel; fee/salary still redraw Source quote +}; +TransferOfferEditorState open_transfer_offer_editor_source(GameState&, + const TransferOfferEditorRequest&,GameRandom&,WatcomRandom&); +TransferOfferEditorState edit_transfer_offer_editor_source(GameState&, + const TransferOfferEditorState&,const TransferOfferEditorEvent&,GameRandom&,WatcomRandom&); +// OpenTransferEditor TeamInfo return: 1c5b7 -> 1c186 -> 1c18b. Rescan and +// redraw the current row, preserving initial percent/G. A first empty selection +// initializes only fee/salary/term once; all seven Native bonus bytes survive. +TransferOfferEditorState resume_transfer_offer_team_info_source(GameState&, + const TransferOfferEditorState&,WatcomRandom&); +// OpenTransferEditor:6936..6953 resolves the direct footer's actual player slot. +// Unmanaged sellers use the Native pool slot; managed sellers use the first +// masked-ID match in their real 24/16-slot squad. The opened owner retains +// Source local40; stale retained rows reject instead of silently reselecting. +ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const GameState&, + const TransferOfferEditorState&); +// After player information returns: zero return flags preserve the entire editor and quote; +// otherwise rescan/requote by rebuilding the quote without repeating the initial G draw. +TransferOfferEditorState resume_transfer_offer_player_info_source(GameState&, + const TransferOfferEditorState&,uint8_t player_info_primary_refresh,uint8_t player_info_secondary_refresh,WatcomRandom&); +TransferOfferEditorState cancel_transfer_offer_editor_source(const GameState&, + const TransferOfferEditorState&); +struct TransferOfferEditorSubmitResult { + TransferOfferEditorState editor; + TransferActionResult action; +}; +TransferOfferEditorSubmitResult submit_transfer_offer_editor_source(GameState&, + const TransferOfferEditorState&,WatcomRandom&,const HumanBuyerSaleHooks&,MinuteReport&); + +// Submit a manager bid on an existing list entry. A full-value fee and salary meeting +// the demand complete an immediate agreement; lower viable offers persist for weekly review. +TransferActionResult submit_transfer_bid(GameState& g, const TransferBidRequest& request, WatcomRandom& rand); + +// Explicit opt-in Source SubmitTransferBidSourceHumanBuyer ordinary bid-submit path. Unlike the legacy +// overload, the caller owns staged Native/W state, supplies the exact source +// pool slot, actual career mode is present in Native, and the session provides +// its allocator/entry ownership plus Original notice presenter. Source-approved +// AI/free-agent purchases use the exact shared settlement; other sellers retain +// a pending bid. Unsupported contexts require caller rollback. +TransferActionResult submit_transfer_bid_source_human_buyer(GameState& g, + const TransferBidRequest& request, WatcomRandom& rand, + const HumanBuyerSaleHooks& hooks, MinuteReport& report); + +// Put one of the manager's squad rows on the list. The request consumes the original +// listing-price RNG and returns the new stable entry index through the result. +TransferActionResult list_manager_player(GameState& g, int manager, int squad_row, + WatcomRandom& rand, MinuteReport& report); + +enum class TrainingCampBookingBlock { none, booked_this_week, visit_limit, invalid_request }; + +// SetTrainingCampFocus: persist the four focus sliders (+0xc1..+0xc4) without drawing or +// applying training. Rejects an invalid manager or any value outside the original 0..15 range. +bool set_training_camp_focus(GameState& g, int manager, const std::array& focus); + +// BookTrainingCamp controller gates, before payment and training effects. +TrainingCampBookingBlock training_camp_booking_block(const GameState& g, int manager); + +// Text: price of a stay at `resort` for the manager's team - the resort's base +// price (DeskActions_ConfigureTrainingCampData_RuntimeField2 of the loaded game) plus 5 000 per player of the squad +// (QuoteNationalFriendlyMatch with 0xff, the player count). Draws nothing. +int32_t training_camp_price(const GameState& g, int manager, int resort); + +// BookTrainingCamp on "Buchen": the price is booked (BookMoney2, not forced). If the money is +// there, record +0x890 (training camp expenses) grows by it, record +0x21f counts the stays +// (bit 7 = "already in a camp this week", cleared by the day step) and the camp takes +// effect (training_camp_effect). Returns false if the booking failed. The four focus +// sliders (record +0xc1..+0xc4, 0..15) are set on the screen before. +// The screen allows a booking only if bit 7 of +0x21f is clear and fewer than 3 stays +// were made (+0x21f & 0x7f < 3) - checked by the caller. +bool book_training_camp(GameState& g, int manager, int resort, WatcomRandom& rand); + +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// TrainingCampEffect (with the supported rule profile patch TrainingCampEffect2 / TrainingCampEffect3 / TrainingCampEffect4): the +// effect of a training camp. The team morale rises by 12 * quality * 20 % (clamped to +// 0..47), then every player of the squad may improve in condition, technique, form, +// familiarity (tactics board +0xf) and freshness (board +0x0e bits 0-5). See the .cpp. +// Ends with the message DeskActionsRuntimeField8 (SystemIdentity, no draws). +void training_camp_effect(GameState& g, int manager, int resort, WatcomRandom& rand); + +} // namespace bmh + +namespace bmh { + +// The stock exchange screen MaxSharesToBuy (bank button). The twelve shares are entries of +// 0x5c bytes in GameState::stocks (StockExchange): +0x00 long-term value (u32, price * 100), +// +0x04 + manager * 4 the amount the manager paid for his shares (u32), +0x16 trend byte, +// +0x4e current price (u16), +0x50 + manager * 2 shares held (u16), +0x59 age of the trend. +constexpr int kStocks = 12; + +// Largest number of shares of `stock` the manager may buy: (money + credit line) / price, +// with at most 9999 shares of one company. +int max_shares_to_buy(const GameState& g, int manager, int stock); + +// Buying `count` shares: the price times count plus 1.5 % fee is booked (BookMoney2, not +// forced) - but only while the paid amount of all shares held stays below 5 % of the +// money (record +0x314 / 20), else the message Bank_OriginalToUtf8_TextPointer8 ("too much") and nothing +// happens (returns false). Record +0x324 (stock balance) falls by the amount. +bool buy_shares(GameState& g, int manager, int stock, int count); + +// Selling `count` shares at the current price: the paid amount shrinks by its average per +// share, the money (forced booking) and record +0x324 rise. +void sell_shares(GameState& g, int manager, int stock, int count); + +// The "Tip" button (costs 5 000, booked forced with statistics): 0 (sell) .. 4 (buy), +// from the trend byte and the price against the long-term value, then with chance 1/3 +// moved by -2, 0 or +2 (WatcomRandom(0, 2) twice). The text is Bank_FormatError_RuntimeField19[tip]. +int stock_tip(GameState& g, int manager, int stock, WatcomRandom& rand); + +} // namespace bmh + +namespace bmh { + +// The stadium screen ConstructionPricePercent (stadium button) - the parts that draw numbers or book. +// The manager record holds 14 periphery objects (+0x00..+0x0d condition, +0x1e..+0x2b +// construction weeks), eight Facility/Maintain investments (+0x0e.. condition, +// +0x2c.. construction weeks, +0x3c.. current/pending level), and eight stand blocks +// (+0x34.. construction weeks, +0x44.. seat/roof flags, +0x4c.. current capacity in +// thousands, +0x54.. future capacity). These are distinct Source branches. + +// On opening: the game generator restarts from the saved seed CareerSession_Invalid_RuntimeField2 and draws the +// building company's discount, DeskActionsRuntimeField9 = 100 - G(r / 100, r / 100 + 5) with r = +// record +0x8b4 (int16). Returns the price percentage (100 - discount). +int construction_price_percent(const GameState& g, int manager, GameRandom& game); + +// The offer for periphery object `object` (0..13) when it is clicked: the game generator +// restarts from CareerSession_Invalid_RuntimeField2, draws G(0, 100) once per object before it and then the +// price percentage G(85, 115); price = base (StadiumPriceTable) * percentage / 1 000 000 * +// 10 000. +int32_t periphery_offer(const GameState& g, int object, GameRandom& game); + +// PayConstruction: pays a construction. With `sponsor` and a sponsor share (record +0x171) +// the price is reduced once - by ((share >> 5) + 3) * 10 % below a limit of ((share >> 2) +// & 7) * 325 000 + 26 000, else by WatcomRandom(2, 4) * 5 % ("Der Sponsor fühlt sich +// ausgenutzt") - and the share is cleared. Booked with statistics, not forced. +enum class ConstructionNoticeKind { SponsorContribution, SponsorExploited, InsufficientFunds }; +struct ConstructionNotice { + int manager = -1; + ConstructionNoticeKind kind = ConstructionNoticeKind::InsufficientFunds; + uint32_t gross_price = 0, subsidy = 0; + int percent = 0; +}; +using ConstructionNoticeHook = std::function; + +// PayConstruction presents the sponsor notice before clearing+171. A genuine +// BookMoney2 refusal presents funds after that clearing. Presenter exceptions +// propagate; the caller owns the whole transaction checkpoint/rollback. +bool pay_construction(GameState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand, + const ConstructionNoticeHook& notice = {}); + +// "Ja" on the offer: pay_construction(price, sponsor) and the construction time of the +// object (CareerSession_DispatchStadium_RuntimeField2[object * 5]) is entered at record +0x1e + object. +bool build_periphery(GameState& g, int manager, int object, uint32_t price, WatcomRandom& rand, + const ConstructionNoticeHook& notice = {}); + +enum class StandBlockOfferDecision : uint8_t { Pending, Declined, Accepted }; + +struct StandBlockOffer { + int percent = 0; + uint32_t base_price = 0; + uint32_t offered_price = 0; // quoted +percent price; the amount shown before Yes/No + uint32_t price = 0; // amount to pay: base price until Accepted + int base_days = 0; + int construction_days = 0; // original duration until Accepted + StandBlockOfferDecision decision = StandBlockOfferDecision::Pending; +}; + +// PrepareStandBlockOffer, before its Yes/No prompt: consumes exactly W(6,14) and returns the +// percentage and quoted price. The quote is a value; displaying it consumes no more RNG. +// The path has not been compared with a matching original recording. +StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand); + +// Resolve the PrepareStandBlockOffer answer once. No leaves the base price/time and draws nothing; +// Yes applies the quoted price and consumes exactly W(days>>3, days>>1) to shorten time. +// Repeated resolution is ignored, so a duplicated input cannot consume another draw. +bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand); + +// ConstructionPricePercent choices 0..7: TEXTD734..741. Choices 8..15 are separate stand +// expansion editors and must never use the Facility/Maintain record arithmetic. +enum class StadiumInvestment : uint8_t { + Floodlights = 0, Scoreboard, PitchHeating, VipLounge, Pitch, Comfort, Condition, Safety +}; +struct StadiumInvestmentConstants { + std::array price{}; // EXE CareerSession_DispatchStadium_RuntimeField[choice], not CareerSession_DispatchStadium_RuntimeField[choice+8] + std::array weeks{}; // EXE CareerSession_DispatchStadium_RuntimeField2[(choice+14)*5] +}; +struct StadiumInvestmentOption { + uint8_t current_status = 0, current_level = 0, increment = 0, target_level = 0; + uint32_t base_price = 0; + uint8_t base_weeks = 0; + bool operator==(const StadiumInvestmentOption&) const = default; +}; +// Pure projection. Busy or terminal investments have no options. Invalid owner, +// constants or a nonzero idle high nibble raise FormatError. Heating/VIP offer +// one tier unless (raw status &7)==2, including raw0. Ordinary tiers start at +// the full raw status byte and stop before5; bit3 yields no ordinary options. +// target_level is the accepted level after weekly completion's &7 narrowing. +std::vector stadium_investment_options_source( + const GameState&, int manager, StadiumInvestment, int construction_percent, + const StadiumInvestmentConstants&); +// Revalidate the owned option against the current record and trusted Original +// constants before payment. Both resolved tip answers build: Declined means no +// tip, not cancel. Source sponsor draws/consumption can precede payment refusal; +// only successful payment writes +2c/+3c. No actual block capacity/flags +// (+34/+44/+54), GameRandom or weekly compensation is touched. +bool build_stadium_investment_source(GameState&, int manager, StadiumInvestment, + int construction_percent, const StadiumInvestmentConstants&, + const StadiumInvestmentOption&, const StandBlockOffer& resolved_tip, WatcomRandom&, + const ConstructionNoticeHook& notice = {}); + +// LeagueTableRangeDialog: persist the active 11-match pools coupon. The stake sits at +// Coupon + manager*0x14 and picks at +8..+0x12. Money is only charged by +// settle_pools_coupon at matchday end; this confirmation itself draws no RNG. +// BuildPoolsCoupon makes the screen unavailable unless all eleven fixtures exist. +// BalanceFromGame bounds stake to 10,000..400,000 (zero clears it). +bool submit_pools_coupon(GameState& g, int manager, uint32_t stake, + const std::array& tips); + +} // namespace bmh + +namespace bmh { + +// Source-backed advertising contracts (DeskActionsOperation/CheckAdvertisingRenewal). Offers are +// generated elsewhere and live in the manager's saved +0x8cc pool. Projection +// is read-only: it never generates offers or consumes RNG. +enum class AdvertisingOfferStatus : uint8_t { + available, accepted, invalid_manager, invalid_display_slot, invalid_state, no_offers, + unavailable_target, unsupported_extension, insufficient_boards, stale_offer, + malformed_offer, invalid_request +}; + +struct AdvertisingOfferCandidate { + int raw_slot = -1; // saved pool index, 0..9 (TV: 0..4) + std::array bytes{}; // complete source offer record + uint32_t monthly_amount = 0; // DWORD +0 + uint8_t bundle_units = 0; // byte +4 (DWORD word 1, low byte) + uint8_t months = 0; // byte +5 + uint8_t sponsor_id = 0xff; // byte +7 + bool present = false; + bool can_accept = false; +}; + +struct AdvertisingOfferList { + AdvertisingOfferStatus status = AdvertisingOfferStatus::invalid_request; + int manager = -1; + int display_slot = -1; // 0..13 boards, 14 shirt, 15 television + int contract_slot = -1; // physical manager-record row backing display_slot + std::array contract_bytes{}; // exact selected row for request binding + int pool_group = -1; // 0 boards, 1 shirt, 2 television + int free_boards = 0; + std::vector offers; +}; + +struct AdvertisingOfferRequest { + int manager = -1; + int display_slot = -1; // screen row after source sort (0..15) + int contract_slot = -1; // physical row identity from the UI projection + std::array expected_contract{}; + int raw_slot = -1; + std::array expected_offer{}; // binds UI choice to the projected offer + bool operator==(const AdvertisingOfferRequest&) const = default; +}; + +struct AdvertisingOfferResult { + AdvertisingOfferStatus status = AdvertisingOfferStatus::invalid_request; + int manager = -1; + int display_slot = -1; + int contract_slot = -1; + int raw_slot = -1; +}; + +// A group of identical offers may require several boards. Empty boards and rows +// marked replaceable by source flag +6 bit 7 count toward capacity. +AdvertisingOfferList advertising_offers(const GameState& g, int manager, int display_slot); + +// Accept an existing offer atomically. Board rows are source-sorted before the +// bundle is installed; the group byte at +4 receives AdGroupId and that counter +// advances once. Shirt/TV offers replace their corresponding slot. This commit +// books no immediate cash and draws no RNG. Option-extension offers are excluded. +AdvertisingOfferResult accept_advertising_offer(GameState& g, + const AdvertisingOfferRequest& request); + +// CheckAdvertisingRenewal: a click on a contract whose months ran out (sponsor set, months 0 - the +// month change posted "kann verlängert werden", Month_MonthChange_TextPointer). The sponsor's demand (word +// +8, the club attraction it wants) is scaled by W(95, 105) % (WatcomRandom); if it stays +// below the club's attraction (ClubAttraction) the manager is asked "Möchten Sie den Vertrag +// mit verlängern ?" (DeskActions_CheckAdvertisingRenewal_TextPointer/DeskActions_CheckAdvertisingRenewal_TextPointer2), otherwise the sponsor declines ("Die Firma +// wird den Vertrag nicht verlängern.", DeskActions_CheckAdvertisingRenewal_TextPointer3..DeskActions_CheckAdvertisingRenewal_TextPointer5, a mailbox message) and the +// place becomes free. Step one draws the random number and settles the refusal; step two +// applies the manager's answer: yes = the old duration again (byte +6 & 0x7f), no = free. +// Either way byte +6 is cleared and the other boards of the same bundle (group byte +4) +// get a copy of the result. +struct AdvertisingRenewal { + enum class Status : uint8_t { invalid, not_expired, declined_by_sponsor, offered } status = Status::invalid; + int contract_slot = -1; // 0-13 boards, 14 shirt, 15 TV + std::string question; // the original question text (offered) + std::string notice; // the sponsor's refusal (declined_by_sponsor) +}; +AdvertisingRenewal check_advertising_renewal(GameState& g, int manager, int display_slot, WatcomRandom& rand); +bool answer_advertising_renewal(GameState& g, int manager, int contract_slot, bool renew); + +// CheckAdvertisingRenewal advertising spend fields (manager record +0x850/+0x854/+0x858, +// delivery countdown +0x287). Projection is read-only; only goods purchasing draws. +struct AdvertisingSpendingView { + int manager = -1; + int target_slot = -1; // 16 merchandise, 17 press budget, 18 fan-work budget + uint32_t current_amount = 0; + uint32_t maximum_amount = 0; + uint8_t delivery_weeks = 0; + bool available = false; +}; + +enum class AdvertisingSpendingStatus : uint8_t { + accepted, no_change, insufficient_funds, delivery_pending, + invalid_manager, invalid_target, invalid_amount, stale_request, invalid_state +}; + +struct AdvertisingSpendingRequest { + int manager = -1; + int target_slot = -1; + uint32_t amount = 0; + uint32_t expected_amount = 0; + uint8_t expected_delivery_weeks = 0; + bool operator==(const AdvertisingSpendingRequest&) const = default; +}; + +struct AdvertisingSpendingResult { + AdvertisingSpendingStatus status = AdvertisingSpendingStatus::invalid_state; + bool changed = false; + uint32_t message_address = 0; +}; + +AdvertisingSpendingView advertising_spending(const GameState& g, int manager, int target_slot); +AdvertisingSpendingResult set_advertising_spending(GameState& g, + const AdvertisingSpendingRequest& request, + WatcomRandom& rand); + +} // namespace bmh + +namespace bmh { + +// The funds of the same screen (block FundBlock in GameState::memory, six entries of 0x1c +// bytes): +0x00 price of a unit ((1 << k) * 100 000), +0x04 + manager * 4 the amount the +// manager paid (u32), +0x14 + manager * 2 units held (u16, at most 10 per fund). +constexpr int kFunds = 6; + +// Units of fund `fund` the manager can buy: (money + credit line) / (price * 1.05), at most +// 10 minus the units held. +int max_fund_units(const GameState& g, int manager, int fund); + +// Buying `count` units: price * count plus 5 % fee is booked (not forced) - record +0x324 +// falls by it, record +0x30c rises by the fee and by price * count / 9. Every fund but +// the first costs a surcharge as well: count * G(price / 40, price / 10), paid (forced) and +// added to +0x30c, with the message CareerSession_Int32T_TextPointer2. Returns the surcharge. +int32_t buy_fund_units(GameState& g, int manager, int fund, int count, GameRandom& game); + +// Selling `count` units at the price: the paid amount shrinks by its average per unit, the +// money (forced) and +0x324 rise, +0x30c falls by price * count / 9. +void sell_fund_units(GameState& g, int manager, int fund, int count); + +// The fixed-term deposit (record +0x318): a positive amount moves money from the account +// to the deposit, a negative one back (both booked forced; +0x324 changes by the same). +// The deposit earns interest in daily_interest. +void move_to_deposit(GameState& g, int manager, int32_t amount); + +// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules. +// NormalizePitchSetPieceSource (supported rule profile patch), when the line-up screen opens (PitchScreen, desk menu 3 and +// before matches): a manager record without the set-piece marker 0x3253 at +0xb0a gets it, +// with the takers cleared (+0xafc..+0xaff = 0, +0xb08 = designated-taker signature). +void open_lineup_screen(GameState& g, int manager); + +} // namespace bmh diff --git a/src/game/driver.cpp b/src/game/driver.cpp new file mode 100644 index 0000000..8dc1be3 --- /dev/null +++ b/src/game/driver.cpp @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/driver.hpp" + +#include +#include +#include + +#include "game/matchday.hpp" +#include "game/matchday_setup.hpp" +#include "game/season.hpp" + +namespace bmh { + +int cup_tie(const MatchGroup& grp, int m) { + const uint16_t r = grp.cup_results.at(size_t(m)); + int home = r >> 5 & 0x1F, away = r & 0x1F; + int other_home = 0, other_away = 0; + if (!grp.cup_other_leg.empty()) { + other_home = grp.cup_other_leg.at(size_t(m)) >> 5 & 0x1F; + other_away = grp.cup_other_leg.at(size_t(m)) & 0x1F; + } + // this match's home team was the away team of the other leg + if ((grp.flags() & 0x10) && other_home + away == home + other_away && (r >> 11) == 0) { + away *= 2; // away goals of this match ... + other_away *= 2; // ... and of the other leg count double + } + const int home_total = home + other_away, away_total = other_home + away; + return (unsigned(home_total) < unsigned(away_total) ? 1 : 0) + (home_total == away_total ? 2 : 0); +} + +bool cup_screen_shown(const std::vector& buttons, int cup_id, int minute) { + if (buttons.empty()) return true; + const int kind = (minute > 45) + 1; + const int row = cup_id + 5; + if (row == 0x12) return buttons.at(size_t(0x12 + kind)) == 0 || buttons.at(size_t(0x1b + kind)) == 0; + return buttons.at(size_t(kind + row * 9)) == 0; +} + +void play_phase(MatchEngine& engine, std::vector& groups, int first, int last, int stoppage, int phase, + MinuteReport& report, const std::function& after_minute) { + for (MatchGroup& grp : groups) grp.ended = 0, grp.phase = phase; + for (int minute = first; minute <= last + stoppage && !report.unsupported; minute++) { + bool running = false; + for (const MatchGroup& grp : groups) + for (int m = 0; m < grp.matches(); m++) + if (!((grp.void_mask() | grp.ended) >> m & 1)) running = true; + if (!running) break; // the original leaves the phase after a minute without matches + report = engine.minute(minute, last, stoppage); + if (after_minute) after_minute(minute); + } +} + +namespace { + +void set_void(MatchGroup& grp, int m) { + const uint32_t v = grp.void_mask() | 1u << m; + for (int i = 0; i < 4; i++) grp.desc.at(0xb8 + size_t(i)) = uint8_t(v >> (8 * i)); +} + +} // namespace + +namespace { + +bool group_played(const MatchGroup& grp) { + for (int m = 0; m < grp.matches(); m++) + if (grp.ended >> m & 1) return true; + return false; +} + +bool result_visible(GameState& g, const MatchGroup& grp, int last, + const std::vector& buttons, PhaseResultKind& kind, + int& competition_id) { + const uint32_t id = le32(grp.desc, 0xcc); + if (id < 0x15) { + kind = PhaseResultKind::League; + competition_id = int(id); + return league_screen_shown(buttons, 2, last, int(id)); + } + kind = PhaseResultKind::Cup; + competition_id = int16_t(g.memory.u16(id + 0x18)); + return cup_screen_shown(buttons, competition_id, last); +} + +PhaseResultRequest make_result_request(const MatchGroup& grp, uint64_t phase_id, + uint32_t group_index, uint64_t revision, + PhaseResultKind kind, int competition_id, int last) { + PhaseResultRequest req; + req.phase_id = phase_id; + req.group_index = group_index; + req.revision = revision; + req.kind = kind; + req.competition_id = competition_id; + req.phase_end_minute = last; + req.matches.reserve(size_t(grp.matches())); + for (int m = 0; m < grp.matches(); ++m) { + PhaseResultMatch score; + score.home_team = grp.fixtures.at(size_t(m * 2)); + score.away_team = grp.fixtures.at(size_t(m * 2 + 1)); + score.score_known = match_score(grp, m, score.home_score, score.away_score); + req.matches.push_back(score); + } + return req; +} + +void finish_group_phase(GameState& g, MatchGroup& grp, int last, GameRandom& game) { + const bool full_time = last == 90 || last == 120 || last == 40; + if (!full_time) return; + const bool final_phase = last == 40 || last == 120; + for (int m = 0; m < grp.matches(); m++) { + if ((grp.flags() & 8) && cup_tie(grp, m) == 2) { + uint16_t& r = grp.cup_results.at(size_t(m)); + if (r != 0xCCCC) r = uint16_t((final_phase ? 2 : 1) * 0x400 + (r & 0x3FF)); + if (final_phase) finish_match(g, grp, m, last, game); + continue; + } + if (grp.void_mask() >> m & 1) continue; + finish_match(g, grp, m, last, game); + set_void(grp, m); + } +} + +PhaseEndOutput rejected(const char* why) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Rejected; + out.reason = why; + return out; +} + +PhaseEndOutput advance_phase_end(PhaseEndCursor& c) { + while (c.next_group < c.groups->size()) { + MatchGroup& grp = c.groups->at(c.next_group); + if (c.phase_played) { + PhaseResultKind kind; + int competition_id = 0; + if (result_visible(*c.state, grp, c.last, c.buttons, kind, competition_id)) { + c.pending = make_result_request(grp, c.phase_id, c.next_group, c.revision, + kind, competition_id, c.last); + // CupGroupOverviewEffects initializes the cup viewer before presenting it. + // Keep this once at entry, so closing cannot erase viewer edits. + if (kind == PhaseResultKind::Cup) cup_overview_effects(*c.state); + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + } + finish_group_phase(*c.state, grp, c.last, *c.game); + ++c.next_group; + } + c.complete = true; + c.pending.reset(); + PhaseEndOutput out; + out.status = PhaseEndStatus::Complete; + return out; +} + +} // namespace + +PhaseEndOutput begin_phase_end(PhaseEndCursor& c, uint64_t phase_id, GameState& g, + std::vector& groups, int last, + const std::vector& buttons, GameRandom& game, + WatcomRandom& rand, MinuteReport& report) { + if (c.initialized) { + const bool same = c.phase_id == phase_id && c.state == &g && c.groups == &groups && c.last == last && + c.buttons_source == &buttons && c.game == &game && c.rand == &rand && c.report == &report; + if (!c.complete) { + if (!same) return rejected("phase already active with different identity or borrowed objects"); + if (c.pending) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + return rejected("active phase has no pending result"); + } + if (same) { + PhaseEndOutput out; + out.status = PhaseEndStatus::Complete; + return out; + } + } + c.initialized = true; + c.complete = false; + // Original local_48 belongs to EndPhase, not to a group. Preserve this + // gate throughout the barrier even as each acknowledged group settles. + c.phase_played = std::any_of(groups.begin(), groups.end(), group_played); + c.phase_id = phase_id; + c.revision = 1; + c.next_group = 0; + c.last = last; + c.buttons = buttons; + c.buttons_source = &buttons; + c.state = &g; + c.groups = &groups; + c.game = &game; + c.rand = &rand; + c.report = &report; + c.pending.reset(); + c.last_ack.reset(); + c.after_last_ack.reset(); + return advance_phase_end(c); +} + +PhaseEndOutput continue_phase_end(PhaseEndCursor& c, const std::optional& reply) { + if (!c.initialized) return rejected("phase not started"); + if (!reply) { + if (c.complete) return rejected("phase already complete"); + if (!c.pending) return rejected("no result is pending"); + PhaseEndOutput out; + out.status = PhaseEndStatus::Waiting; + out.request = c.pending; + return out; + } + if (c.last_ack && reply->phase_id == c.last_ack->phase_id && + reply->group_index == c.last_ack->group_index && reply->revision == c.last_ack->revision) { + return *c.after_last_ack; + } + if (c.complete) return rejected("phase already complete"); + if (!c.pending || reply->phase_id != c.pending->phase_id || + reply->group_index != c.pending->group_index || reply->revision != c.pending->revision) + return rejected("stale or mismatched result acknowledgement"); + + MatchGroup& grp = c.groups->at(c.pending->group_index); + if (c.pending->kind == PhaseResultKind::League) { + stir_random(*c.game, *c.rand); + } + finish_group_phase(*c.state, grp, c.last, *c.game); + c.next_group = c.pending->group_index + 1; + c.last_ack = *reply; + ++c.revision; + c.pending.reset(); + PhaseEndOutput out = advance_phase_end(c); + c.after_last_ack = out; + return out; +} + +void end_phase(GameState& g, std::vector& groups, int last, const std::vector& buttons, + GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function&, + const GameState&)>& presenter) { + PhaseEndCursor cursor; + PhaseEndOutput out = begin_phase_end(cursor, 1, g, groups, last, buttons, game, rand, report); + while (out.status == PhaseEndStatus::Waiting && out.request) { + const PhaseResultRequest& req = *out.request; + if (presenter) presenter(req, groups, g); + out = continue_phase_end(cursor, PhaseResultReply{req.phase_id, req.group_index, req.revision}); + } +} + +void play_matchday(MatchEngine& engine, GameState& g, std::vector& groups, + const std::vector& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& after_minute, int stop_at) { + // EndPhase calls of the matchday: outdoors two halves (4 minutes of stoppage in the + // second) and extra time; the indoor tournament (CareerSessionRuntimeField) plays 2 x 20 minutes + const int outdoor[4][4] = {{1, 45, 0, 0}, {46, 90, 4, 0}, {91, 105, 0, 1}, {106, 120, 1, 1}}; + const int indoor[2][4] = {{1, 20, 0, 0}, {21, 40, 0, 0}}; + engine.indoor = g.indoor; + std::vector> phases; + if (g.indoor) + for (const auto& p : indoor) phases.push_back({p[0], p[1], p[2], p[3]}); + else + for (const auto& p : outdoor) phases.push_back({p[0], p[1], p[2], p[3]}); + for (const auto& p : phases) { + play_phase(engine, groups, p[0], p[1], p[2], p[3], report, after_minute); + if (report.unsupported) return; + if (p[1] == stop_at) return; + end_phase(g, groups, p[1], buttons, game, rand, report, engine.phase_results); + if (report.unsupported) return; + // FinishEvent / BuildSideRecords: EvaluatePoolsCoupon(0) after the second half (outdoors) + if (!g.indoor && p[1] == 90) evaluate_pools_coupon(g, groups); + } + // CupTie2: penalty shoot-outs + for (MatchGroup& grp : groups) + for (int m = 0; m < grp.matches() && !report.unsupported; m++) + if ((grp.flags() & 8) && !grp.cup_results.empty() && (grp.cup_results[size_t(m)] >> 11) != 0) + engine.penalty_shootout(grp, m, report); +} + +} // namespace bmh diff --git a/src/game/driver.hpp b/src/game/driver.hpp new file mode 100644 index 0000000..1342a26 --- /dev/null +++ b/src/game/driver.hpp @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The matchday driver after the kick-off (FinishEvent + BuildSideRecords, BMH.exe V2.24). +// +// The driver plays the phases one after another with EndPhase(first, last, +// stoppage, phase): +// 1..45 (no stoppage), 46..90 (+ up to 4), then 91..105 and 106..120 (+ up to 1, +// phase 1 = extra time; indoor tournaments play 1..20 and 21..40 instead). +// A phase ends when every match has ended; a phase in which no match is running draws +// nothing. At the end of a phase (end_phase): +// - if any match played in the phase, the result screen of every group is called +// unless switched off at the desk, including groups already settled in regular +// time; leaving a league screen stirs the random numbers (stir_random), +// - at full time (90, 120, and 40 indoors) every match gets FinishMatch and is marked +// done, except cup ties decided on the day (descriptor flag 8) that are still level +// on aggregate (cup_tie): they go into extra time, after 120 minutes into the +// penalty shoot-out (CupTie2). + +#include +#include +#include +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// CupTie: state of a cup tie after match m of a group: 0 the home side is through, +// 1 the away side, 2 still level. Two-legged ties add the other leg (its home team is +// this match's away team); with descriptor flag 0x10 away goals count double while the +// match is in regular time. +int cup_tie(const MatchGroup& grp, int m); + +// Whether the result screen of a cup (CupGroupOverviewEffects with a phase end minute) is shown. +bool cup_screen_shown(const std::vector& buttons, int cup_id, int minute); + +// One phase: minutes first..last+stoppage until every match has ended. `after_minute` +// is called after each simulated minute (for checks). Stops early if the engine reports +// an unsupported path. +void play_phase(MatchEngine& engine, std::vector& groups, int first, int last, int stoppage, int phase, + MinuteReport& report, const std::function& after_minute = {}); + +// The end of EndPhase for a phase that ended at minute `last`. +void end_phase(GameState& g, std::vector& groups, int last, const std::vector& buttons, + GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function&, + const GameState&)>& presenter = {}); + +// Nonblocking end-of-phase result barrier. The cursor borrows the original mutable +// objects for its whole lifetime; do not copy/move it or independently mutate those +// objects while pending. Native viewer actions use the owning synchronous App dispatcher; +// it must preserve group identity and never resume simulation. Cup entry effects precede +// presentation; league exit RNG and match settlement belong to the single ACK. +// Only presentation metadata and a bounded last-ACK record are owned. +enum class PhaseResultKind { League, Cup }; +struct PhaseResultMatch { + int home_team = 0; + int away_team = 0; + bool score_known = false; + int home_score = 0; + int away_score = 0; +}; +struct PhaseResultRequest { + uint64_t phase_id = 0; + uint32_t group_index = 0; + uint64_t revision = 0; + PhaseResultKind kind = PhaseResultKind::League; + int competition_id = 0; + int phase_end_minute = 0; + std::vector matches; +}; +struct PhaseResultReply { + uint64_t phase_id = 0; + uint32_t group_index = 0; + uint64_t revision = 0; +}; +enum class PhaseEndStatus { Waiting, Complete, Rejected }; +struct PhaseEndOutput { + PhaseEndStatus status = PhaseEndStatus::Complete; + std::optional request; + const char* reason = nullptr; +}; +struct PhaseEndCursor { + PhaseEndCursor() = default; + PhaseEndCursor(const PhaseEndCursor&) = delete; + PhaseEndCursor& operator=(const PhaseEndCursor&) = delete; + PhaseEndCursor(PhaseEndCursor&&) = delete; + PhaseEndCursor& operator=(PhaseEndCursor&&) = delete; + + bool initialized = false; + bool complete = false; + bool phase_played = false; // EndPhase local_48, frozen for all groups + uint64_t phase_id = 0; + uint64_t revision = 0; + uint32_t next_group = 0; + int last = 0; + std::vector buttons; // copied presentation settings + const std::vector* buttons_source = nullptr; // identity for repeated begin + GameState* state = nullptr; // borrowed, original object + std::vector* groups = nullptr; // borrowed, original objects + GameRandom* game = nullptr; // borrowed, original generator + WatcomRandom* rand = nullptr; // borrowed, original generator + MinuteReport* report = nullptr; // borrowed + std::optional pending; + std::optional last_ack; + std::optional after_last_ack; +}; + +// First call starts/resumes the phase; repeating begin with the same phase while waiting +// polls the identical request. A completed cursor may be reused for a later phase. +PhaseEndOutput begin_phase_end(PhaseEndCursor& cursor, uint64_t phase_id, GameState& g, + std::vector& groups, int last, + const std::vector& buttons, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); +// An empty reply polls without effects. Only an exact current (phase, group, revision) +// reply resumes the group. Duplicate last ACK returns its cached continuation; older or +// mismatched replies are rejected without state/RNG/cursor advancement. +PhaseEndOutput continue_phase_end(PhaseEndCursor& cursor, + const std::optional& reply = std::nullopt); + +// All phases of a matchday (not indoor): regular time, extra time where needed. +// `stop_at` (45, 90, 105 or 120) stops at the whistle of that phase, before its result +// screens and match bookkeeping (end_phase); 0 plays everything. +void play_matchday(MatchEngine& engine, GameState& g, std::vector& groups, + const std::vector& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& after_minute = {}, int stop_at = 0); + +} // namespace bmh diff --git a/src/game/environment.cpp b/src/game/environment.cpp new file mode 100644 index 0000000..8a77cf9 --- /dev/null +++ b/src/game/environment.cpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/environment.hpp" + +#include + +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/week.hpp" + +namespace bmh { + +namespace { + +constexpr uint32_t kSpending = ::bmh::layout::Spending; // + manager * 0x24 + item * 4 +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kYouthPaid = 0x880; // youth expenses booked this season +// EnvironmentRuntimeField: the step of each item in thousands (items 3..5: 5 000 per level) +constexpr int kUnit[kEnvironmentItems] = {2, 4, 5, 5, 5, 5}; + +uint32_t spending_at(int manager, int item) { return kSpending + uint32_t(manager) * 0x24 + uint32_t(item) * 4; } + +// TeamLeague3: the academy's season price by the club's league +int32_t youth_price(const GameState& g, int manager) { + const int league = team_league(g.manager_teams.at(size_t(manager))); + return league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000; +} + +// YouthOpen: July (unless the Bundesliga is past its 17th round) or August +bool youth_open(const GameState& g) { + const int month = month_code(g.date); + if (month == 7) return !(g.league_rounds.at(0) > 0x11); + return month == 8; +} + +bool youth_paid(const GameState& g, int manager) { + const size_t at = size_t(manager) * kRecordSize + kYouthPaid; + const uint32_t paid = uint32_t(g.manager_records.at(at)) | uint32_t(g.manager_records.at(at + 1)) << 8 | + uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24; + return paid >= uint32_t(youth_price(g, manager)); +} + +} // namespace + +EnvironmentState environment_state(const GameState& g, int manager) { + EnvironmentState s; + for (int i = 0; i < kEnvironmentItems; i++) { + s.monthly[size_t(i)] = int32_t(g.memory.u32(spending_at(manager, i))); + // the stars (SizeT7): staff value / step, the academy 6 when on, 0/2 none + if (i >= 3) s.level[size_t(i)] = std::clamp(s.monthly[size_t(i)] / (kUnit[i] * 1000), 0, 6); + else if (i == kYouthAcademy) s.level[size_t(i)] = s.monthly[size_t(i)] != 0 ? 6 : 0; + } + s.youth_price = youth_price(g, manager); + s.youth_paid = youth_paid(g, manager); + s.youth_open = youth_open(g); + return s; +} + +EnvironmentResult set_environment(GameState& g, int manager, int item, int level, std::string* message) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || item < 0 || item >= kEnvironmentItems || level < 0 || + level > 6 || !g.memory.has(spending_at(manager, item) + 3)) + return EnvironmentResult::invalid; + const uint32_t at = spending_at(manager, item); + const int32_t before = int32_t(g.memory.u32(at)); + int32_t value = 0; + EnvironmentResult result = EnvironmentResult::changed; + if (item >= 3) { + value = level * kUnit[item] * 1000; + } else if (item == kYouthAcademy) { + // YouthPrice: a click on an active academy means "off" + int wanted = level; + if (before != 0 && wanted != 0) wanted = 0; + const int32_t price = youth_price(g, manager); + if (!youth_paid(g, manager)) { + if (wanted == 0) { + value = 0; + } else if (!youth_open(g)) { + value = 0; + result = EnvironmentResult::too_late; + if (message) *message = message_text(g, ::bmh::layout::Environment_SetEnvironment_ExecutableField); // "Zu spät für diese Saison..." + } else { + value = price; + } + } else { + // paid this season: stays on; a click meant as "off" brings the second string of + // the same text block (*Environment_SetEnvironment_ExecutableField + 0x42) + value = price; + if (wanted == 0) { + result = EnvironmentResult::contract_runs; + if (message) { + *message = message_text_following(g, ::bmh::layout::Environment_SetEnvironment_ExecutableField); + // OpenBMH-authored notice when an edition has no academy tail text. + if (message->empty()) *message = "This academy contract stays active until the season ends."; + } + } + } + } + g.memory.set32(at, uint32_t(value)); + if (result == EnvironmentResult::changed && value == before) result = EnvironmentResult::unchanged; + return result; +} + +} // namespace bmh diff --git a/src/game/environment.hpp b/src/game/environment.hpp new file mode 100644 index 0000000..0d6aa9b --- /dev/null +++ b/src/game/environment.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: enables the supported youth academy and represents staff levels in monthly increments of five thousand. +// The club environment ("Umfeld", desk menu 24, H2 p. 93; supported rule profile manual p. 107, 111): +// the screen Image with the supported rule profile patch (SizeT7 / EnvironmentOperation / +// YouthPrice / YouthOpen). Six monthly running costs per manager live at +// Spending + manager * 0x24 (u32 each); the month change books them +// (month.cpp monthly_expenses) and the staff values steer training, injuries and healing. +// +// item 0, 2 the original's two other youth age groups: the patch always sets 0 +// item 1 the youth academy (supported rule profile): on or off. On it is the league's season price +// (TeamLeague3: 1.5 M, 1 M, 580 000, 280 000), paid in full at the next month +// change while record +0x880 (youth expenses this season) is below it. It can +// be switched on in July and August only ("Zu spät für diese Saison...") and +// not switched off once paid ("Der Vertrag läuft bis zum Saisonende."). +// item 3..5 co-trainer, doctor, physio: level 0..6 times 5 000 a month (EnvironmentRuntimeField) +// +// A click on a tile sets the level from the mouse position (supported rule profile: one click per value). + +#include +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +constexpr int kEnvironmentItems = 6; +enum EnvironmentItem : int { kYouthAcademy = 1, kCoTrainer = 3, kDoctor = 4, kPhysio = 5 }; + +struct EnvironmentState { + std::array monthly{}; // Spending values + std::array level{}; // the stars the screen draws (0..6) + int32_t youth_price = 0; // the season price of the academy for the club's league + bool youth_paid = false; // record +0x880 reached the price: cannot be switched off + bool youth_open = false; // July/August: the academy can still be switched on +}; + +EnvironmentState environment_state(const GameState& g, int manager); + +enum class EnvironmentResult : uint8_t { changed, unchanged, too_late, contract_runs, invalid }; + +// A click on `item` at `level` (0..6; for the academy any level > 0 means "on" and a click on +// an active academy switches it off). `message` gets the original's message box text, if any. +EnvironmentResult set_environment(GameState& g, int manager, int item, int level, std::string* message = nullptr); + +} // namespace bmh diff --git a/src/game/highscore.cpp b/src/game/highscore.cpp new file mode 100644 index 0000000..b85669f --- /dev/null +++ b/src/game/highscore.cpp @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/highscore.hpp" + +#include +#include +#include +#include +#include + +#include "game/weekly.hpp" + +namespace bmh { +namespace { +constexpr size_t kRecord = 0xb0c; +// OpenBMH deviates from the original: reads the supported edition-specific high-score format from the loaded image. +// supported rule profile executable HighscoreRuntimeField..a5144, verified against the installed LE image. +constexpr std::array kHistoryWeights{3, 5, 4, 30, 20, 10, 5, 40}; +constexpr std::array kNationalWeights{30, 20, 10, 5}; +constexpr std::array kTitleWeights{40, 30, 50}; +int32_t signed32(uint32_t v) { return std::bit_cast(v); } +uint16_t rec16(const GameState& g, int m, size_t offset) { + const size_t at = size_t(m) * kRecord + offset; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} +uint32_t rec32(const GameState& g, int m, size_t offset) { + return uint32_t(rec16(g, m, offset)) | uint32_t(rec16(g, m, offset + 2)) << 16; +} +uint8_t rec8(const GameState& g, int m, size_t offset) { + return g.manager_records.at(size_t(m) * kRecord + offset); +} +std::string record_name(const GameState& g, int m) { + std::string name; + for (size_t i = 0; i < 30; ++i) { + const auto c = rec8(g, m, 0xa8 + i); + if (!c) return name; + name.push_back(char(c)); + } + throw std::invalid_argument("highscore: unterminated manager name"); +} +// HighscoreScore(0x1f,0,0xff), deliberately using the Source global asset-manager. +int32_t net_assets(const GameState& g, int m) { + uint32_t sum = rec32(g, m, 0x314) + rec32(g, m, 0x318); + for (uint32_t k = 0; k < 6; ++k) + sum += uint32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c)) * + g.memory.u32(::bmh::layout::FundBlock + k * 0x1c); + for (size_t k = 0; k < 12; ++k) { + const size_t at = k * 0x5c; + const uint32_t held = uint16_t(g.stocks.at(at + 0x50 + size_t(m) * 2) | + g.stocks.at(at + 0x51 + size_t(m) * 2) << 8); + const uint32_t price = uint16_t(g.stocks.at(at + 0x4e) | g.stocks.at(at + 0x4f) << 8); + sum += held * price; + } + for (uint32_t k = 0; k < 5; ++k) + sum -= g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + k * 0x18); + return signed32(sum); +} +uint32_t read32(const uint8_t* p) { + return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; +} +void put32(uint8_t* p, uint32_t v) { + for (int k = 0; k < 4; ++k) p[k] = uint8_t(v >> (8 * k)); +} +std::string read_name(const uint8_t* p) { + size_t n = 0; + while (n < 30 && p[n]) ++n; + if (n == 30) throw std::invalid_argument("highscore: unterminated file name"); + return {reinterpret_cast(p), n}; +} +void put_name(uint8_t* p, const std::string& s) { + if (s.size() >= 30 || s.find('\0') != std::string::npos) + throw std::invalid_argument("highscore: name does not fit Source row"); + // strcpy preserves bytes beyond the terminator of an existing row. + std::copy(s.begin(), s.end(), p); + p[s.size()] = 0; +} +} // namespace + +HighscoreScore highscore_score(const GameState& g, int manager, HighscoreContext context) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) + throw std::invalid_argument("highscore: manager is outside active slots"); + HighscoreScore result; + const int team = g.manager_teams.at(size_t(manager)); + if (team == kNoTeam) { + // CareerSession_DispatchLineup_RuntimeField+CareerSession_InstallLeagueSizes_RuntimeField6+ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 == kNoTeam in the supported Original database; + // national honours store (team-kNoTeam)|0x80, so Germany's index is0. + for (uint32_t year = 0; year < 20; ++year) + for (uint32_t place = 0; place < 4; ++place) { + const uint8_t v = g.memory.u8(::bmh::layout::Placements + year * 4 + place); + if ((v & 0x80) && (v & 0x7f) == 0) + result.history += int32_t(kNationalWeights[place]) * 10; + } + } else { + if (g.season < 0) throw std::invalid_argument("highscore: negative season index"); + const int asset_manager = context == HighscoreContext::SeasonBoundary + ? int(g.manager_teams.size()) : int(g.memory.u8(::bmh::layout::ActiveManager)); + result.assets = std::min(net_assets(g, asset_manager) / 50000, 100); + result.patience = rec8(g, manager, 0x26f); + GameState facility_state = g; // facility_rating's public API takes mutable state. + int second = 0; + result.facilities = facility_rating(facility_state, manager, &second) * 4; + result.team = int(uint16_t(team_average(g, team, 0x2ff).value)) / 10; + const uint32_t count = std::min(uint32_t(g.season) + 1, 50u); + uint32_t history = 0; + for (uint32_t year = 0; year < count; ++year) { + const size_t at = 0xda + year * 3; + const uint8_t v = rec8(g, manager, at + 2); + history += uint32_t(rec8(g, manager, at)) + uint32_t(rec8(g, manager, at + 1)) * 2 + + uint32_t(kHistoryWeights[v >> 5]) * (v & 0x1f); + } + result.history = int32_t((history & 0xffff) / count); + } + uint32_t total = uint32_t(result.assets) + uint32_t(result.patience) + + uint32_t(result.facilities) + uint32_t(result.team) + uint32_t(result.history); + for (size_t k = 0; k < 3; ++k) + result.titles += int32_t(kTitleWeights[k]) * rec16(g, manager, 0x8a4 + k * 2); + total += uint32_t(result.titles); + result.total = std::max(signed32(total), 0); + return result; +} + +HighscoreRow highscore_candidate(const GameState& g, int manager, HighscoreContext context) { + if (g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == 0) return {}; + HighscoreRow row; + row.score = highscore_score(g, manager, context).total; + row.club_name = g.club_name(g.manager_teams.at(size_t(manager))); + row.manager_name = record_name(g, manager); + for (size_t k = 0; k < 3; ++k) row.titles[k] = rec16(g, manager, 0x8a4 + k * 2); + return row; +} + +void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate) { + size_t target = rows.size(); + for (size_t k = 0; k < rows.size(); ++k) + if (rows[k].manager_name == candidate.manager_name && rows[k].club_name == candidate.club_name) { + target = k; + break; + } + if (target == rows.size() && rows.back().score < candidate.score) target = rows.size() - 1; + if (target == rows.size()) return; + rows[target] = candidate; + // Swap uses these pairwise swaps; preserve equal-score ordering exactly. + for (size_t a = 0; a < 4; ++a) + for (size_t b = a + 1; b < 5; ++b) + if (rows[a].score < rows[b].score) std::swap(rows[a], rows[b]); +} + +HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable rows, HighscoreContext context) { + HighscoreProjection out; + out.signature = g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7); + out.ranked = out.signature != 0; + out.rows = std::move(rows); + if (!out.ranked) return out; + // GameEndAlternateScoreScreen gates the entire manager loop using slot0, not each candidate's team. + if (!g.manager_teams.empty() && + (g.manager_teams[0] != kNoTeam || (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) == 0)) + for (size_t m = 0; m < g.manager_teams.size(); ++m) + insert_highscore(out.rows, highscore_candidate(g, int(m), context)); + return out; +} + +HighscoreBytes encode_highscore_table(const HighscoreTable& rows) { + HighscoreBytes bytes{}; + for (size_t k = 0; k < rows.size(); ++k) { + uint8_t* p = bytes.data() + k * 72; + std::copy(rows[k].original_bytes.begin(), rows[k].original_bytes.end(), p); + put32(p, uint32_t(rows[k].score)); + put_name(p + 4, rows[k].club_name); + put_name(p + 0x22, rows[k].manager_name); + for (size_t t = 0; t < 3; ++t) { + p[0x40 + t * 2] = uint8_t(rows[k].titles[t]); + p[0x41 + t * 2] = uint8_t(rows[k].titles[t] >> 8); + } + } + return bytes; +} +HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) { + HighscoreTable rows{}; + for (size_t k = 0; k < rows.size(); ++k) { + const uint8_t* p = bytes.data() + k * 72; + std::copy(p, p + 72, rows[k].original_bytes.begin()); + rows[k].score = signed32(read32(p)); + rows[k].club_name = read_name(p + 4); + rows[k].manager_name = read_name(p + 0x22); + for (size_t t = 0; t < 3; ++t) rows[k].titles[t] = uint16_t(p[0x40 + t * 2] | p[0x41 + t * 2] << 8); + } + return rows; +} +std::filesystem::path highscore_file(const std::filesystem::path& base, uint16_t signature, const std::string& prefix) { + if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file"); + return base / (prefix + std::to_string(signature)); +} +HighscoreTable load_highscore_table(const std::filesystem::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) { + HighscoreTable empty{}; + save_highscore_table(file, empty); // Read creates a zero table on a missing file. + return empty; + } + HighscoreBytes bytes{}; + in.read(reinterpret_cast(bytes.data()), bytes.size()); + return decode_highscore_table(bytes); +} +bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) { + const auto bytes = encode_highscore_table(rows); + std::ofstream out(file, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(reinterpret_cast(bytes.data()), bytes.size()); + return bool(out); +} +} // namespace bmh diff --git a/src/game/highscore.hpp b/src/game/highscore.hpp new file mode 100644 index 0000000..4f99215 --- /dev/null +++ b/src/game/highscore.hpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +// HighscoreOperation / GameEndAlternateScoreScreen. Names retain Original ISO646-DE bytes. +struct HighscoreRow { + int32_t score = 0; + std::string club_name; + std::string manager_name; + std::array titles{}; + // Preserve unused/trailing bytes of an existing Source row when saving it again. + std::array original_bytes{}; +}; +using HighscoreTable = std::array; +using HighscoreBytes = std::array; + +struct HighscoreProjection { + uint16_t signature = 0; // CareerSession_FormatError_RuntimeField7: any nonzero signature selects its own ranked file. + bool ranked = false; // signature0 selects Source's alternate visualization. + HighscoreTable rows{}; +}; + +struct HighscoreScore { + int32_t assets = 0; + int32_t patience = 0; + int32_t facilities = 0; + int32_t team = 0; + int32_t history = 0; + int32_t titles = 0; + int32_t total = 0; +}; + +enum class HighscoreContext { ActiveManager, SeasonBoundary }; +// Assets in HighscoreScore use global ActiveManager even when scoring another manager. At the +// season boundary DailyInterest's preceding manager loop leaves ActiveManager=manager_count. +// Pass that context explicitly without modifying the caller's continuation state. +HighscoreScore highscore_score(const GameState& g, int manager, + HighscoreContext context = HighscoreContext::ActiveManager); +HighscoreRow highscore_candidate(const GameState& g, int manager, + HighscoreContext context = HighscoreContext::ActiveManager); +void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate); +HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable rows = {}, + HighscoreContext context = HighscoreContext::ActiveManager); + +HighscoreBytes encode_highscore_table(const HighscoreTable& rows); +HighscoreTable decode_highscore_table(const HighscoreBytes& bytes); +// The caller supplies the configured installation base and Original TEXTD889 prefix. +std::filesystem::path highscore_file(const std::filesystem::path& base, + uint16_t signature, const std::string& prefix = "high/h."); +HighscoreTable load_highscore_table(const std::filesystem::path& file); +bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows); + +} // namespace bmh diff --git a/src/game/human_buyer_sale.hpp b/src/game/human_buyer_sale.hpp new file mode 100644 index 0000000..145afca --- /dev/null +++ b/src/game/human_buyer_sale.hpp @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +struct MinuteReport; + +// The unsaved PendingOfferAnswer observation is owned by CareerSession. Missing evidence +// is unsupported; zero is never an implicit default. +enum class HumanBuyerSaleAllocatorGate : uint8_t { unsupported, zero, blocked }; +// OpenTransferEditor owns this unsaved transient: its ordinary AI-seller entry starts at +// zero, while targeted human-seller processing may mark a list entry. The +// session must supply this only after observing the actual ordinary UI entry. +enum class HumanBuyerSaleDirectMode : uint8_t { unsupported, ordinary_ai_purchase }; + +enum class HumanBuyerSaleStatus : uint8_t { + moved, funds_refused, allocator_blocked, no_room, unsupported +}; + +// DispatchClubPlayerPendingOffers supplies param8 independently of FindManagerForClub's active-count +// lookup. Only the checked national pending caller may bind a retained raw +// owner or use parked record4 for a human buyer/movement board. +struct SourcePendingOwner { + int manager = -1; + int team = -1; +}; + +struct HumanBuyerSaleRequest { + int list_entry = -1; + int bid_slot = -1; + uint32_t list_address = 0; + size_t source_pool_slot = 0; + int expected_seller = -1; + int expected_buyer = -1; + int expected_active_manager = -1; + // -1 identifies a normal list row. Pending callers provide the explicit raw + // OfferSlots slot; the shared helper never manufactures raw+40 from this value. + int raw_offer_slot = -1; + // Poaching (src/game/poach.hpp): a direct sale on the special row 40..43 that + // Range2 prepared; no raw OfferSlots slot belongs to it. + bool poach = false; + // DayStepRest2/Range2 return-to-borrower re-offer on a special entry. This is + // a separate non-poaching Source owner and requires its exact OfferSlots marker. + bool loan_return_entry = false; + // The day step's list decision (TransferListCountdown -> Void2) passes buyer and seller + // managers to SettleHumanBuyerSale explicitly; whoever is on turn (ActiveManager) is not bound to + // them. Set for that caller: the active-manager checks below do not apply. + bool day_step = false; + // Only raw pending entries with reduced national runtime and a matching + // saved order/owner/record/pool qualify. Accounts use param8; movement still + // uses FindManagerForClub. Never changes ordinary/day-step/poach defaults. + std::optional source_pending_owner = std::nullopt; +}; + +struct HumanBuyerSaleNotice { + int manager = -1; + int list_entry = -1; + int raw_offer_slot = -1; + uint32_t source_text_address = 0; + std::string original_message; + uint16_t source_flags = 0; +}; + +struct HumanBuyerSalePaid { + int list_entry = -1; + int bid_slot = -1; + int raw_offer_slot = -1; + int player = -1; + int seller = -1; + int buyer = -1; + int seller_manager = -1; // SettleHumanBuyerSale accounting seller (DispatchClubPlayerPendingOffers param8) + int buyer_manager = -1; + uint32_t raw_fee = 0; + uint32_t adjusted_fee = 0; + uint32_t salary = 0; + uint8_t term = 0; +}; + +struct HumanBuyerSaleHooks { + HumanBuyerSaleAllocatorGate allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; + HumanBuyerSaleDirectMode direct_mode = HumanBuyerSaleDirectMode::unsupported; + std::function notice; + // Optional source caller acknowledgement after all deterministic transaction + // validation and immediately before SettleHumanBuyerSale. The direct adapter uses this + // for SubmitTransferBidSourceHumanBuyer's DeskActions_SubmitTransferBidImpl_ExecutableField ACK; pending callers leave it empty. + std::function before_accounts; + // Used only by the Void2 pending caller to preserve its severance/ACK/news + // sequence between SettleHumanBuyerSale and Fail. The direct SubmitTransferBidSourceHumanBuyer caller leaves + // this empty. It does not own list cleanup or Weekly_PendingSettleHumanBuyer_RuntimeField/DeskActions_EditorFail_RuntimeField2. + std::function after_paid_accounts; + // PresentManagerDialog yes/no question to a manager (poaching: the human seller agrees to the fee, + // the buyer accepts the fee the DFB sets). Required only for poaching. + std::function confirm; +}; + +struct HumanBuyerSaleResult { + HumanBuyerSaleStatus status = HumanBuyerSaleStatus::unsupported; + int player = -1; + int seller = -1; + int buyer = -1; + int seller_manager = -1; // SettleHumanBuyerSale accounting seller (DispatchClubPlayerPendingOffers param8) + int buyer_manager = -1; + uint32_t raw_fee = 0; + uint32_t adjusted_fee = 0; +}; + +// Shared exact SettleHumanBuyerSale account/subsidy and Fail ownership/board/history +// composition. Caller supplies explicit list and pool coordinates (ordinary +// 0..39 or special 40..43), owns staging, notices and any source-specific +// caller work. A successful move removes matching-player pool entries through +// ReleasePlayer. This helper never rewrites bids, performs caller-wide list/pool +// cleanup, or sets Weekly_PendingSettleHumanBuyer_RuntimeField/DeskActions_EditorFail_RuntimeField2. Unsupported boundaries require caller rollback. +HumanBuyerSaleResult settle_human_buyer_sale(GameState&, const HumanBuyerSaleRequest&, + const HumanBuyerSaleHooks&, WatcomRandom&, MinuteReport&); + +} // namespace bmh diff --git a/src/game/league_pairings.cpp b/src/game/league_pairings.cpp new file mode 100644 index 0000000..212d3de --- /dev/null +++ b/src/game/league_pairings.cpp @@ -0,0 +1,547 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/league_pairings.hpp" + +#include +#include +#include +#include + +#include "game/matchday.hpp" +#include "game/matchday_setup.hpp" +#include "game/match_engine.hpp" +#include "game/schedule.hpp" +#include "game/source_tip.hpp" +#include "game/table.hpp" + +namespace bmh { +namespace { +void require(bool value,const char* reason) { + if(!value) throw std::invalid_argument(reason); +} +void clear_computer_tip(LeaguePairingsOwner& owner) { + owner.computer_tip_active=false;owner.computer_tip_league=owner.computer_tip_round=-1; + owner.computer_tip_original.fill(0);owner.computer_tip_results.clear(); +} +void prepare_computer_tip(GameState& g,LeaguePairingsOwner& owner, + const LeaguePairingsConstants& c,GameRandom& game) { + const uint32_t preferences_at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(owner.manager); + require(!owner.filter_active&&!owner.postponed_active&& + (g.memory.u8(preferences_at)&0x0f)<=3, + "pairings: Computer Tip supports only ordinary/search modes 0..3"); + require(owner.round>=0&&size_t(owner.league)=kResultsSize, + "pairings: Computer Tip Native seed/results unavailable"); + const auto page=league_pairings_view_source(g,owner,c); + const size_t expected=league_fixtures(owner.league,owner.round+1).size(); + require(page.rows.size()==expected&&page.total_rows==int(expected), + "pairings: Computer Tip requires the complete ordinary fixture row set"); + for(const auto& row:page.rows) + require(row.raw_result==0xcc,"pairings: Computer Tip requires every visible result to be 0xcc"); + const int32_t source_seed=std::bit_cast(g.memory.u32(::bmh::layout::CurrentMatchday)); + require(source_seed>=0&&source_seed<=10000, + "pairings: Computer Tip rejects an unqualified signed Native seed"); + + const size_t first=result_index(owner.league,owner.round+1,0); + require(first+10<=g.results.size(),"pairings: Computer Tip ten-byte Source backup is unavailable"); + std::array original{}; + if(owner.computer_tip_active) { + require(owner.computer_tip_league==owner.league&&owner.computer_tip_round==owner.round&& + owner.computer_tip_results.size()==expected, + "pairings: stale Computer Tip forecast identity"); + original=owner.computer_tip_original; + for(size_t i=0;i<10;++i) + require(g.results[first+i]==original[i],"pairings: Native result slice changed under Computer Tip"); + } else { + std::copy_n(g.results.begin()+static_cast(first),10,original.begin()); + } + + struct Input { const LeaguePairingsRow* row; int home_rating,away_rating,home_secondary,away_secondary; }; + std::vector inputs;inputs.reserve(expected); + for(const auto& row:page.rows) { + require(row.source_round==owner.round&&row.fixture_index>=0&& + size_t(row.fixture_index) results;results.reserve(expected); + for(const auto& input:inputs) { + const auto& row=*input.row; + results.push_back({owner.league,row.source_round,row.fixture_index, + row.home.runtime_team,row.home.club_identity,row.away.runtime_team,row.away.club_identity, + row.raw_result,source_tip_result(staged_game,c.computer_tip_gap,input.home_rating,input.away_rating, + input.home_secondary,input.away_secondary)}); + } + game=staged_game;owner.computer_tip_active=true; + owner.computer_tip_league=owner.league;owner.computer_tip_round=owner.round; + owner.computer_tip_original=original;owner.computer_tip_results=std::move(results); + g.memory.set8(preferences_at,uint8_t(g.memory.u8(preferences_at)|0x10)); +} +int filtered_fixture_count(int league,int team) { + int count=0; + for(int round=0;round=0&&o.manager<4&& + size_t(o.manager)=0&&o.runtime_club<138))&& + size_t(o.runtime_club)=0&&o.league<9&&o.round>=0&&o.round=-1&&(!o.active_phase||o.active_group>=0), + "pairings: invalid active presentation phase"); + require(g.memory.has(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&& + (((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0c)==0)|| + (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==4|| + (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==8)&& + g.memory.has(::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2+1), + "pairings: missing preferences or unsupported saved list mode"); + require(g.results.size()>=kResultsSize&&g.club_ids.size()>=138&&g.league_rounds.size()>=9&& + g.memory.has(::bmh::layout::Postponed+0xef)&&g.memory.has(::bmh::layout::CompetitionCalendar+365*2+1), + "pairings: incomplete Native schedule"); + const auto selection_valid=[&](int team,int identity) { + return team<0 ? team>=-2&&identity==-1 : + team<138&&team_league(team)==o.league&&g.club_ids.at(size_t(team))==identity; + }; + require(selection_valid(o.search_first,o.search_first_identity)&& + selection_valid(o.search_second,o.search_second_identity)&& + (o.search_first!=-1 || (o.search_second==-1&&!o.search_second_click))&& + (o.search_first!=-2 || (o.search_second==-2&&!o.search_second_click))&& + (o.search_first==-1 || (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==2)&& + (!o.search_second_click || (o.search_first>=0&&o.search_second>=-1)), + "pairings: stale or invalid search selection"); + const uint8_t mode=uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f); + const bool mode8=mode==8; + if(mode8) { + require(o.postponed_active&&!o.filter_active&&o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&& + o.search_first==-1&&o.search_second==-1&&o.search_first_identity==-1&&o.search_second_identity==-1&& + !o.search_second_click&&o.postponed_offset>=0&&o.postponed_offset%10==0, + "pairings: invalid postponed-list owner"); + const int count=postponed_fixture_count(g,o.league); + require((count==0&&o.postponed_offset==0)||(count>0&&o.postponed_offset=int(g.league_rounds.at(size_t(o.league)))&& + o.computer_tip_results.size()==expected&&g.memory.has(::bmh::layout::CurrentMatchday), + "pairings: invalid Computer Tip owner scope"); + const size_t first=result_index(o.league,o.round+1,0); + require(first+10<=g.results.size(),"pairings: Computer Tip result backup is unavailable"); + for(size_t n=0;n<10;++n) + require(g.results[first+n]==o.computer_tip_original[n], + "pairings: Computer Tip original result slice changed"); + const auto fixtures=league_fixtures(o.league,o.round+1); + require(fixtures.size()==expected,"pairings: Computer Tip fixture count changed"); + for(size_t n=0;n=0&&o.filter_offset%10==0&&o.filter_team>=-2, + "pairings: invalid Source club-filter mode"); + if(o.filter_team>=0) { + require(o.filter_team<138&&team_league(o.filter_team)==o.league&& + g.club_ids.at(size_t(o.filter_team))==o.filter_identity&& + (o.filter_offset==0||o.filter_offset(g.league_rounds.at(size_t(league)),league_matchdays(league)-1); +} +LeaguePairingsTeam team_view(const GameState& g,int team,int played) { + LeaguePairingsTeam out; out.runtime_team=team;out.club_identity=g.club_ids.at(size_t(team)); + if(played) { + const int r=played-1; + const size_t at=(size_t(team)*13+size_t(r/3))*2; + require(at+1>((r%3)*5))&31)+1; + } + constexpr std::array flags{0x1f1,0x1f2,0x1f4,0x1f8,0x1ff}; + for(size_t n=0;n0&&c.domestic_league_count<=9, + "pairings: unsupported Source calendar constants"); + require(c.calendar_class.at(size_t(league))<32,"pairings: invalid calendar mask shift"); + const uint32_t mask=league>=c.domestic_league_count?0x10u:1u<0xcc;} + +std::optional league_pairings_active_packet_source( + const GameState& g,const LeaguePairingsOwner& owner,const std::vector& groups, + std::span referee_profiles) { + validate(g,owner); + // Mode4's armed -2 sentinel still uses the ordinary selected-round list. + // A selected filter and Mode8 explicitly clear local74 in Move. + if(owner.postponed_active||(owner.filter_active&&owner.filter_team>=0))return std::nullopt; + const auto fixtures=league_fixtures(owner.league,owner.round+1); + int found=-1; + for(size_t n=0;n=2&&group.fixtures[0]==fixtures.front().home&& + group.fixtures[1]==fixtures.front().away)found=int(n); + } + if(found<0)return std::nullopt; + const auto& group=groups[size_t(found)]; + require(group.fixtures.size()==fixtures.size()*2, + "pairings: incomplete active fixture vector"); + LeaguePairingsActivePacket packet; + packet.league=owner.league;packet.round=owner.round;packet.group_index=found; + packet.rows.reserve(fixtures.size()); + for(size_t n=0;n0x50+n, + "pairings: incomplete active referee/weather descriptor"); + const uint8_t referee=group.desc[0x10+n]; + require(size_t(referee)=0)&& + packet.league==owner.league&&packet.round==owner.round&&packet.group_index>=0&& + packet.group_index==owner.active_group,"pairings: stale active descriptor owner"); + const auto fixtures=league_fixtures(owner.league,owner.round+1); + require(packet.rows.size()==fixtures.size(),"pairings: incomplete active presentation rows"); + for(size_t n=0;n=0&&manager<4&&size_t(manager)=0&&out.runtime_club<138))&& + size_t(out.runtime_club)=0&&(e.value==0||e.value==1)&&bool(e.value)!=before.active_phase, + "pairings: invalid active presentation redraw"); + out.active_phase=bool(e.value);break; + case LeaguePairingsAction::reset: out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));reset();break; + case LeaguePairingsAction::previous: + if(out.postponed_active) {if(out.postponed_offset>=10)out.postponed_offset-=10;break;} + if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) { + if(out.filter_active&&out.filter_offset>=10)out.filter_offset-=10; + break; + } + out.round=(out.round+league_matchdays(out.league)-1)%league_matchdays(out.league);out.title_round=out.round;break; + case LeaguePairingsAction::next: + if(out.postponed_active) { + const auto page=league_pairings_view_source(g,before,c); + if(page.rows.size()==10&&out.postponed_offset+10=0&& + out.filter_offset+10=0&&out.league<9,"pairings: invalid manager league preference"); + [[fallthrough]]; + case LeaguePairingsAction::select_league: + if(e.kind==LeaguePairingsAction::select_league) { + require(e.value>=0&&e.value<9,"pairings: invalid league selection");out.league=e.value; + } + if(out.league!=before.league) { + // LeagueMatchdays: retained round must be in the league and at/before + // its next round. Directparam0 does not apply the automatic reset. + if(out.round>=league_matchdays(out.league)||out.round>g.league_rounds.at(size_t(out.league))) + out.round=current_round(g,out.league); + out.title_round=out.round; + reset(); + } + break; + case LeaguePairingsAction::team_info: + case LeaguePairingsAction::search_team: { + require(!out.filter_active&&!(e.kind==LeaguePairingsAction::search_team&&out.postponed_active), + "pairings: filtered rows cannot open ordered search"); + require((e.kind==LeaguePairingsAction::search_team)==(out.search_first!=-1), + "pairings: row action does not match Source search ownership"); + const auto view=league_pairings_view_source(g,before,c);bool found=false; + for(const auto& row:view.rows)for(const auto* team:{&row.home,&row.away}) + found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity; + require(found,"pairings: stale fixture team identity"); + if(e.kind==LeaguePairingsAction::team_info)break; + if(!out.search_second_click) { + out.search_first=e.value;out.search_first_identity=e.expected_club_identity; + out.search_second=-1;out.search_second_identity=-1;out.search_second_click=true; + } else { + out.search_second=e.value;out.search_second_identity=e.expected_club_identity; + // LeagueMatchdays2 scans directed home/away fixtures in ascending round + // then row order. A missing self-pair keeps round and local30=1. + for(int round=0;roundruntime_team==e.value&&team->club_identity==e.expected_club_identity; + require(found,"pairings: stale filtered-row team identity"); + out.filter_team=e.value;out.filter_identity=e.expected_club_identity; + while(out.filter_offset>=filtered_fixture_count(out.league,out.filter_team)&&out.filter_offset>0) + out.filter_offset-=10; + break; + } + case LeaguePairingsAction::close: + reset();g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager), + uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xef)); + out.active_phase=false;out.active_group=-1; + out.closed=true;stir_random(game,rand);return out; + case LeaguePairingsAction::unsupported: + throw std::invalid_argument("pairings: Original Zusatzaktion ist noch nicht verfügbar"); + } + validate(g,out); + const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager); + if(e.kind!=LeaguePairingsAction::computer_tip) + g.memory.set8(at,uint8_t(g.memory.u8(at)&0xef)); + return out; +} + +LeaguePairingsView league_pairings_view_source(const GameState& g,const LeaguePairingsOwner& o, + const LeaguePairingsConstants& c) { + validate(g,o);LeaguePairingsView out;out.owner=o;out.played_rounds=g.league_rounds.at(size_t(o.league)); + out.total_rounds=league_matchdays(o.league);out.preferences=g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager)); + const bool postponed=o.postponed_active; + if(!postponed)out.match_date=round_date(g,o.league,o.round,c); + auto append_row=[&](int round,size_t n,const Fixture& fixture) { + LeaguePairingsRow row; + row.source_round=round;row.fixture_index=int(n); + row.home=team_view(g,fixture.home,out.played_rounds); + row.away=team_view(g,fixture.away,out.played_rounds); + row.raw_result=g.results.at(result_index(o.league,round+1,int(n))); + if(o.computer_tip_active) { + const auto match=std::find_if(o.computer_tip_results.begin(),o.computer_tip_results.end(), + [&](const auto& tip) {return tip.league==o.league&&tip.source_round==round&& + tip.fixture_index==int(n)&&tip.home_runtime_team==row.home.runtime_team&& + tip.home_club_identity==row.home.club_identity&& + tip.away_runtime_team==row.away.runtime_team&& + tip.away_club_identity==row.away.club_identity;}); + if(match!=o.computer_tip_results.end()) { + require(row.raw_result==match->original_result, + "pairings: Native result changed under Computer Tip forecast"); + row.computer_tip_result=match->predicted_result; + } + } + if(postponed) { + for(uint32_t k=0;k<40;++k) { + const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at); + if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) { + row.postponed_queue_slot=uint8_t(k);row.postponed_day=day; + row.postponed_date=g.season_start+day;break; + } + } + } else if(!league_pairings_played_source(row.raw_result)&&row.raw_result!=0xcc) { + for(uint32_t k=0;k<40;++k) { + const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at); + if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) { + row.postponed_date=g.season_start+day;break; + } + } + } + if(!o.active_phase&&!postponed&&!(o.filter_active&&o.filter_team>=0)&&round>=out.total_rounds/2) { + const uint8_t raw=g.results.at(result_index(o.league,round+1-out.total_rounds/2,int(n))); + if(league_pairings_played_source(raw))row.first_leg_result=raw; + } + if(o.filter_active&&o.filter_team>=0&&row.raw_result==0xcc) + row.scheduled_date=round_date(g,o.league,round,c); + out.rows.push_back(std::move(row)); + }; + if(postponed) { + out.page_offset=o.postponed_offset; + for(int round=0;round=o.postponed_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]); + ++out.total_rows; + } + } + } else if(o.filter_active&&o.filter_team>=0) { + out.page_offset=o.filter_offset; + for(int round=0;round=o.filter_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]); + ++out.total_rows; + } + } + } else { + const auto fixtures=league_fixtures(o.league,o.round+1); + out.total_rows=int(fixtures.size()); + for(size_t n=0;n +#include +#include +#include +#include + +#include "game/state.hpp" +#include "game/random.hpp" + +namespace bmh { + +struct MatchGroup; + +// Normal LeagueScreenShown(2,0)->Move(0) only. The App owns the staged Native/W/G +// transaction. No mutator here calls a presenter, advances a day, or saves. +struct LeaguePairingsConstants { + std::array points_mode{}, calendar_class{}; + std::array computer_tip_gap{}; + uint8_t domestic_league_count=0; +}; +struct LeaguePairingsTipResult { + int league=-1,source_round=-1,fixture_index=-1; + int home_runtime_team=-1,home_club_identity=-1,away_runtime_team=-1,away_club_identity=-1; + uint8_t original_result=0xcc,predicted_result=0xcc; + bool operator==(const LeaguePairingsTipResult&) const=default; +}; +struct LeaguePairingsOwner { + int manager=-1, runtime_club=-1, club_identity=-1, league=-1, round=-1, title_round=-1; + uint8_t league_group=0; + bool supported=false, closed=false; + // Move local28 and its current active descriptor. Process-only; + // neither field is serialized or changes the league fixture/result arrays. + bool active_phase=false; + int active_group=-1; + // Move locals60/50/30. -1 means ordinary row TeamInfo, -2 is the + // freshly armed search sentinel. Saved preference2 alone does not arm it. + int search_first=-1,search_second=-1; + int search_first_identity=-1,search_second_identity=-1; + bool search_second_click=false; + // Move mode4 has a separate single-club filter; its selection is not + // the ordered two-team search state above. -2 is freshly armed, -1 inactive. + int filter_team=-1,filter_identity=-1,filter_offset=0; + bool filter_active=false; + // Move mode8 owns a separate postponed-result list and ten-row page. + int postponed_offset=0; + bool postponed_active=false; + // KI-Tipp is a one-redraw runtime forecast, keyed to the actual fixture + // identities. Its ten-byte original slice includes unplayed/padding bytes; + // the forecast never writes that slice back to serialized Native results. + bool computer_tip_active=false; + int computer_tip_league=-1,computer_tip_round=-1; + std::array computer_tip_original{}; + std::vector computer_tip_results; + bool operator==(const LeaguePairingsOwner&) const=default; +}; +struct LeaguePairingsTeam { + int runtime_team=-1, club_identity=-1; + int previous_rank=-1; // TablePosition, already 1-based; absent before round1. + std::array strength{}; // 1f1,1f2,1f4,1f8,1ff, Void6. +}; +struct LeaguePairingsActiveRow { + int source_round=-1,fixture_index=-1; + int home_runtime_team=-1,home_club_identity=-1,away_runtime_team=-1,away_club_identity=-1; + uint8_t referee_index=0,referee_profile=0,weather=0; + int8_t temperature=0; + std::string referee_name; // Original bytes from MasterDatabaseMetadata -> ba370. + bool operator==(const LeaguePairingsActiveRow&) const=default; +}; +struct LeaguePairingsActivePacket { + int league=-1,round=-1,group_index=-1; + std::vector rows; + bool operator==(const LeaguePairingsActivePacket&) const=default; +}; +struct LeaguePairingsRow { + LeaguePairingsTeam home,away; + uint8_t raw_result=0xcc; + std::optional computer_tip_result; + std::optional postponed_date,scheduled_date; + std::optional postponed_day; + std::optional postponed_queue_slot; + std::optional first_leg_result; + // Native/source coordinates survive a multi-round filtered projection. + int source_round=-1,fixture_index=-1; +}; +struct LeaguePairingsView { + LeaguePairingsOwner owner; + int played_rounds=0, total_rounds=0; + int total_rows=0,page_offset=0; + uint8_t preferences=0; + uint32_t match_date=0xffff; + std::vector rows; +}; +enum class LeaguePairingsAction { reset,previous,next,select_league,toggle_group,team_info,close,unsupported,search,search_team,filter_by_club,filter_club,postponed_list,computer_tip,presentation_redraw }; +struct LeaguePairingsEvent { + LeaguePairingsAction kind=LeaguePairingsAction::unsupported; + int value=-1; + int expected_club_identity=-1; // stable team identity for TeamInfo/search/filter. +}; + +LeaguePairingsOwner open_league_pairings_source(GameState&,int manager,const LeaguePairingsConstants&); +LeaguePairingsOwner edit_league_pairings_source(GameState&,const LeaguePairingsOwner&, + const LeaguePairingsEvent&,const LeaguePairingsConstants&,GameRandom&,WatcomRandom&); +// Pure, bounded Source projection; renderers never call a Native/RNG mutator. +LeaguePairingsView league_pairings_view_source(const GameState&,const LeaguePairingsOwner&, + const LeaguePairingsConstants&); +// Read only active process descriptors, never reconstruct weather/referees from +// saved bytes or run event preparation. Last first-pair match follows Move. +std::optional league_pairings_active_packet_source( + const GameState&,const LeaguePairingsOwner&,const std::vector&, + std::span referee_profiles); +void validate_league_pairings_active_packet_source(const GameState&,const LeaguePairingsOwner&, + const LeaguePairingsActivePacket&); +bool league_pairings_played_source(uint8_t raw); +bool league_pairings_postponed_source(uint8_t raw); + +} // namespace bmh diff --git a/src/game/lineup.cpp b/src/game/lineup.cpp new file mode 100644 index 0000000..1dea703 --- /dev/null +++ b/src/game/lineup.cpp @@ -0,0 +1,866 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/lineup.hpp" + +#include +#include +#include +#include + +namespace bmh { + +namespace { + +// Position type by formation depth x (table at layout field). +constexpr int8_t kTypeByDepth[24] = {0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 1, 2, 2}; +// Position type of bench slots by slot index (table at layout field); 9 = any. +constexpr int8_t kTypeBySlot[24] = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 1, 2, 2, 3, 3, 9, 9, 9, 9, 9, 9, 9}; +constexpr int16_t kUnavailable = -32000; // 0x8300 +constexpr int kMismatchWeight = 0x40; // local_54 for computer teams + +constexpr size_t kManagerRecordSize = 0xB0C; +constexpr size_t kManagerBoardSize = 0x840; +constexpr size_t kBoardRowSize = 0x58; +constexpr size_t kFormationManagerSize = 0x160; +constexpr size_t kNativeFormationBlockSize = 0x580; + +uint8_t formation_byte(const GameState& g, size_t index) { + // The native byte table runs directly into the tactics block at 0x580. + // Int2 indexes through that contiguous memory for manager 3's + // indoor formations and reserve rows. + if (index < kNativeFormationBlockSize) return g.formations.at(index); + return g.tactics.at(index - kNativeFormationBlockSize); +} + +bool pitch_context_valid(const GameState& g, int manager, int team) { + if (manager < 0 || manager > 3 || team < 0 || team >= 138 || g.lineups_frozen || + !g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::GameMode) || + g.memory.u8(::bmh::layout::ActiveManager) != manager || g.memory.u8(::bmh::layout::GameMode) < 1 || g.memory.u8(::bmh::layout::GameMode) > 3 || + size_t(manager) >= g.manager_teams.size() || g.manager_teams[size_t(manager)] != team || + g.manager_of(team) != manager || size_t(team) >= g.team_flags.size() || + size_t(team) >= g.club_ids.size() || size_t(team + 1) * 2 > g.club_heap_78.size() || + g.manager_records.size() < size_t(manager + 1) * kManagerRecordSize || + g.manager_options.size() < size_t(manager + 1) * 5 || + g.tactics.size() < size_t(manager + 1) * kManagerBoardSize || + g.formations.size() < size_t(manager + 1) * kFormationManagerSize || + g.player_cards.size() != g.players.size()) + return false; + const size_t record = size_t(manager) * kManagerRecordSize; + const uint16_t record_team = uint16_t(g.manager_records[record + 0x290] | + uint16_t(g.manager_records[record + 0x291]) << 8); + if (record_team != uint16_t(team)) return false; + const SquadRange range = squad_range(team); + if ((range.count != 16 && range.count != 24) || range.first + range.count > g.squad_slots.size()) + return false; + bool empty_seen = false; + std::array seen{}; + size_t occupied = 0; + for (size_t row = 0; row < range.count; ++row) { + const uint16_t slot = g.squad_slots[range.first + row]; + const size_t id = slot & 0x0fff; + if (id == 0x0fff) { empty_seen = true; continue; } + if (empty_seen || id >= g.players.size() || seen[id]) return false; + seen[id] = true; + ++occupied; + } + if (occupied < 11) return false; + const size_t board = size_t(manager) * kManagerBoardSize; + for (size_t row = 0; row < 11; ++row) { + const uint16_t slot = g.squad_slots[range.first + row]; + const size_t id = slot & 0x0fff; + const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]); + const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]); + if (id >= g.players.size() || (slot & 0xc000) != 0x8000 || + depth < 0 || depth > 19 || lane < 0 || lane > 8) + return false; + const bool fit = ((g.players[id].w364 >> 16) & 0x1f) == 0; + if (fit) for (size_t prior = 0; prior < row; ++prior) { + const size_t prior_id = g.squad_slots[range.first + prior] & 0x0fff; + if (((g.players[prior_id].w364 >> 16) & 0x1f) != 0) continue; + const size_t other = board + prior * kBoardRowSize; + if (int8_t(g.tactics[other + 0x41]) == depth && + int8_t(g.tactics[other + 0x42]) == lane) + return false; + } + } + return true; +} + +bool optimized_pitch_valid(const GameState& g, int manager, int team) { + if (!pitch_context_valid(g, manager, team)) return false; + const SquadRange range = squad_range(team); + const size_t board = size_t(manager) * kManagerBoardSize; + std::array seen{}; + for (size_t row = 0; row < 11; ++row) { + const uint16_t slot = g.squad_slots[range.first + row]; + const size_t id = slot & 0x0fff; + const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]); + const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]); + if (id >= g.players.size() || seen[id] || (slot & 0xc000) != 0x8000 || + depth < 0 || depth > 19 || lane < 0 || lane > 8) + return false; + seen[id] = true; + } + return true; +} + +// Abs2-based detail score in Int2. Both preference fields come +// from the w35c value loaded from PlayerConditionTechniqueForm: +21 for depth and +24 for lane. +int16_t detailed_position_value(int16_t base, const Player& player, int x, int y, int detail) { + if (detail == 0 || player.position() == 0) return base; + const int role = player.position(); + const int preferred_y = int(player.w35c >> 24 & 7); + const int preferred_x = int(player.w35c >> 21 & 7) + (role - 1) * 7 + (role == 2); + const int delta_y = std::abs(y - preferred_y); + const int delta_x = std::abs(x - preferred_x); + const int loss = (detail * delta_y + (detail + 1) * delta_x) >> 1; + return int16_t(((100 - loss) * int(base)) / 100); +} + +bool run_pitch_optimizer(GameState& staged, int manager, int team, int formation) { + if (staged.lineups_frozen || formation < 0 || formation > 7) return false; + try { + auto_lineup(staged, team, 0xe4); + } catch (...) { + return false; + } + return staged.manager_options[size_t(manager) * 5] == formation + 1 && + optimized_pitch_valid(staged, manager, team); +} + +} // namespace + +void prepare_lineup_entry(GameState& g, int team) { + const int manager = g.manager_of(team); + const SquadRange range = squad_range(team); + if (manager < 0 || team < 0 || range.count < 11 || range.first + range.count > g.squad_slots.size()) + throw std::invalid_argument("prepare_lineup_entry: unsupported manager squad"); + const size_t badge = size_t(team) * 2; + if (badge + 1 >= g.club_heap_78.size()) + throw std::invalid_argument("prepare_lineup_entry: incomplete club badge table"); + + // SquadCount(team, 2) counts occupied IDs over the whole squad range. + // Original team rows are compact; reject a sparse map rather than applying + // its count as a row bound to a different layout. + size_t players = 0; + for (size_t row = 0; row < range.count; ++row) + players += (g.squad_slots[range.first + row] & 0x0fff) != 0x0fff; + if (players < 11) throw std::invalid_argument("prepare_lineup_entry: too few players"); + for (size_t row = 0; row < players; ++row) { + const int id = g.squad_slots[range.first + row] & 0x0fff; + if (id == 0x0fff || size_t(id) >= g.players.size()) + throw std::invalid_argument("prepare_lineup_entry: sparse or invalid squad"); + } + + // PrepareLineupEntry scans backward for the last row with either field/bench + // marker, then reassigns those marker bits by row, through row 16 only. + int last = -1; + for (int row = int(players) - 1; row >= 0; --row) + if (g.squad_slots[range.first + size_t(row)] & 0xc000) { last = row; break; } + for (int row = 0; row <= last && row < 17; ++row) { + uint16_t& slot = g.squad_slots[range.first + size_t(row)]; + slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000)); + } +} + +bool set_pitch_automatic_weight_source(GameState& g, int manager_slot, int runtime_club, + int weight_index, uint8_t old_weights, uint8_t new_weights) { + if (!pitch_context_valid(g, manager_slot, runtime_club) || weight_index < 0 || weight_index > 2 || + g.memory.u8(::bmh::layout::GameMode) == 1) + return false; + const size_t at = size_t(manager_slot) * kManagerRecordSize + 0x288; + if (g.manager_records[at] != old_weights) return false; + const unsigned shift = unsigned(weight_index * 2); + const uint8_t mask = uint8_t(3u << shift); + const uint8_t next_field = uint8_t((((old_weights >> shift) & 3u) + 1u) & 3u); + const uint8_t expected = uint8_t((old_weights & uint8_t(~mask)) | uint8_t(next_field << shift)); + if (new_weights != expected) return false; + try { + GameState staged = g; + staged.manager_records[at] = new_weights; + g = std::move(staged); + return true; + } catch (...) { + return false; + } +} + +bool move_pitch_player_source(GameState& g, int manager_slot, int runtime_club, + int row, int player_id, uint16_t slot, + int old_depth, int old_lane, int new_depth, int new_lane) { + if (!pitch_context_valid(g, manager_slot, runtime_club) || row < 0 || row >= 11 || + old_depth < 0 || old_depth > 19 || old_lane < 0 || old_lane > 8 || + new_depth < 0 || new_depth > 19 || new_lane < 0 || new_lane > 8 || + (old_depth == new_depth && old_lane == new_lane)) + return false; + const SquadRange range = squad_range(runtime_club); + const size_t record = range.first + size_t(row); + const size_t board = size_t(manager_slot) * kManagerBoardSize; + const size_t row_at = board + size_t(row) * kBoardRowSize; + if (g.squad_slots[record] != slot || (slot & 0x0fff) != player_id || + player_id < 0 || size_t(player_id) >= g.players.size() || (slot & 0xc000) != 0x8000 || + ((g.players[size_t(player_id)].w364 >> 16) & 0x1f) != 0 || + int8_t(g.tactics[row_at + 0x41]) != old_depth || + int8_t(g.tactics[row_at + 0x42]) != old_lane) + return false; + int exact_occupant = -1; + int indoor_partner = -1; + for (int other = 0; other < 11; ++other) { + if (other == row) continue; + const uint16_t other_slot = g.squad_slots[range.first + size_t(other)]; + const size_t other_id = other_slot & 0x0fff; + if (other_id >= g.players.size() || ((g.players[other_id].w364 >> 16) & 0x1f) != 0) continue; + const size_t other_at = board + size_t(other) * kBoardRowSize; + const int depth = int8_t(g.tactics[other_at + 0x41]); + const int lane = int8_t(g.tactics[other_at + 0x42]); + if (depth == new_depth && lane == new_lane) { + exact_occupant = other; + break; + } + const int dx = std::abs(new_depth - depth); + const int dy = std::abs(new_lane - lane); + if (dx < 2 && dy < 2) { + if (!g.indoor) return false; // Outdoor source branch refuses adjacent targets. + // PitchScreen keeps the last eligible hall neighbor encountered. + // The exact-coordinate branch above remains the ordinary swap path. + indoor_partner = other; + } + } + try { + GameState staged = g; + auto* selected = staged.tactics.data() + row_at; + if (exact_occupant >= 0) { + auto* occupied = staged.tactics.data() + board + size_t(exact_occupant) * kBoardRowSize; + const uint8_t occupied_depth = occupied[0x41], occupied_lane = occupied[0x42]; + occupied[0x41] = selected[0x41]; + occupied[0x42] = selected[0x42]; + selected[0x41] = occupied_depth; + selected[0x42] = occupied_lane; + } else { + // PitchScreen clears this row, its old hall partner and every + // reciprocal reference to either before installing the new move. + for (size_t other = 0; other < 24; ++other) { + auto* candidate = staged.tactics.data() + board + other * kBoardRowSize; + if (other == size_t(row) || + (indoor_partner >= 0 && other == size_t(indoor_partner)) || + candidate[0x3f] == uint8_t(row) || + (indoor_partner >= 0 && candidate[0x3f] == uint8_t(indoor_partner))) + candidate[0x3f] = 0xff; + } + selected[0x41] = uint8_t(new_depth); + selected[0x42] = uint8_t(new_lane); + if (g.indoor && indoor_partner >= 0) { + auto* partner = staged.tactics.data() + board + size_t(indoor_partner) * kBoardRowSize; + selected[0x3f] = uint8_t(indoor_partner); + partner[0x3f] = uint8_t(row); + } + } + staged.manager_options[size_t(manager_slot) * 5] = 0; // successful placement selects manual AA. + g = std::move(staged); + return true; + } catch (...) { + return false; + } +} + +bool apply_pitch_formation_source(GameState& g, int manager_slot, int runtime_club, + int formation, uint8_t expected_weights) { + if (!pitch_context_valid(g, manager_slot, runtime_club) || formation < 0 || formation > 7) + return false; + const size_t record = size_t(manager_slot) * kManagerRecordSize; + if (g.manager_records[record + 0x288] != expected_weights || + (g.manager_records[record + 0x218 + size_t(g.indoor)] & uint8_t(1u << formation)) == 0) + return false; + try { + GameState staged = g; + staged.manager_options[size_t(manager_slot) * 5] = uint8_t(formation + 1); + if (!run_pitch_optimizer(staged, manager_slot, runtime_club, formation)) return false; + g = std::move(staged); + return true; + } catch (...) { + return false; + } +} + +bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_club, + int formation, uint8_t expected_weights, + const std::array& formation_positions) { + if (!pitch_context_valid(g, manager_slot, runtime_club) || formation < 4 || formation > 7) + return false; // Ordinary Source access exposes only the four own slots for saving. + const size_t record = size_t(manager_slot) * kManagerRecordSize; + const size_t board = size_t(manager_slot) * kManagerBoardSize; + const size_t table = size_t(manager_slot) * kFormationManagerSize + + (g.indoor ? 0xb0 : 0) + size_t(formation) * 0x16; + const size_t mask = record + 0x218 + size_t(g.indoor); + if (g.manager_records[record + 0x288] != expected_weights || + table + formation_positions.size() > g.formations.size()) + return false; + for (size_t row = 0; row < 11; ++row) { + const uint16_t slot = g.squad_slots[squad_range(runtime_club).first + row]; + const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]); + const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]); + if ((slot & 0xc000) != 0x8000 || depth < 0 || depth > 19 || lane < 0 || lane > 8 || + formation_positions[row] != uint8_t(depth) || + formation_positions[11 + row] != uint8_t(lane)) + return false; + } + try { + GameState staged = g; + std::copy(formation_positions.begin(), formation_positions.end(), staged.formations.begin() + std::ptrdiff_t(table)); + staged.manager_records[mask] |= uint8_t(1u << formation); + staged.manager_options[size_t(manager_slot) * 5] = uint8_t(formation + 1); + if (!run_pitch_optimizer(staged, manager_slot, runtime_club, formation)) return false; + g = std::move(staged); + return true; + } catch (...) { + return false; + } +} + +static void auto_lineup_impl(GameState& g, int team, int mode, int manager) { + if (team >= 138 && team != kNoTeam) return; // teams without squads + if (g.lineups_frozen) return; // LineupRuntimeField (the season change) + const bool improve_from_reserves = (mode & 0x80) != 0; + mode &= 0x7F; + + // HumanManagerLetsAssistantPickTeamWhen: a human manager lets the assistant pick the team when his option byte 0 + // is set; its value - 1 is the formation, taken from the manager's own formation set. + int formation = 0, set = 0; + int weight = kMismatchWeight, familiarity = 0, detail = 0; + if (manager >= 0) { + const uint8_t raw_option = manager < 4 ? g.manager_options.at(size_t(manager) * 5) : 0; + const int option = int8_t(raw_option - 1); + if (raw_option == 0) { + // Int2: with a manual human line-up, modes below 100 only + // copy formation coordinates to a transient scratch table; mode + // 0x65 (101) and all other modes below 100 return without mutating + // the saved line-up. GameState has no such scratch table, so that + // non-persistent coordinate copy is intentionally not represented. + // The source enters DispatchLiveOverview only when the club-table bit in + // *ClubBadgeSelectors agrees with CareerSessionRuntimeField. We retain that boundary rather + // than applying the human normalizer to a different game mode. + const size_t club_word = size_t(team) * 2; + if (club_word + 1 >= g.club_heap_78.size()) + throw std::invalid_argument("auto_lineup: incomplete club badge table"); + uint16_t badge_word = uint16_t(g.club_heap_78[club_word] | + uint16_t(g.club_heap_78[club_word + 1]) << 8); + const bool mode_mismatch = ((badge_word >> 9) & 1) != unsigned(g.indoor); + if (mode_mismatch) { + // Int2 does not reject a manual club on a mode transition. + // It clears the stored badge selector to bit 0, sets its indoor bit + // from CareerSessionRuntimeField, and falls through to the ordinary assistant + // scorer with formation 0. Keep the manager's assistant scoring + // parameters below; AA itself remains off. + badge_word = uint16_t((badge_word & 0x01ff) | (unsigned(g.indoor) << 9)); + g.club_heap_78[club_word] = uint8_t(badge_word); + g.club_heap_78[club_word + 1] = uint8_t(badge_word >> 8); + formation = 0; + set = manager; + const uint8_t style = g.manager_records.at(size_t(manager) * 0xB0C + 0x288); + weight = 1 << ((style & 3) + 4); + familiarity = (style >> 4) & 3; + if (g.level >= 6) detail = (style >> 2) & 3; + } else { + if (mode == 0x65 || mode < 100) return; + const SquadRange range = squad_range(team); + const size_t board_base = size_t(manager) * 0x840; + if (range.count < 11 || range.first + range.count > g.squad_slots.size() || + g.tactics.size() < board_base + 0x840 || g.player_cards.size() != g.players.size()) + throw std::invalid_argument("auto_lineup: incomplete manual line-up state"); + + size_t player_count = 0; + for (size_t row = 0; row < range.count; ++row) + player_count += (g.squad_slots[range.first + row] & 0x0fff) != 0x0fff; + // DispatchLiveOverview works on whatever count the squad has: a short squad simply + // fields fewer players. That happens to the national team outside the world + // mode, which nobody nominates, when its human coach takes it over on an + // international day (SwapManagerSlots2 -> Int2(0x165, 0xe4)). + if (player_count > range.count) + throw std::invalid_argument("auto_lineup: manual line-up has an invalid squad size"); + for (size_t row = 0; row < player_count; ++row) { + const size_t id = g.squad_slots[range.first + row] & 0x0fff; + if (id == 0x0fff || id >= g.players.size()) + throw std::invalid_argument("auto_lineup: manual line-up has a sparse squad"); + } + + auto board = [&](size_t row) { return g.tactics.data() + board_base + row * 0x58; }; + auto fit = [&](size_t row) { + const int id = g.squad_slots[range.first + row] & 0x0fff; + return id != 0x0fff && size_t(id) < g.players.size() && + (g.players[size_t(id)].w364 >> 16 & 0x1f) == 0; + }; + // DispatchLiveOverview / Fit: move a fit player from the end of the + // roster into each injured row in the first 17 slots. Coordinates + // stay with the destination board row after the full 0x58-byte swap. + for (size_t row = 0; row < 17 && row < player_count; ++row) { + if (fit(row)) continue; + size_t replacement = player_count; + while (replacement > 0) { + --replacement; + if (fit(replacement)) break; + } + if (!fit(replacement) || replacement <= row) break; + std::swap(g.squad_slots[range.first + row], g.squad_slots[range.first + replacement]); + std::swap_ranges(board(row), board(row) + 0x58, board(replacement)); + std::swap(board(row)[0x41], board(replacement)[0x41]); + std::swap(board(row)[0x42], board(replacement)[0x42]); + } + // DispatchLiveOverview: clear old status nibbles; fit players in the first + // 11 rows start, the next six are bench. Invalid fit-player + // coordinates are initialized to (0,0) as in the original. + for (size_t row = 0; row < player_count; ++row) { + uint16_t& slot = g.squad_slots[range.first + row]; + slot &= 0x0fff; + if (fit(row) && row < 17) { + slot |= uint16_t(row < 11 ? 0x8000 : 0x4000); + const int8_t x = int8_t(board(row)[0x41]), y = int8_t(board(row)[0x42]); + if (row < 11 && (x < 0 || x > 19 || y < 0 || y > 8)) { + board(row)[0x42] = 0; + board(row)[0x41] = board(row)[0x42]; + } + } + } + // GatedByParamLive updates only players in flagged rows, preserving the + // card's high bits and replacing its slot index in low five bits. + for (size_t row = 0; row < player_count; ++row) { + const uint16_t slot = g.squad_slots[range.first + row]; + if ((slot & 0xc000) == 0) continue; + const size_t id = slot & 0x0fff; + g.player_cards[id] = uint16_t((g.player_cards[id] & 0xffe0) | row); + } + return; + } + } + if (raw_option != 0) { + if (option == -1) throw std::invalid_argument("auto_lineup: invalid human formation option"); + formation = option; + set = manager; + const uint8_t style = g.manager_records.at(size_t(manager) * 0xB0C + 0x288); // assistant settings + weight = 1 << ((style & 3) + 4); + familiarity = (style >> 4) & 3; + if (g.level >= 6) detail = (style >> 2) & 3; + } + } else { + formation = g.formation(team); + } + // formation table (block Formations): x at +0..10, y at +11..21; the original walks on past 11 + const size_t table = size_t(formation) * 0x16 + (g.indoor ? 0xb0 : 0) + size_t(set) * 0x160; + auto board = [&](int slot) -> uint8_t* { return &g.tactics.at(size_t(manager) * 0x840 + size_t(slot) * 0x58); }; + + g.team_flags.at(team) &= 0xFFFE; + SquadRange range = squad_range(team); + if (manager >= 0) + for (size_t s = 0; s < range.count; s++) board(int(s))[0x3f] = 0xFF; + int count = int(range.count); + bool first_eleven_only = mode == 0x65 || mode < 100; + if (first_eleven_only) count = 11; + + int16_t value[24]; + int16_t best_score[24]; + for (int i = 0; i < 24; i++) value[i] = best_score[i] = kUnavailable; + + int found = 0; + for (; found < count; found++) { + uint16_t& slot = g.squad_slots.at(range.first + found); + int id = slot & 0x0FFF; + if (id == 0x0FFF) break; + const Player& p = g.players.at(id); + if ((p.w364 >> 16 & 0x1F) == 0) { + value[found] = int16_t(p.form() / 3 + p.condition() + p.technique()); + if (manager >= 0 && familiarity != 0) { + // players not used to their place on the board are worth less + int16_t f = int16_t(board(found)[0xf] - 0x19); + if (f > 0x2d) f = int16_t(f * 2 - 0x19); + value[found] = int16_t(value[found] - (f * familiarity) / 2); + } + } + slot &= 0x3FFF; // clear line-up and bench flags + } + int players = first_eleven_only ? 11 : found; + + for (int pos = 0; pos < players; pos++) { + int type; + if (pos < 11) type = kTypeByDepth[formation_byte(g, table + size_t(pos))]; + else type = kTypeBySlot[pos]; + int best = -1; + for (int j = pos; j < players; j++) { + uint16_t entry = g.squad_slots.at(range.first + j); + int id = entry & 0x0FFF; + if (value[j] == kUnavailable || (entry & 0xC000) != 0 || id == 0x0FFF) continue; + int player_type = g.players.at(id).position(); + int mismatch; + if (type == 9) mismatch = 0; + else if ((player_type == 0) != (type == 0)) mismatch = int16_t(weight) * 25; + else mismatch = int16_t(weight) * (player_type > type ? player_type - type : type - player_type); + const Player& candidate = g.players.at(size_t(id)); + int16_t position_value = value[j]; + // Int2 reads the coordinate pointers only inside local_20's + // level-6, non-goalkeeper branch. Normal and keeper/bench paths must + // not require bytes beyond the eleven formation coordinates. + if (detail != 0 && candidate.position() != 0) { + const int x = formation_byte(g, table + size_t(pos)); + const int y = formation_byte(g, table + 0xb + size_t(pos)); + position_value = detailed_position_value(value[j], candidate, x, y, detail); + } + int score = int16_t(position_value - mismatch); + if (best_score[pos] < score) { + best = j; + best_score[pos] = int16_t(score); + } + } + if (best == -1) continue; + if (type != 9) { + if (manager >= 0) { + // the chosen player gets the place on the board + board(best)[0x41] = formation_byte(g, table + size_t(pos)); + board(best)[0x42] = formation_byte(g, table + 0xb + size_t(pos)); + } + if (value[best] != kUnavailable) g.squad_slots.at(range.first + best) |= uint16_t(pos < 11 ? 0x8000 : 0x4000); + } + if (best != pos) { + // SquadSlotsBoardEntriesChangePlaces: squad slots and the board entries change places + std::swap(g.squad_slots.at(range.first + pos), g.squad_slots.at(range.first + best)); + if (manager >= 0) std::swap_ranges(board(pos), board(pos) + 0x58, board(best)); + std::swap(value[pos], value[best]); + } + } + // Int2, local_34: bit 7 requests a second pass for field rows + // 1..10. Compare reserves against each first-pass score using the base + // value and role penalty, without the detailed coordinate penalty. + // The keeper is excluded; first-eleven-only modes have no reserve range. + if (improve_from_reserves) { + for (int pos = 1; pos < 11; ++pos) { + const int type = kTypeByDepth[formation_byte(g, table + size_t(pos))]; + int16_t best = best_score[pos]; + int replacement = -1; + for (int row = 11; row < players; ++row) { + const int id = g.squad_slots.at(range.first + row) & 0x0fff; + if (value[row] == kUnavailable || id == 0x0fff) continue; + const int role = g.players.at(id).position(); + if (role == 0) continue; + const int16_t score = int16_t(value[row] - std::abs(role - type) * weight); + if (best < score) { + replacement = row; + best = score; + } + } + if (replacement < 0) continue; + uint16_t& reserve = g.squad_slots.at(range.first + replacement); + uint16_t& field = g.squad_slots.at(range.first + pos); + reserve = uint16_t((reserve & 0x1fff) | 0x8000); + field = uint16_t((field & 0x1fff) | (replacement < 17 ? 0x4000 : 0)); + std::swap(field, reserve); + if (manager >= 0) { + std::swap_ranges(board(pos), board(pos) + 0x58, board(replacement)); + board(pos)[0x41] = formation_byte(g, table + size_t(pos)); + board(pos)[0x42] = formation_byte(g, table + 0xb + size_t(pos)); + } + std::swap(value[pos], value[replacement]); + } + } + // Indoors a human manager's first eleven play in pairs that change together: every board + // place without a partner (+0x3f = 0xFF) takes the next free one at most one field away + // (both +0x41 and +0x42), both note each other's index. + if (g.indoor && manager >= 0) + for (int i = 0; i < 10; i++) { + if (board(i)[0x3f] != 0xFF) continue; + for (int j = i + 1; j <= 10; j++) { + if (board(j)[0x3f] != 0xFF) continue; + if (std::abs(int(int8_t(board(i)[0x42])) - int8_t(board(j)[0x42])) > 1 || + std::abs(int(int8_t(board(i)[0x41])) - int8_t(board(j)[0x41])) > 1) + continue; + board(i)[0x3f] = uint8_t(j); + board(j)[0x3f] = uint8_t(i); + break; + } + } + // OpenBMH deviates from the original: disables the foreign-player limit in the supported rule profile. +// (foreign-player limit ForeignPlayerLimitEnabled is off in the supported rule profile) + // After a full line-up every player in the eleven or on the bench notes his squad slot + // (relative to the squad start) in bits 0-4 of his card word (*PlayerCards). + if (!first_eleven_only && !g.player_cards.empty()) + for (int s = 0; s < found; s++) { + const uint16_t entry = g.squad_slots.at(range.first + s); + if (entry & 0xC000) { + uint16_t& cards = g.player_cards.at(entry & 0x0FFF); + cards = uint16_t((cards & 0xFFE0) | s); + } + } +} + +void auto_lineup(GameState& g, int team, int mode) { + auto_lineup_impl(g,team,mode,g.manager_of(team)); +} + +void auto_lineup_parked_club_source(GameState& g, int team, int mode) { + constexpr size_t record = 4*0xb0c+0x290; + if (team<0 || team>=138 || g.manager_teams.size()!=1 || g.manager_teams[0]!=kNoTeam || + !g.memory.has(::bmh::layout::CoachActive) || g.memory.u8(::bmh::layout::CoachActive)==0 || + !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 || + !g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + record+2>g.manager_records.size() || + (int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=kNoTeam || + (int(g.manager_records[record]) | int(g.manager_records[record+1])<<8)!=team || + g.tactics.size()<5*0x840) + throw std::invalid_argument("auto_lineup: invalid FindManagerForClub parked club context"); + auto_lineup_impl(g,team,mode,4); +} + +void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending) { + while (count > 1) { + uint32_t pivot = keys[count >> 1]; + int i = -1, j = count; + for (;;) { + if (!ascending) { + do i++; while (pivot < keys[i]); + do j--; while (keys[j] < pivot); + } else { + do i++; while (keys[i] < pivot); + do j--; while (pivot < keys[j]); + } + if (j <= i) break; + std::swap(keys[i], keys[j]); + std::swap(items[i], items[j]); + } + quicksort_by_key(items, keys, i, ascending); + items += i; + keys += i; + count -= i; + } +} + +bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand) { + if (!(team < 138 || team == kNoTeam)) return false; + const int manager = g.manager_of(team); + int used = g.team_flags.at(team) >> 5 & 7; // substitutions so far + if (mode == 10) { + // a random change of a human team only when the assistant may substitute (option 1) + if (manager >= 0 && !g.manager_option(manager, 1)) return false; + if (used >= kMaxSubstitutions - 1) return false; + } + + SquadRange range = squad_range(team); + int first = int(range.first); + int last_bench = team > 0x59 ? 16 : 17; + + // --- candidates on the bench ------------------------------------------------------------ + int16_t slot[24]; + uint32_t score[24]; + int n = 0; + for (int s = 11; s < last_bench; s++) { + uint16_t entry = g.squad_slots.at(first + s); + int id = entry & 0x0FFF; + if (id == 0x0FFF) break; + const Player& p = g.players.at(id); + if (!(entry & 0x4000) || (p.w364 >> 16 & 0x1F) != 0 || (p.w364 >> 12 & 1) != 0) continue; + int type = p.position(); + if (type == 0 && mode != 20) continue; + int base; + if (mode < 20) { + if (mode < 10) { + if (mode > 7) mode = 7; // the original clamps its parameter here for good + int trait = int(p.w35c >> 21 & 7); + base = 0x70 - (trait > mode ? trait - mode : mode - trait) * 16; + } else { + base = rand.range(0, 99); + } + } else { + if (off == first + s) continue; + if (mode != 20) { + int t = mode - 20; + base = 0x300 - (t > type ? t - type : type - t) * 256; + } else { + base = (type == 0) << 12; + } + } + int strength = p.strength(false); // Strength(w35c, 0) + score[n] = uint32_t(type + int16_t(base + strength) * 4); + slot[n] = int16_t(s); + n++; + } + if (n == 0) return false; + quicksort_by_key(slot, score, n); + int on = slot[0] + first; + int on_type = int(score[0] & 3); + + // --- the player to take off (tactical and random changes) ------------------------------ + if (mode < 20) { + n = 0; + for (int s = 0; s < 11; s++) { + uint16_t entry = g.squad_slots.at(first + s); + if (!(entry & kSlotInLineup)) continue; + const Player& p = g.players.at(entry & 0x0FFF); + int type = p.position(); + // The original compares the relative slot with the absolute index of the + // substitute here, which only matters for team 0. + if (s == on) continue; + if (!(type != 0 || (on_type == 0 && rand.range(0, 3) == 0))) continue; + if (!(type == 0 || on_type != 0)) continue; + int v; + if (mode < 10) { + int trait = int(p.w35c >> 21 & 7); + v = (trait > mode ? trait - mode : mode - trait) << 5; + } else { + v = (type > on_type ? type - on_type : on_type - type) << 6; + } + uint32_t junk = uint32_t(p.form() / 3 - p.technique()) - uint32_t(p.condition()); + score[n] = uint32_t(int32_t(int16_t(v + (0x14A - int16_t(junk))))); + slot[n] = int16_t(s); + n++; + } + if (n == 0) return false; + quicksort_by_key(slot, score, n); + off = slot[0] + first; + } + if (used == kMaxSubstitutions) return false; + + // --- the change itself ----------------------------------------------------------------- + used++; + std::swap(g.squad_slots.at(on), g.squad_slots.at(off)); // SquadSlotsBoardEntriesChangePlaces + if (manager >= 0) { + // the two tactics board slots are swapped too + auto board = g.tactics.begin() + long(size_t(manager) * 0x840); + std::swap_ranges(board + long(size_t(on - first) * 0x58), board + long(size_t(on - first + 1) * 0x58), + board + long(size_t(off - first) * 0x58)); + } + g.squad_slots.at(on) &= 0x1FFF; + g.squad_slots.at(off) &= 0x1FFF; + g.players.at(g.squad_slots.at(off) & 0x0FFF).w364 |= 0x1000; // the substitute has played + g.squad_slots.at(off) |= 0x8000; + g.squad_slots.at(on) |= 0x4000; + if (manager >= 0) { + // human teams: the re-sort uses a formation after the attitude (mode / 2 for the + // tactical changes, else the manager's setting, record +0xd2): option byte 0 is set + // to 4 - attitude for the call and restored afterwards + int attitude = mode < 9 ? mode >> 1 : int8_t(g.manager_records.at(size_t(manager) * 0xB0C + 0xd2)); // (mode as clamped above) + if (attitude > 3) attitude = 3; + uint8_t& option = g.manager_options.at(size_t(manager) * 5); + const uint8_t saved = option; + option = uint8_t(4 - attitude); + auto_lineup(g, team, 0x65); + option = saved; + } else { + auto_lineup(g, team, 0x65); + } + g.team_flags.at(team) = uint16_t((g.team_flags.at(team) & 0xFF1F) | used << 5); + return true; +} + +bool manual_substitution(GameState& g, int team, int field_slot, int bench_slot) { + const SquadRange range = squad_range(team); + if (field_slot < 0 || field_slot >= 11 || bench_slot < 11 || size_t(bench_slot) >= range.count) return false; + const size_t off = range.first + size_t(field_slot), on = range.first + size_t(bench_slot); + const uint16_t out = g.squad_slots.at(off), in = g.squad_slots.at(on); + if ((out & 0x0FFF) == 0x0FFF || !(out & kSlotInLineup)) return false; + // the substitute: on the bench (slot flag 0x4000) and not yet played in this match + // (w364 bit 12, set when he came on - a player taken off may not come back) + if ((in & 0x0FFF) == 0x0FFF || !(in & 0x4000) || (g.players.at(in & 0x0FFF).w364 & 0x1000)) return false; + int used = g.team_flags.at(team) >> 5 & 7; + if (used >= kMaxSubstitutions) return false; + used++; + std::swap(g.squad_slots.at(on), g.squad_slots.at(off)); // SquadSlotsBoardEntriesChangePlaces + const int manager = g.manager_of(team); + if (manager >= 0) { + // the board entries change places too, but the place on the pitch stays with the slot + auto board = g.tactics.begin() + long(size_t(manager) * 0x840); + auto a = board + long(size_t(field_slot) * 0x58), b = board + long(size_t(bench_slot) * 0x58); + const uint8_t x = a[0x41], y = a[0x42]; + std::swap_ranges(a, a + 0x58, b); + a[0x41] = x, a[0x42] = y; + } + g.squad_slots.at(on) &= 0x1FFF; + g.squad_slots.at(off) &= 0x1FFF; + g.players.at(g.squad_slots.at(off) & 0x0FFF).w364 |= 0x1000; // the substitute has played + g.squad_slots.at(off) |= kSlotInLineup; + g.squad_slots.at(on) |= 0x4000; + g.team_flags.at(team) = uint16_t((g.team_flags.at(team) & 0xFF1F) | used << 5); + return true; +} + +} // namespace bmh + +namespace bmh { + +bool initialize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club) { + if (!pitch_context_valid(g, manager_slot, runtime_club)) return false; + const size_t rec = size_t(manager_slot) * kManagerRecordSize; + if (uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253) { + g.manager_records[rec + 0xafc] = g.manager_records[rec + 0xafd] = 0; + g.manager_records[rec + 0xafe] = g.manager_records[rec + 0xaff] = 0; + g.manager_records[rec + 0xb08] = g.manager_records[rec + 0xb09] = 0; + g.manager_records[rec + 0xb0a] = 0x53; g.manager_records[rec + 0xb0b] = 0x32; + } + return true; +} + +bool normalize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club) { + if (!initialize_pitch_set_piece_source(g, manager_slot, runtime_club)) return false; + const size_t rec = size_t(manager_slot) * kManagerRecordSize; + const auto member = [&](uint16_t stored) { + if (!stored || stored > 0x0fff) return false; + const int id = int(stored) - 1; + const auto range = squad_range(runtime_club); + for (size_t i = 0; i < range.count; ++i) + if ((g.squad_slots[range.first + i] & 0x0fff) == id) return true; + return false; + }; + for (size_t off : {size_t(0xafc), size_t(0xafe), size_t(0xb08)}) { + uint16_t value = uint16_t(g.manager_records[rec + off] | uint16_t(g.manager_records[rec + off + 1]) << 8); + if (!member(value)) g.manager_records[rec + off] = g.manager_records[rec + off + 1] = 0; + } + return true; +} + +bool set_pitch_set_piece_taker_source(GameState& g, int manager_slot, int runtime_club, + int selector, int row, int player_id, uint16_t slot, + uint16_t expected_old_value) { + if (!pitch_context_valid(g, manager_slot, runtime_club) || selector < 2 || selector > 4 || + row < 0) return false; + const auto range = squad_range(runtime_club); + const size_t at = range.first + size_t(row), rec = size_t(manager_slot) * kManagerRecordSize; + if (size_t(row) >= range.count || at >= range.first + range.count || g.squad_slots[at] != slot || (slot & 0xc000) == 0 || + (slot & 0x0fff) != player_id || player_id < 0 || size_t(player_id) >= g.players.size() || + ((g.players[size_t(player_id)].w364 >> 16) & 0x1f) != 0 || + uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253) + return false; + static constexpr size_t offsets[] = {0, 0, 0xafc, 0xafe, 0xb08}; + const size_t field = rec + offsets[selector]; + const uint16_t current = uint16_t(g.manager_records[field] | uint16_t(g.manager_records[field + 1]) << 8); + if (current != expected_old_value) return false; + const uint16_t encoded = uint16_t(player_id + 1); + g.manager_records[field] = uint8_t(encoded); g.manager_records[field + 1] = uint8_t(encoded >> 8); + return true; +} + +bool auto_pitch_set_piece_takers_source(GameState& g, int manager_slot, int runtime_club, + const std::array& expected_old_values) { + if (!pitch_context_valid(g, manager_slot, runtime_club)) return false; + const size_t rec = size_t(manager_slot) * kManagerRecordSize; + if (uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253) + return false; + static constexpr size_t offsets[] = {0xafc, 0xafe, 0xb08}; + for (size_t i = 0; i < 3; ++i) { + const auto off = offsets[i]; + if (uint16_t(g.manager_records[rec + off] | uint16_t(g.manager_records[rec + off + 1]) << 8) != expected_old_values[i]) + return false; + } + for (const auto off : offsets) g.manager_records[rec + off] = g.manager_records[rec + off + 1] = 0; + return true; +} + +bool set_player_order_source(GameState& g, int manager_slot, int runtime_club, int row, int player, int aspect, int value) { + if (manager_slot < 0 || size_t(manager_slot) >= g.manager_teams.size() || g.manager_teams[size_t(manager_slot)] != runtime_club || + aspect < 0 || aspect > 3 || row < 0 || row >= 24) + return false; + const SquadRange range = squad_range(runtime_club); + if (size_t(row) >= range.count || range.first + size_t(row) >= g.squad_slots.size()) return false; + const uint16_t slot = g.squad_slots[range.first + size_t(row)]; + // only a starter on the pitch can be selected in the ORDER view + if ((slot & 0x0fff) != uint16_t(player) || !(slot & 0x8000)) return false; + const size_t at = size_t(manager_slot) * 0x840 + size_t(row) * 0x58 + 2 + size_t(aspect); + if (at >= g.tactics.size()) return false; + g.tactics[at] = uint8_t(std::clamp(value, kOrderMin, kOrderMax)); // ClampInteger(&v, 2, 0x28) + return true; +} + +} // namespace bmh diff --git a/src/game/lineup.hpp b/src/game/lineup.hpp new file mode 100644 index 0000000..ad72219 --- /dev/null +++ b/src/game/lineup.hpp @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection. +// Automatic line-up of computer teams, port of Int2. +// +// The squad of a team is a run of squad slots (squad_range). The first 11 slots are the +// starting line-up in formation order (slot i plays at formation position i, see +// GameState::formation_position), the following slots are the bench and reserves. +// Slot flags: 0x8000 in the starting line-up, 0x4000 on the bench. +// +// The optimiser draws no random numbers. For every fit player (no injury, w364 bits +// 16-20 zero) it computes a base value +// value = condition + technique + form / 3 +// and then fills the positions one after another: position p takes the remaining player +// with the best value - mismatch, where mismatch is +// 0 for bench slots of type 9 (reserves) +// 64 * 25 if exactly one of player and position is a goalkeeper +// 64 * |player position - position type| otherwise +// Position types come from the formation depth for the first 11 slots (table layout field: +// 0 goalkeeper, 1 defence, 2 midfield, 3 attack) and from table layout field for the bench. +// The chosen player is swapped into slot p and flagged 0x8000 (slots 0-10) or 0x4000. +// +// Ported: assistant training-camp familiarity penalty and detailed position scoring at +// difficulty >= 6. The foreign-player limit (ForeignPlayerLimitEnabled) is off in supported rule profile. + +#include +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// Games: in-place quicksort (Hoare partition, middle element as pivot) of `keys` +// descending (ascending if `ascending`), comparing as unsigned 32-bit, moving `items` +// along. Ported exactly because the order of equal keys depends on the algorithm. +void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending = false); + +// Maximum number of substitutions per match (CareerSession_DispatchLiveSubstitution_ExecutableField). +constexpr int kMaxSubstitutions = 3; + +// Injure: substitution for a computer team. +// off absolute squad slot of the player to take off, used only for mode >= 20 +// mode < 10 tactical change towards trait value `mode` (w35c bits 21-23) +// 10 random change (called during the match), keeps the last substitution +// for emergencies +// 20+t replace the player in `off` (injured or booked) by a bench player of +// position type t (t = 0 prefers a goalkeeper) +// Picks the best fit bench player (not injured, not yet played), for modes < 20 also the +// player to take off, swaps them, re-sorts the eleven (auto_lineup mode 0x65) and counts +// the substitution in the team flags (bits 5-7). Returns false if nothing was changed. +// Draws from `rand` like the original. +bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand); + +// A substitution the manager makes himself during his live match (the line-up screen +// PitchScreen opened from the match, "AUFSTELLUNG AUTO"): the player in line-up slot +// `field_slot` (0-10, relative to the squad) leaves, the bench player in `bench_slot` (11..) +// takes his place on the pitch and on the tactics board (the place, board bytes +// 0x41/0x42, stays with the slot). The flags and the counter are those of `substitute`: +// the incoming player has played (w364 bit 12), the slots get 0x8000 / 0x4000, the team flags +// count the change. Returns false (nothing changed) for an empty or not lined-up field slot, +// a bench player who already played or after kMaxSubstitutions. Rate the side again +// afterwards (MatchEngine::rerate_team). No random numbers. +bool manual_substitution(GameState& g, int team, int field_slot, int bench_slot); + +// mode as in the original: < 100 only re-sorts the current first 11 slots (used right +// before a match, AutoLineup), 100 picks from the whole squad, 101 (0x65) re-sorts the +// first 11 after a substitution. Bit 0x80 additionally improves field rows 1-10 +// from the reserves after the first positional selection, as in the original. +void auto_lineup(GameState& g, int team, int mode); + +// Explicit FindManagerForClub record4 lookup for the club parked during a national +// takeover. Validate the raw record/board; never extend the active manager list. +void auto_lineup_parked_club_source(GameState& g, int team, int mode); + +// PrepareLineupEntry: re-flag the already chosen field and bench rows on lineup-screen entry. +// This does not rank, replace or otherwise choose players and consumes no RNG. +void prepare_lineup_entry(GameState& g, int team); + +// Deterministic Source pitch actions for a live, mode-bound human-manager +// desk (outdoor or indoor). Each helper stages the complete GameState and returns +// true only after a complete Source action can be committed; false is a +// neutral rejection with Native state untouched. None consumes W/G RNG. +// The caller still owns active-screen, revision, prepared-entry and ACK checks. +bool set_pitch_automatic_weight_source(GameState& g, int manager_slot, int runtime_club, + int weight_index, uint8_t old_weights, uint8_t new_weights); +bool move_pitch_player_source(GameState& g, int manager_slot, int runtime_club, + int row, int player_id, uint16_t slot, + int old_depth, int old_lane, int new_depth, int new_lane); +bool apply_pitch_formation_source(GameState& g, int manager_slot, int runtime_club, + int formation, uint8_t expected_weights); +bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_club, + int formation, uint8_t expected_weights, + const std::array& formation_positions); + +// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection. +// supported rule profile NormalizePitchSetPieceSource/NormalizePitchSetPieceSource3/NormalizePitchSetPieceSource2/NormalizePitchSetPieceSource4: deterministic, owner-bound +// set-piece presentation state. Stored takers are player_id+1; zero is AUTO. +bool normalize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club); +bool initialize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club); +bool set_pitch_set_piece_taker_source(GameState& g, int manager_slot, int runtime_club, + int selector, int row, int player_id, uint16_t slot, + uint16_t expected_old_value); +bool auto_pitch_set_piece_takers_source(GameState& g, int manager_slot, int runtime_club, + const std::array& expected_old_values); + +// ORDER (PitchScreen with desk flag 0x20, H2 p. 43): the four instructions of a starter on +// the tactics board, bytes +2..+5 - 0 defensive/offensive, 1 running, 2 commitment, 3 fighting +// (the live scene reads +5, rating.cpp). A click in a bar sets the value from the mouse +// position or moves it by one; ClampInteger keeps it within 2..40. `row` is the board/squad +// row of the manager's club, `player` its expected player. Returns false (nothing changed) +// for a stale or invalid request. +constexpr int kOrderMin = 2, kOrderMax = 40; +bool set_player_order_source(GameState& g, int manager_slot, int runtime_club, int row, int player, int aspect, int value); + +} // namespace bmh diff --git a/src/game/match.cpp b/src/game/match.cpp new file mode 100644 index 0000000..565449f --- /dev/null +++ b/src/game/match.cpp @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/match.hpp" + +#include +#include + +#include "game/rating.hpp" +#include "game/schedule.hpp" + +namespace bmh { + +namespace { + +// Average monthly temperature in °C, indexed directly by CareerSession_PairingsRuntimeDraw_ExecutableField5 (1-12; table at +// MatchRuntimeField4, 13 entries; the month code indexes it directly, not modulo 12). +constexpr int8_t kMonthTemperature[13] = {2, 0, 8, 12, 15, 21, 26, 26, 18, 11, 6, 2, 0}; +// Temperature offset of a team's home region (table at MatchRuntimeField3, index = team_region()): +// 0 top leagues, 1-4 regional leagues, from 10 on the foreign countries (7 clubs each). +// The last entries lie beyond the table in the original and are kept as found there. +constexpr int8_t kRegionTemperature[48] = {0, -1, 5, 0, 0, 5, 0, -1, -5, -4, -2, 0, 0, -3, -1, -1, + -1, 6, 6, 4, -3, 4, -6, 7, 0, 0, 0, 0, 0, 2, 0, -3, + 8, 8, 8, 8, 10, 9, 3, 11, -29, 15, 10, 0, -27, 15, 10, 0}; +// Crowd factor per league in thousands (table at layout field): the home side gets its bonus if +// the attendance exceeds a random value in [factor * 1000 + 3000, factor * 1000 + 6000]. +constexpr uint8_t kLeagueCrowd[10] = {27, 12, 7, 7, 3, 27, 27, 27, 27, 27}; +// First league that counts as a regional league (LeaguePairings_LeaguePairingsConstants_RuntimeField). +constexpr int kFirstRegionalLeague = 5; +// Number of cup-only teams before the amateur blocks (CareerSession_InstallLeagueSizes_RuntimeField6). +constexpr int kCupTeams = 30; + +int clamp(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; } + +// BuildSideRecords2 evaluated at kick-off (score 0:0, minute 0) for a computer team: +// start from 2 (home) or 1 (away), one step more defensive if the opponent's attack/ +// midfield value (byte 2) is more than 10 higher, one step more offensive if it is more +// than 10 lower - but only for match_index != 0 (the original compares the match index +// where the minute was probably meant). A 1/201 roll picks a special event code that is +// not stored. +int initial_attitude(const SideRecord& own, const SideRecord& other, int side, int match_index, WatcomRandom& rand) { + int substitution = -1; // cannot happen at minute 0 + return attitude_update(own.b.data(), other.b.data(), side, match_index, 0, 0, 0, rand, substitution); +} + +} // namespace + +int attitude_update(const uint8_t* own, const uint8_t* other, int side, int match_index, int own_goals, int opp_goals, + int minute, WatcomRandom& rand, int& substitution_mode) { + int own2 = int8_t(own[2]), other2 = int8_t(other[2]); + int base = 2 - side; + if (own2 + 10 < other2) base = 1 - side; + int low = base; // attitude (low byte of uVar5 in the original) + int high = 0; // "special" code (high byte), only used for the substitution request + if (other2 < own2 - 10 && match_index != 0) low = base + 1; + if (own_goals < opp_goals && opp_goals - 2 <= own_goals) { // behind by one or two + low = low + 1 + (minute > 80 ? 1 : 0); + high = minute > 80 ? 8 : 6; + } + if (opp_goals < own_goals && own_goals - 1 <= opp_goals) { // ahead by one + if (minute > 75) low--; + if (own2 < other2 || (match_index != 0 && minute > 80)) low--; + high = minute > 80 ? 1 : 3; + } + low = int8_t(low); + if (low < 0) low = 0; + if (low > 3) low = 3; + if (high == 0 && rand.range(0, 200) == 0) high = 0x0B; + substitution_mode = -1; + if (minute > 60 && high != 0 && rand.range(0, 60) == 0) substitution_mode = high - 1; // Injure(team, 0, high - 1) + return low; +} + +int region_temperature(int region) { return region >= 0 && region < 48 ? kRegionTemperature[region] : 0; } +int month_temperature(int month) { return kMonthTemperature[month >= 0 && month <= 12 ? month : 0]; } + +int team_region(int team) { + if (team == kNoTeam) return 0; + int t = team; + for (int league = 0; league < kLeagueCount; league++) { + t -= kLeagueSizes[league]; + if (t < 0) return league >= kFirstRegionalLeague ? league - kFirstRegionalLeague + 1 : 0; + } + if (t - kCupTeams >= 0) return (t - kCupTeams) / 7 - kFirstRegionalLeague + 10; + return 0; +} + +void rate_side(GameState& g, const MatchSetup& m, int side, int previous6, WatcomRandom& rand, uint8_t* r, GameRandom* game) { + int team = side ? m.away : m.home, opponent = side ? m.home : m.away; + const int manager = g.manager_of(team); // local_14 + // (the original also has a special case for the pseudo team 0x165 of a human manager, + // which does not play league or cup matches) + + // --- modifier for byte 2 --------------------------------------------------------------- + int modifier = 0; + if (side != 0 && m.climate_effect) { + int region = team_region(team); + if (region != team_region(opponent)) { + int expected = rand.range(0, 6) + month_temperature(m.month) + region_temperature(region) - 3; + // Abs2 on the temperature byte read unsigned (frost counts as 200+) + int deviation = std::abs(int(uint8_t(m.temperature)) - expected); + // The original subtracts byte 6 of the record MatchRuntimeField points to at that + // moment, both operands as signed chars (a balance above 127 counts negative). + modifier = int8_t(int8_t(deviation / 2) - int8_t(previous6)); + } + } + if (side == 0) { + int league = team > 0x164 ? 0 : team_league(team); // TeamLeague2 + int base = kLeagueCrowd[league < 10 ? league : 9] * 1000; + if (unsigned(rand.range(base + 3000, base + 6000)) < unsigned(m.spectators)) { + // a human manager's side with record +0x289 set suffers more from a full house + modifier -= manager >= 0 && g.manager_records.at(size_t(manager) * 0xB0C + 0x289) != 0 ? 9 : 6; + } + } + modifier = clamp(int8_t(modifier), -10, 10); + + // --- Uint8T3: ratings, fit-player scaling, balance ------------------------------ + // one context for all six profiles: profiles 4 and 5 see the stale technique of profile 3 + RatingContext weather{g.chance_rain, g.chance_temperature}; + weather.rand = &rand; // clubs without squad draw their ratings + weather.game = game; // human teams: motivation draws + weather.live_scene = g.live_scene; + for (int i = 0; i < 6; i++) r[i] = uint8_t(team_rating(g, team, kRatingProfiles[i], weather)); + using namespace avg; + TeamAverage condition = team_average(g, team, LINEUP_ONLY | ALL_POSITIONS | CONDITION, &rand); + TeamAverage technique = team_average(g, team, LINEUP_ONLY | ALL_POSITIONS | TECHNIQUE, &rand); + int players = technique.players; // count of the last call, like local_10 + if (players < 11 && players > 2) + for (int i = 1; i < 4; i++) r[i] = uint8_t((players - 3) * r[i] / 10); + r[6] = uint8_t(clamp((condition.value - technique.value) * 4 + 100, 0, 200)); + + r[2] = uint8_t(clamp(r[2] - modifier, 0, 99)); + // (the original lets two cheat codes, CareerSession_FormatError_RuntimeField9, set a human side's six ratings to + // fixed values; not ported) + if (manager < 0) { + int rhythm = r[6] >> 1; // computer teams: half the balance, at least 50 + r[7] = uint8_t(rhythm < 50 ? 50 : rhythm); + } else { + // human teams: record +0xd9 (signed) * 5 plus the balance, scaled to 0-100 + const int8_t d9 = int8_t(g.manager_records.at(size_t(manager) * 0xB0C + 0xd9)); + r[7] = uint8_t((d9 * 5 + r[6]) * 100 / 0xFF); + } +} + +std::array build_side_records(GameState& g, const MatchSetup& m, WatcomRandom& rand, GameRandom* game) { + std::array rec{}; + int previous6 = 0; // byte 6 of the record built last (MatchRuntimeField still points to it) + + for (int side = 0; side < 2; side++) { + SideRecord& r = rec[side]; + rate_side(g, m, side, previous6, rand, r.b.data(), game); + previous6 = r.b[6]; + + // --- BuildSideRecords2 at 0:0 ---------------------------------------------------------- + // Bug in the original: for the home side the away record is not built yet. The 18 + // bytes come from malloc without clearing (ManagerOf2 flag 0), so the home side + // compares against leftover heap contents. That cannot be derived from the game + // state; OpenBMH uses a cleared record (0) as a deterministic stand-in. + const int manager = g.manager_of(side ? m.away : m.home); + if (manager >= 0 && !g.manager_option(manager, 2)) + r.b[8] = g.manager_records.at(size_t(manager) * 0xB0C + 0xd2); // the manager's own setting + else + r.b[8] = uint8_t(initial_attitude(r, rec[1 - side], side, m.match_index, rand)); + } + return rec; +} + +} // namespace bmh diff --git a/src/game/match.hpp b/src/game/match.hpp new file mode 100644 index 0000000..26ea1b6 --- /dev/null +++ b/src/game/match.hpp @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Match simulation - structure of the original, port in progress. +// +// This header records what is known about the original's match engine so the port can +// follow it step by step. Everything below refers to BMH.exe V2.24 function addresses. +// +// --------------------------------------------------------------------------------------- +// Matchday flow (FinishEvent) +// --------------------------------------------------------------------------------------- +// 1. For every competition playing today a "match group" descriptor (0xD0 bytes, up to 6 +// in table MatchdayGroupDescriptors) is set up by FixturesFromGenerateFixtures: the fixtures from generate_fixtures(), +// the number of matches, and a pointer to the result bytes in block LeagueResults. +// 2. Per match an 18-byte record is allocated (two 9-byte "side" records, home first) +// and filled by BuildSideRecords3 (see "Side record"). +// 3. Teams with fewer than 8 fit players lose 0:2 and are fined 200 000. +// 4. The match loop EndPhase(first_minute, last_minute, max_stoppage, phase) runs +// for 1..45, 46..90 (+ up to 4 minutes stoppage), and for cup ties 91..105 and +// 106..120. Indoor tournaments (CareerSessionRuntimeField set) play 1..20 and 21..40. +// +// --------------------------------------------------------------------------------------- +// Side record (9 bytes per team and match, BuildSideRecords3 / Uint8T3) +// --------------------------------------------------------------------------------------- +// [0..5] six ratings from TeamRating(team, weight table at layout field + i * 10): the +// line-up is walked, every player adds a position-dependent value to one of +// 4 x 3 buckets (goalkeeper / defence / midfield / attack x left/centre/right), +// the buckets are weighted and averaged; result capped at 110. +// [1..3] are scaled by (players - 3) / 10 if fewer than 11 players are fit. +// [2] additionally reduced by a home/away and fatigue modifier clamped to -10..+10. +// [6] (avg condition - avg technique) * 4 + 100, clamped 0..200 +// (team_average with flags 0x1F1 and 0x1F2). +// [7] human teams: (manager bonus * 5 + [6]) * 100 / 255, else [6] / 2 (min 50); +// clamped to 44..80 where it is used as the chance rhythm (MatchRuntimeField2). +// [8] read as "local_a4" together with byte 0x11 of the other side. +// +// --------------------------------------------------------------------------------------- +// Per minute, per match, per side (EndPhase, around 0x382xx) +// --------------------------------------------------------------------------------------- +// - After the regular time every running match ends with probability 1/2 per minute +// (Watcom rand, WatcomRandom::range(0, 1)). +// - Random events (injuries, cards) are triggered with WatcomRandom::range(0, 220) < +// rhythm - 30 and EventImpl. +// - Chance roll: GameRandom::range(0, pressure * 4 + 44) compared against +// side[8] + other[0x11] + 3 + 14 * indoor; above means no chance this minute. +// - Otherwise the chance quality is built from side[2], GameRandom::range(0, rhythm) / 10, +// minute dependent bonus GameRandom::range(6, 12) while minute < side[6] (50..130), +// the opponent's [0xB] and [0xF] bytes and GameRandom::range(0, 100); the difference +// indexes the table at layout field (index 5..24) which gives the goal threshold, tested +// against GameRandom::range(0, pressure * 4 + 56). +// +// --------------------------------------------------------------------------------------- +// Randomness and reproducibility +// --------------------------------------------------------------------------------------- +// Goals are decided by GameRandom (GameRandom), but its seed comes from +// CurrentMatchday = WatcomRandom::range(0, 10000) (AdvanceTurn) or the saved CareerSession_Invalid_RuntimeField2, +// and WatcomRandom (seeded from the clock at program start) also decides stoppage time +// and random events. A matchday can therefore only be reproduced bit-exactly when both +// generator states at kick-off are known (e.g. read from memory in the DOSBox debugger). + +#include +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// The 9-byte record of one team in one match (see "Side record" above). +struct SideRecord { + std::array b{}; + uint8_t goalkeeping() const { return b[0]; } + uint8_t attitude() const { return b[8]; } // 0 defensive .. 3 all-out attack +}; + +// Per-match input of the side record setup that comes from the match group descriptor. +struct MatchSetup { + int home = 0, away = 0; // team ids + int match_index = 0; // position inside the match group (affects the attitude quirk) + bool climate_effect = false; // descriptor flag bit 1 (set for league matchdays) + int temperature = 0; // descriptor byte 0x30 + match: temperature at the venue in °C + int spectators = 0; // result of the spectator calculation (Attendance) + int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5, index into the monthly temperature table +}; + +// Builds both side records of a match like BuildSideRecords does at kick-off: for the home +// side and then the away side it runs BuildSideRecords3 (ratings, home/climate modifier, +// condition-technique balance, rhythm) followed by BuildSideRecords2 at 0:0 (initial attitude). +// Order matters: the home attitude is computed while the away record is still empty. +// +// Draws from `rand` exactly like the original (home bonus roll, climate roll for away +// teams from other regions, and the 1/201 attitude roll per side). Teams of human +// managers also draw from `game` (see team_rating) and may keep their own attitude. +std::array build_side_records(GameState& g, const MatchSetup& m, WatcomRandom& rand, + GameRandom* game = nullptr); + +// BuildSideRecords3 for one side: recomputes bytes 0-7 of a side record (byte 8, the attitude, +// is left alone). Used at kick-off and during the match after line-up changes. +// previous6 byte 6 of the record MatchRuntimeField points to when the original calls it +// (at kick-off the previously built record, during the match the side's own) +void rate_side(GameState& g, const MatchSetup& m, int side, int previous6, WatcomRandom& rand, uint8_t* record, + GameRandom* game = nullptr); + +// Attitude of a computer team (BuildSideRecords2), 0 defensive .. 3 all-out attack. +// own/other the two side records (byte 2 = attack/midfield strength is compared) +// side 0 home, 1 away (home starts one step more offensive) +// match_index position in the match group; the "much stronger" step is skipped for +// match 0 (the original tests the match index where the minute was meant) +// own_goals/opp_goals, minute: behind by 1-2 -> +1 (+2 after minute 80), +// ahead by 1 -> -1 after minute 75, another -1 if weaker or late +// Draws from `rand`: 1/201 "special" roll when no score rule applied, and after minute 60 +// a 1/61 roll that asks for a substitution: substitution_mode is then the mode for +// substitute() (special code - 1), otherwise -1. +int attitude_update(const uint8_t* own, const uint8_t* other, int side, int match_index, int own_goals, int opp_goals, + int minute, WatcomRandom& rand, int& substitution_mode); + +// OpenBMH deviates from the original: uses the enhanced injury selection and suspension rules. +// InjurePlayer(slot, type, match, manager) with its supported rule profile continuation: injures the +// player in the absolute squad slot. The type passed in is replaced by a drawn one +// (WatcomRandom(0, 999)); returns the type. A human manager's club doctor shortens the +// absence. Players with w364 bits 13-15 set are protected. +int injure_player(GameState& g, int slot, int type, bool match, int manager, WatcomRandom& rand); + +// Region of a team for the climate effect (TeamRegion): 0 for the top five leagues, +// 1..4 for the four regional leagues, higher values for amateur teams (7 per region). +int team_region(int team); + +// Temperature offset of a region (MatchRuntimeField3[region]) and the average temperature of a +// month (MatchRuntimeField4[CareerSession_PairingsRuntimeDraw_ExecutableField5]). +int region_temperature(int region); +int month_temperature(int month); + +} // namespace bmh diff --git a/src/game/match_engine.cpp b/src/game/match_engine.cpp new file mode 100644 index 0000000..806c557 --- /dev/null +++ b/src/game/match_engine.cpp @@ -0,0 +1,1286 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/match_engine.hpp" + +#include +#include +#include +#include +#include + +#include "game/lineup.hpp" +#include "game/match.hpp" +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/rating.hpp" +#include "game/reality_match.hpp" + +namespace bmh { + +namespace { + +// Goal threshold by chance quality index 5..24 (table at layout field). +constexpr uint8_t kChanceTable[25] = {11, 12, 13, 14, 16, 18, 20, 21, 22, 22, 23, 25, 26, + 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33}; +// player_value attributes by pick mode (table at layout field): 0 shooter, 1 assistant, +// 2 penalty taker, 3 free kick / corner taker. +constexpr uint16_t kPickAttributes[4] = {0x1297, 0x0127, 0x0080, 0x0802}; + +int clamp(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; } + +} // namespace + +MinuteReport MatchEngine::minute(int minute, int last_minute, int stoppage) { + MinuteReport report; + if (reality_rules && !state.reality.initialized) { + for (size_t i = 0; i < 5; ++i) state.reality.cue_actors[i] = reality_rules->u8(::bmh::layout::MatchEngine_Minute_ExecutableField2 + uint32_t(i)); + state.reality.card_kind = reality_rules->u8(::bmh::layout::MatchEngine_Minute_ExecutableField); + state.reality.deflected = reality_rules->u8(::bmh::layout::MatchEngine_Minute_ExecutableField3) != 0; + state.reality.distance = reality_rules->u8(::bmh::layout::MatchEngine_Minute_ExecutableField4); + state.reality.initialized = true; + } + for (MatchGroup& g : groups) { + for (int m = 0; m < g.matches(); m++) { + uint32_t bit = 1u << m; + if ((g.ended & bit) || (g.void_mask() & bit)) continue; + // End of match / half. The Watcom roll is only drawn after the regular time. + if ((last_minute < minute && rand.range(0, 1) != 0) || minute == stoppage + last_minute) { + g.end_minute.at(m) = uint8_t(minute); + g.ended |= bit; + continue; + } + // Attitudes are read once per match and minute and swapped between the sides + // (local_a4 = own, local_8c = opponent). + int own = g.records.at(m * 18 + 8), opp = g.records.at(m * 18 + 17); + for (int s = 0; s < 2 && !report.unsupported; s++) { + try { + side(g, m, s, minute, own, opp, report); + } catch (const std::exception& ex) { + report.fail("internal error in match " + std::to_string(m) + " side " + std::to_string(s) + " (teams " + + std::to_string(g.fixtures.at(m * 2)) + "-" + std::to_string(g.fixtures.at(m * 2 + 1)) + + "): " + ex.what()); + } + std::swap(own, opp); + } + if (report.unsupported) return report; + } + } + return report; +} + +// OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// PickTaker via DesignatedSlot / PickPlayer: picks a line-up player of `team`. Up to 199 +// tries: a random line-up slot, the player's value for the mode plus a position bonus, +// accepted if WatcomRandom(0, 180) < value; a goalkeeper (depth 0) is rejected 99 of 100 +// times. Sets last_pick_quality (MatchEngineRuntimeField) to the value of the last candidate - 81. +// `preset` (supported rule profile patch, PickPlayer2/80c20/80c40: mode bits 2-5 = slot + 1) fixes the +// slot and accepts without the Watcom roll; only the goalkeeper check remains. +// Human teams use the places on their tactics board, also for the player's value. +int MatchEngine::pick_player(int team, int mode, int exclude, MinuteReport& report, int preset) { + mode &= 0x7F; // 0x80 = reuse the squad of the previous call, same team here + if (team >= 138 && team != kNoTeam) return 0xFFF; // clubs without squad: nobody, no draws + SquadRange range = squad_range(team); + if (range.count == 0) return 0xFFF; + RatingContext ctx{state.chance_rain, state.chance_temperature}; + for (int tries = 0; tries < 199; tries++) { + int slot = preset >= 0 ? preset : rand.range(0, 10); + // MatchEngineRuntimeField2 / MatchEngineRuntimeField3: slot of the last candidate (shooter / assistant modes) + if (mode == 1 || mode == 3) last_assist_slot = slot; + else last_shooter_slot = slot; + uint16_t entry = state.squad_slots.at(range.first + slot); + if (!(entry & kSlotInLineup)) continue; + int player = entry & 0x0FFF; + if (player == exclude || player == 0xFFF) continue; + int x = 0, y = 0; + state.formation_position(team, slot, x, y); + ctx.stale_condition = pick_stack_condition; + int v = int16_t(player_value(state, player, kPickAttributes[mode], 100, team, ctx, int16_t(x), int16_t(y))); + if (kPickAttributes[mode] & 1) pick_stack_condition = state.players.at(player).condition(); + if (mode == 0) v = int16_t(v + x * x / 4 - (4 > y ? 4 - y : y - 4) * 15); + else if (mode == 1) v = int16_t(v + 81 - (10 > x ? 10 - x : x - 10) * 8); + else v = int16_t(v + 81); + last_pick_quality = int16_t(v - 81); + bool accepted = preset >= 0 ? true : rand.range(0, 180) < v; + if (x == 0 && rand.range(0, 100) != 0) accepted = false; + if (accepted) return player; + } + return 0xFFF; +} + +// SetPieceAnimation + Range4: the animated shot on goal of the live desk. Only the random +// numbers are reproduced here (the picture is the UI's business): the side of the goal, +// the ball's end point and the goalkeeper's reaction frames. +void MatchEngine::shot_animation(bool miss, bool follow_up, int acting_side, int group, int match, int minute) { + static const uint8_t kEndLane[2][2] = {{83, 100}, {217, 234}}; // MatchEngineRuntimeField4, by side + // Frame at which the keeper reacts, by reaction step (0-3) and height band (0-2) + // (LiveMatchday_FormatError_RuntimeField6, 4 bytes per step). + static const uint8_t kReactionFrame[4][4] = {{3, 4, 4, 12}, {7, 8, 13, 13}, {9, 15, 15, 15}, {0, 0, 0, 0}}; + + int side = rand.range(0, 1); // left or right of the goal (index into kEndLane) + int flip = side; // local_c: mirror the goal picture + // A scored follow-up is sometimes shown as a plain shot (param_2 cleared). + if (!miss && follow_up) { + if (rand.range(0, 2) != 0) follow_up = false; + else flip ^= 1; + } else { + follow_up = false; + } + int height = rand.range(0x17, 0x3e); // param_3 of Range4 + int lane = rand.range(kEndLane[side][0], kEndLane[side][1]); // param_2 + + // Range4: the ball's end point; a goal gets some scatter. + int x = lane, y = height; // iVar8, local_6c + if (!miss) { + if (!follow_up) { + x += rand.range(-5, 5) + (lane < 160 ? 5 : lane > 160 ? -5 : 0); + y = rand.range(0, 10) + height - 5; + y = y < 0x1b ? 0x1b : y > 0x46 ? 0x46 : y; + } else { + x = rand.range(kEndLane[flip][0], kEndLane[flip][1]); + y = rand.range(0x17, 0x3e); + } + } + const int band = (y < 0x2f) + (y < 0x22); // local_14 + int reached = 0, step = 0, delay = 0; // local_40, local_44, local_48 + int keeper_delay = 0; // (for the picture: the first reaction comes late) + for (int frame = 0; frame < 18; frame++) { + if (frame == kReactionFrame[step][band] && reached < 3) { + reached++; + // The first reaction of the keeper on a goal comes 2-4 frames late (the + // original draws rand(0, 0) first, which is always 0). + if (!miss && step == 0 && rand.range(0, 0) == 0) delay = keeper_delay = rand.range(2, 4); + else delay = 1; + } + if (int16_t(delay) != 0) { + if (delay == 1) step = reached; + delay--; + } + } + if (show) { + ShowEvent e{Show::ShotOnGoal}; + e.side = uint8_t(side), e.kind = miss; + e.flag = uint8_t((follow_up ? 1 : 0) | (flip ? 2 : 0)); + e.a = height, e.b = lane, e.c = y, e.d = keeper_delay; + emit(std::move(e)); + } + if (live_shot) + live_shot({minute, group, match, acting_side, lane, height, x, y, keeper_delay, miss, flip != 0}); +} + +// LiveSetPieceFrames: the animated set piece of the live desk (kind 1 penalty/free kick from +// `distance`, 2 follow-up, 3 corner-like set piece). The original builds a small sprite +// scene (25 figures with position, speed, direction and a frame timer) and records up to +// 0x576 frames, drawing random numbers while placing the figures and at the "phases" of +// the scene, which start whenever a figure's timer runs out. Only the parts that decide +// the random numbers are reproduced: +// - the placement draws (they depend on each other, not on the sprite state), +// - the phase timeline: the goalkeeper's timer (3 frames) starts phase 0, the kicker's +// run-up timer (t or r frames) phase 1 and so on, +// - the x speed of figure 3 (MatchEngineRuntimeField5), the only sprite state a draw depends on. +// The frame list can never overflow here (at most ~30 frames of <= 26 entries). +// `side` is MatchEngineRuntimeField6 (1 = the home side attacks, the picture is mirrored). +// An installed observer retains those same draws for the UI's figure reconstruction. +void MatchEngine::set_piece_animation(int kind, int distance, int side, int group, int match, int minute) { + std::vector draws; + const auto draw = [&](int low, int high) { + const int value = rand.range(low, high); + if (live_set_piece) draws.push_back({low, high, value}); + return value; + }; + static const int16_t kSpotX[2] = {153, 845}; // LiveSetPiece_Run_ExecutableField5: ball x of a follow-up + static const int8_t kDirection[2] = {-1, 1}; // LiveSetPiece_Run_ExecutableField6 + static const int8_t kPlayerX[8] = {0, 20, 30, 20, 30, 30, 30, 30}; // LiveSetPiece_Run_ExecutableField11 + static const uint8_t kPlayerY[8] = {90, 120, 160, 160, 170, 170, 80, 80}; // LiveSetPiece_Run_ExecutableField4 + static const int8_t kAttackerX[2] = {-20, 20}; // LiveSetPiece_Run_ExecutableField9 + static const int16_t kKeeperX[2] = {65, 936}; // LiveSetPiece_Run_ExecutableField + const int dir = kDirection[side]; + auto clamp1 = [](int v) { return v > 1 ? 1 : v < -1 ? -1 : v; }; + + int param = distance ? uint8_t(distance - 15) : 0; + int ball_x = 0, ball_y = 0; // local_38, DI + int kicker_timer = 0; // frames until phase 1 + if (kind == 1 || kind == 2) { + if (kind == 2) { + ball_x = kSpotX[side]; + ball_y = 0x77; + } else { + ball_y = draw(0x4c, 0xb0); // MatchEngineRuntimeField7 is 0 outside the animated scene + if (param > 0x23) param = 0x23; + // Int16T2: x offset of the goal line at height y + int offset = int16_t(((int16_t(ball_y) - 0x17) * 0x3d) / 0x96); + if (side) { + int base = int16_t(offset + 0x2fd); + ball_x = param ? int16_t(base - param * 5) : draw(0x2ae, base); + } else { + int base = int16_t(-offset + 0xef); + ball_x = param ? int16_t(base + param * 5) : draw(base, 0x136); + } + } + kicker_timer = int16_t(draw(10, 40)) >> 1; // run-up of figure 1 + draw(0, 2); // its y speed + } + int r = 0; + if (kind == 3) { + ball_y = draw(0, 1) ? 0xe6 : -20; + ball_x = kSpotX[side] + int16_t(((int16_t(ball_y) - 0x17) * 0x3d) / 0x96) * (side ? 1 : -1) + dir * 0x19; + draw(-20, 20); + draw(0x6d, 0x8b); + r = draw(8, 12); // flight time of the ball = timer of kicker and ball + draw(0, 5); + draw(1, 4); + draw(1, 6); + } + // Further players (figures LiveSetPiece_Run_ExecutableField10), placed unless too close to the ball. + int placed = 0; + if (kind == 1 || kind == 3) { + for (int i = 0; i < (kind == 3 ? 8 : 4); i++) { + if (kind != 3 && draw(0, 1) == 0) continue; + int x = int16_t(kSpotX[side] + draw(kPlayerX[i] - 10, kPlayerX[i] + 10)); + int y = int16_t(draw(kPlayerY[i] - 10, kPlayerY[i] + 10)); + if (std::abs(x - int16_t(ball_x)) < 100 && std::abs(y - int16_t(ball_y)) < 60) continue; + placed++; + } + } + // Penalty/free kick: two attackers next to the ball (figures 2 and 3); figure 3 may run + // towards the ball (0x6a) or the goalkeeper (0x5f) and then has an x speed. + int speed3 = 0; + if (kind == 1) { + for (int j = 0; j < 2; j++) { + int x, lo, hi; + if (j == 0 && draw(0, 1) != 0) { + x = ball_x; + lo = 3, hi = 6; + } else { + x = int16_t(ball_x + draw(kAttackerX[j] - 10, kAttackerX[j] + 10)); + lo = 5, hi = 20; + } + x = int16_t(x + dir * int16_t(draw(lo, hi))); + draw(4, 10); + if (draw(0, 1) == 0) draw(0, 10); + int code = 0xaa; + if (draw(0, 1) == 0 && x - kKeeperX[side] > int16_t(ball_x) - kKeeperX[side]) + code = draw(0, 1) ? 0x5f : 0x6a; + if (j == 1) { + if (code == 0x6a) speed3 = clamp1(int16_t(ball_x) - x); + else if (code == 0x5f) speed3 = clamp1(kKeeperX[side] - x); + } + } + } + + // --- phases ------------------------------------------------------------------------- + if (kind == 1 || kind == 2) { + // frame 3: goalkeeper (phase 0, no draws); frame t: the shot (phase 1); frame t+1: + // phase 2 ends a follow-up, a penalty/free kick ends at phase 3 (no draws). + draw(7, 12); // ball speed; the figure of this number may run in (kind 1) + draw(0, 1); + if (kind == 1) { + draw(0, 1); + if (speed3 == 0) draw(0, 1); + } + (void)kicker_timer; + } else if (kind == 3) { + // Phase 0 (goalkeeper, frame 3), 1 (kicker, frame r), 2 (ball, same frame), 3 and 4: + // after every phase each placed player turns (one draw each). + auto players_turn = [&]() { + for (int i = 0; i < placed; i++) draw(0, 1); + }; + players_turn(); // phase 0 + draw(0, 2); // phase 1: header height + players_turn(); + draw(8, 10); // phase 2: ball speed + draw(0, 1); + draw(3, 5); // always: the flag it tests (local_3c) is never 0 by then + players_turn(); + players_turn(); // phase 3 + players_turn(); // phase 4 (end) + } + if (show) { + ShowEvent e{Show::SetPiece}; + e.side = uint8_t(side), e.kind = uint8_t(kind); + e.a = ball_x, e.b = ball_y, e.c = kicker_timer, e.d = r; + emit(std::move(e)); + } + if (live_set_piece) + live_set_piece({minute, group, match, side, kind, distance, std::move(draws)}); +} + +// OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// Emit (supported rule profile patch): line-up slot (0-10) of the taker a human manager has +// designated for a set piece (manager record field at `offset`: 0xafc penalty, 0xafe +// penalty follow-up, 0xb08 free kick), or -1. The taker must play, be fit and differ from +// `exclude`. The original reads the record of the "current" manager ActiveManager and looks +// for the player in the shooting team; for computer teams that never matches, so the +// team's own manager is used here (identical with one human manager). +int MatchEngine::designated_slot(int team, int offset, int exclude) const { + int manager = state.manager_of(team); + if (manager < 0 || state.manager_records.empty()) return -1; + const uint8_t* rec = state.manager_records.data() + size_t(manager) * 0xB0C; + auto u16 = [&](int at) { return int(rec[at] | rec[at + 1] << 8); }; + if (u16(0xb0a) != 0x3253) return -1; + int id = u16(offset); + if (id == 0 || id > 0xFFF) return -1; + id--; + SquadRange range = squad_range(team); + for (int s = 0; s < 11 && range.count != 0; s++) { + uint16_t entry = state.squad_slots.at(range.first + s); + if (!(entry & kSlotInLineup)) continue; + int player = entry & 0x0FFF; + if (player != id || player == exclude || player == 0xFFF) continue; + if (state.players.at(player).w364 >> 16 & 0x1F) continue; // injured or banned + return s; + } + return -1; +} + +// DesignatedSlot / PickPlayer: pick with a designated taker first (penalty shooter when +// kind 1, free kick taker when kind 3); if that fails, the normal pick. +int MatchEngine::pick_taker(int team, int mode, int exclude, int kind, MinuteReport& report) { + int preset = -1; + if (kind == 1 && (mode & 0x7F) == 2) preset = designated_slot(team, 0xafc, exclude); + if (kind == 3 && (mode & 0x7F) == 3) preset = designated_slot(team, 0xb08, exclude); + if (preset >= 0) { + int player = pick_player(team, mode, exclude, report, preset); + if (player != 0xFFF || report.unsupported) return player; + } + return pick_player(team, mode, exclude, report); +} + +// Injure through the line-up module; human teams are reported as unsupported. +bool MatchEngine::substitute(int team, int off, int mode, MinuteReport& report) { + try { + return bmh::substitute(state, team, off, mode, rand); + } catch (const std::exception& ex) { + report.fail(std::string("substitution: ") + ex.what()); + return false; + } +} + +// BuildSideRecords3 for one side of match m: rebuilds the side record after a line-up change +// (substitution, sending-off, injury). MatchRuntimeField points to the own record at every call +// site in the match loop, so its byte 6 is the "previous" balance. +void MatchEngine::rerate_team(int team, MinuteReport& report) { + for (MatchGroup& g : groups) + for (int m = 0; m < g.matches(); m++) + for (int s = 0; s < 2; s++) + if (g.fixtures.at(size_t(m * 2 + s)) == team) { + rerate(g, m, s, report); + return; + } + report.fail("re-rating: the team plays no match today"); +} + +void MatchEngine::rerate(MatchGroup& g, int m, int s, MinuteReport& report) { + if (g.spectators.size() < size_t(g.matches())) { + report.fail("re-rating needs the attendance (not recorded)"); + return; + } + uint8_t* own = g.records.data() + m * 18 + s * 9; + MatchSetup setup; + setup.home = g.fixtures.at(m * 2); + setup.away = g.fixtures.at(m * 2 + 1); + setup.match_index = m; + setup.climate_effect = (g.flags() & 2) != 0; + setup.temperature = int8_t(g.desc.at(0x30 + m)); + setup.spectators = int(g.spectators[m]); + setup.month = month; + try { + rate_side(state, setup, s, own[6], rand, own, &game); + } catch (const std::exception& ex) { + report.fail(std::string("re-rating: ") + ex.what()); + } +} + +namespace { + +// OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// Injury type tables of InjurePlayer3 (supported rule profile patch): WatcomRandom(0, 999) is mapped to an +// injury type by the first threshold it does not exceed; beyond the last one the type is +// 30. Match injuries use the second table (types 6-30, the light types 0-5 of the first +// table only happen elsewhere, e.g. in training). +constexpr uint16_t kInjuryThresholdsOther[30] = { + 0x01f, 0x03f, 0x05f, 0x07f, 0x09f, 0x0bf, 0x0f1, 0x122, 0x153, 0x184, 0x1b5, 0x1e6, 0x217, 0x248, 0x279, + 0x2aa, 0x2db, 0x30c, 0x33d, 0x36e, 0x37e, 0x38e, 0x39e, 0x3ae, 0x3be, 0x3c9, 0x3d4, 0x3da, 0x3e0, 0x3e6}; +constexpr uint16_t kInjuryThresholdsMatch[24] = { + 0x03c, 0x079, 0x0b6, 0x0f3, 0x130, 0x16d, 0x1aa, 0x1e7, 0x224, 0x260, 0x29c, 0x2d8, + 0x315, 0x351, 0x365, 0x379, 0x38d, 0x3a1, 0x3b5, 0x3c3, 0x3d1, 0x3d8, 0x3df, 0x3e6}; +// Injury duration (matchdays) by type, table at layout field. Types 0-2 cause no absence. +constexpr uint8_t kInjuryDuration[31] = {1, 1, 1, 2, 2, 2, 2, 3, 2, 3, 2, 2, 2, 2, 3, 4, + 2, 3, 2, 3, 6, 8, 6, 8, 10, 12, 16, 20, 24, 28, 30}; +// Event log codes by event kind (MatchEngineRuntimeField8): yellow, red, injury. A second yellow card +// is logged as red - 1 = 4. +constexpr uint8_t kEventLogCode[3] = {3, 5, 6}; +// Class of each competition (MatchEngineRuntimeField9, by descriptor byte 0): 0 for league (0) and +// the competitions 10 and 20-23, which count cards per team; 0xFF = unused id. +constexpr std::array kCompetitionClass = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255, + 4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0}; + +} // namespace + +// OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// InjurePlayer(slot, roll, match, manager) with its supported rule profile continuation (InjurePlayer4, +// InjurePlayer3, InjurePlayer2, Int16T4, tail at layout field): injures the player in the +// absolute squad slot. Returns the injury type; human insurance, club doctor, +// tactics-board flags and messages are handled below. The watched-match caller +// owns any subsequent interactive substitution through live_event. +int injure_player(GameState& g, int slot, int type, bool match, int manager, WatcomRandom& rand) { + const int id = g.squad_slots.at(size_t(slot)) & 0x0FFF; + Player& p = g.players.at(size_t(id)); + // Bits 13-15 of w364 protect the player (not decoded yet): nothing happens. + if (p.w364 >> 8 & 0xE0) return type; + + // OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// InjurePlayer3 (supported rule profile) ignores the type passed in and draws it + const int roll = rand.range(0, 999); + type = 30; + if (match) { + for (int i = 0; i < 24; i++) + if (roll <= kInjuryThresholdsMatch[i]) { type = i + 6; break; } + } else { + for (int i = 0; i < 30; i++) + if (roll <= kInjuryThresholdsOther[i]) { type = i; break; } + } + int duration = type > 2 ? kInjuryDuration[type] : 0; + // w35c bits 27-31 remember the last injury type + 1: a player injured before is out + // 1/8 longer (match injuries only). + if (match && (p.w35c >> 27) != 0) duration = uint8_t(duration + (duration >> 3)); + if (manager >= 0) { + // layout field: a player insured on the tactics board (slot byte 0x43, bits 6-7 the + // cover) earns base pay * (50 + 50 * cover) / 100 per week while out (SquadRange2); + // the manager is told so ("Ihre Versicherung zahlt Ihnen ...", MatchEngineRuntimeField10 " ") + const SquadRange range = squad_range(g.manager_teams.at(size_t(manager))); + const size_t board = size_t(manager) * 0x840 + (size_t(slot) - range.first) * 0x58; + const uint8_t cover = g.tactics.at(board + 0x43); + if (cover != 0 && duration != 0) { + const int32_t base = int32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16 | g.tactics.at(board + 0x53) << 24); + const int32_t pay = base * ((int8_t(cover) >> 6 & 3) * 0x32 + 0x32) / 100; + post_composed(g, manager, message_text(g, ::bmh::layout::MatchEngine_InjurePlayer_TextPointer) + g.player_name(id) + " " + format_amount(g, pay) + + message_text(g, ::bmh::layout::MatchEngine_InjurePlayer_TextPointer2)); + } + } + if (manager >= 0 && duration != 0) { + // A human manager's club doctor (record +0x8ae) shortens the absence by + // duration * (doctor / 100 - 5) / 16, at most 1 matchday for types 3-19, up to 5 for + // the heavy ones (Int16T4); a poor doctor makes it longer. + const int doctor = int16_t(g.manager_records.at(size_t(manager) * 0xB0C + 0x8ae) | + g.manager_records.at(size_t(manager) * 0xB0C + 0x8af) << 8); + // (the / 16 is Watcom's SAR/SHL/SBB idiom at 00054453: (x + 7) >> 4 for negative + // x, so a poor doctor lengthens by one matchday from x = -8 on) + const int x = duration * (doctor / 100 - 5); + int cut = (x + (x < 0 ? 7 : 0)) >> 4; + int cap = type >= 3 ? 1 : 0; + if (type >= 0x14) cap = ((type - 0x10) >> 2) + 1 + (type >= 0x1a ? 1 : 0); + if (cut > cap) cut = cap; + duration = uint8_t(duration - cut); + } + duration = std::clamp(int(int8_t(duration)), 0, 30); // Int8T + p.w35c = (p.w35c & 0x07FFFFFFu) | uint32_t(type + 1) << 27; // BH = 1 at InjurePlayer + p.w364 = (p.w364 & 0xFFE0FFFFu) | uint32_t(duration) << 16; + return type; +} + +bool MatchEngine::injure(int slot, bool match, int manager, MinuteReport& report) { + (void)report; + injure_player(state, slot, 0, match, manager, rand); + return true; +} + +// EventImpl(-1, 0, side): a foul by `side` in match m. After the referee and team rolls +// the event is one of +// kind 2 injury (1 in 39): a random line-up player is injured and substituted, +// kind 1 straight red card (1 in 28 of the bookings), banned for 1-4 matches, +// kind 0 yellow card; a second yellow in the same match turns into a red card (ban 1). +// The ordinary minute loop ignores the return byte. Its draw order, immediate +// substitutions and synchronous presenters remain the Source mode0 path. +void MatchEngine::event(MatchGroup& g, int m, int s, int minute, MinuteReport& report) { + (void)event_impl(g, m, s, minute, -1, report); +} + +ForcedMatchEvent MatchEngine::forced_event(MatchGroup& g, int m, int s, int minute, + int absolute_slot, MinuteReport& report) { + if (s < 0 || s > 1 || m < 0 || m >= g.matches()) + throw FormatError("Reality event needs a valid fixture and side"); + const auto range = squad_range(g.fixtures.at(m * 2 + s)); + if (absolute_slot < int(range.first) || absolute_slot >= int(range.first + range.count)) + throw FormatError("Reality offender is outside the selected team's squad"); + return event_impl(g, m, s, minute, absolute_slot, report); +} + +ForcedMatchEvent MatchEngine::event_impl(MatchGroup& g, int m, int s, int minute, + int fixed_slot, MinuteReport& report) { + ForcedMatchEvent result; + const bool forced = fixed_slot >= 0; + if (match_events_disabled) return result; + show_at(g, m, minute); + // The stricter the referee (bits 3-4 of his table byte), the likelier an event. + int referee = g.desc.at(0x10 + m); + int k = int8_t(3 - (referees.at(referee) >> 3 & 3)) + 1; + if (rand.range(0, k) != 0) return result; + + int team = g.fixtures.at(m * 2 + s); + int opp_team = g.fixtures.at(m * 2 + 1 - s); // MatchEngineRuntimeField11 + // Small-squad teams (id >= 90) only half of the time; teams without squads never. The + // national team (0x165, squad nominated on the national team days) only while manager + // slot 0 holds it (CupDraw_FormatError_RuntimeField2 == 0x165: a Bundestrainer's match). + if (!(team < 90 || rand.range(0, 1) == 0)) return result; + if (!(team < 138 || team == kNoTeam)) return result; + if (team == kNoTeam && (state.manager_teams.empty() || state.manager_teams[0] != kNoTeam)) return result; + const int manager = state.manager_of(team); // FindManagerForClub, local_6c + const bool human = manager >= 0; + SquadRange range = squad_range(team); // SquadRange4 + + int kind = 0; // local_70: 0 yellow, 1 red, 2 injury + int card_delta = 0; // added to the team's card counters + int ban = 0; // local_80: matches banned for a red card (0 = no red card) + if (!forced && rand.range(0, 38) == 0) { + kind = 2; + rand.range(10, 30); // local_7c: passed to InjurePlayer but overwritten there + } else { + if (rand.range(0, 2) == 0) return result; // no booking after all + // local_5c = the team's card counters DeskRecords_Teams_RuntimeField (low byte yellow, high byte red; + // red cards only counted in competitions 0 and 10) + if (rand.range(0, 27) == 0) { + kind = 1; + ban = rand.range(1, 4); + if (g.desc.at(0) == 0 || g.desc.at(0) == 10) card_delta = 0x100; + } else { + card_delta = 1; + } + } + if (range.count == 0) return result; + + // Pick the offender: mode0 draws slot0-11, mode1 keeps the supplied slot. + // Empty or not playing ends the event. Players + // with more condition than technique foul more; goalkeepers rarely (1 in 5, injuries + // 1 in 2). + int slot = 0, player = 0; + for (int tries = 0;; tries++) { + slot = forced ? fixed_slot : int(range.first) + rand.range(0, 11); + uint16_t entry = state.squad_slots.at(slot); + if (entry == 0x0FFF) return result; + if (!(entry & kSlotInLineup)) return result; + player = entry & 0x0FFF; + const Player& p = state.players.at(player); + int balance = int8_t(uint8_t(p.condition() - p.technique())); + if (rand.range(0, 20) > balance + 15 - int8_t(tries)) continue; + if (p.position() != 0 || rand.range(0, kind == 2 ? 1 : 4) == 0) break; + } + Player& p = state.players.at(player); + + if (kind == 2) { + if (human && rand.range(0, 2) != 0) { + // layout field: with 2 in 3 the slot's byte 0x0f of the tactics board protects the + // player of a human team: no injury if W(0, 60) exceeds it (the event ends) + const int protection = state.tactics.at(size_t(manager) * 0x840 + (size_t(slot) - range.first) * 0x58 + 0xf); + if (rand.range(0, 60) > protection) return result; + } + if (!injure(slot, true, manager, report)) return result; + } + + bool second_yellow = false; // local_74 + if (kind == 0 && (state.squad_slots.at(slot) & 0x1000)) { + kind = 1; + second_yellow = true; + ban = 1; + } + if (kind == 0) { + int yellow = int(p.w368 >> 14 & 0xF); // yellow cards this season + if (yellow < 15) yellow++; + p.w368 = (p.w368 & 0xFFFC3FFFu) | uint32_t(yellow) << 14; + state.squad_slots.at(slot) |= 0x1000; // booked in this match + } + auto bump = [&](int offset) { // descriptor counters: +0xbc bookings, +0xc0 red cards + uint32_t v = le32(g.desc, offset) + 1; + for (int i = 0; i < 4; i++) g.desc.at(offset + i) = uint8_t(v >> (8 * i)); + }; + if (ban != 0) { + bump(0xc0); + // OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// Absence (supported rule profile): the ban goes to w364 bits 16-20 (duration | 0x10 = banned + // instead of injured). A player with an injury history (w35c bits 27-31) keeps a + // running injury; if he is fit, the history is cleared outside competitions + // (MatchEngineRuntimeField9 flag of the competition, local_9c). + bool set_ban = true; + if (p.w35c >> 27) { + bool competition = kCompetitionClass.at(g.desc.at(0)) != 0; + if ((p.w364 >> 16 & 0x1F) == 0 && !competition) p.w35c &= 0x07FFFFFFu; + else set_ban = false; + } + if (set_ban) { + p.w364 &= 0xFFE0FFFFu; + p.w364 |= uint32_t(ban) << 16 | 0x100000u; + } + // layout field: team flag bit 0 (sent-off player) and w368 bits 24-26. The original + // clears the field before reading it back, so the "counter" always becomes 1. + state.team_flags.at(team) |= 1; + p.w368 = (p.w368 & 0xF8FFFFFFu) | 0x01000000u; + } else if (kind != 2) { + bump(0xbc); + } + // Sent off or injured: the player leaves the pitch (slot flags 0x1000-0x8000 cleared). + if (ban != 0 || kind == 2) state.squad_slots.at(slot) &= 0x0FFF; + + g.log.push_back(uint16_t(player + (kEventLogCode[kind] - second_yellow) * 0x1000)); + g.log.push_back(uint16_t(team * 0x80 + minute)); + + // When one of the teams is watched live (MatchEngineRuntimeField12, team flag bits 6/7 of team or + // opponent) the event is shown in a message box (DcThat, DrawnFirstBy). That is + // pure presentation without random numbers (verified against the matchday 4 + // recording): a Booking ShowEvent for the UI (presentation.hpp). + if (show || live_booking) { + const int shown_kind = second_yellow ? 3 : kind; // bStack_3c + const int foul = second_yellow ? 0 : kind; // local_44 + const int flags = (state.team_morale.at(team) & 0xC0) | (state.team_morale.at(opp_team) & 0x80); + const bool has_live_matches = !state.live_matches.empty(); + const bool box = !forced && has_live_matches && ((flags == 0x80 && (foul != 0 || !button(::bmh::layout::MatchEngine_EventImpl_ExecutableField))) || + (flags == 0x40 && ((foul == 0 && !button(::bmh::layout::MatchEngine_EventImpl_ExecutableField2)) || (foul != 0 && !button(::bmh::layout::MatchEngine_EventImpl_ExecutableField3))))); + if (show) { + ShowEvent e{Show::Booking}; + e.side = uint8_t(s), e.kind = uint8_t(shown_kind), e.flag = box; + e.team = int16_t(team), e.player = int16_t(player); + e.a = int32_t(p.w368 >> 14 & 0xF); // yellow cards of the season (shown for a yellow card) + e.b = ban; + e.text = message_text(state, ::bmh::layout::LiveMatchday_FormatError_TextPointer2 + uint32_t(shown_kind) * 4) + state.player_name(player); + emit(std::move(e)); + } + if (live_booking && box) + live_booking({minute, show_group, m, s, shown_kind, team, player, int(p.w368 >> 14 & 0xf), ban}); + } + + // Substitution: always after an injury, after a yellow card 1 in 13 (Injure with + // mode position + 20: a substitute of the same position). A sent-off player is not + // replaced. + bool change = kind == 2 || (kind == 0 && ban == 0 && rand.range(0, 12) == 0); + if (trace) + std::fprintf(stderr, " event m%d s%d team %d kind %d second %d ban %d player %d slot %d change %d\n", m, s, team, kind, + int(second_yellow), ban, player, int(slot - range.first), int(change)); + // A human team that is watched (team byte bit 7, option LiveDeskDisabled off) is changed + // automatically only when the assistant may substitute (option byte 1); otherwise the + // manager gets the substitution screen after a red card or an injury (PitchScreen). + const bool watched = !live_desk_disabled && (state.team_morale.at(team) & 0x80); + const bool assistant = !human || !watched || state.manager_option(manager, 1); + if (change && assistant && forced) { + result.change = DeferredRealityChange{false, team, slot, p.position() + 20}; + } else if (change && assistant) { + const bool changed = substitute(team, slot, p.position() + 20, report); + if (report.unsupported) return result; + if (changed && show) { + ShowEvent e{Show::Substitution}; + e.side = uint8_t(s), e.team = int16_t(team), e.player = int16_t(player); + e.other = int16_t(state.squad_slots.at(slot) & 0x0FFF); // the substitute took the slot + emit(std::move(e)); + } + } else if (kind != 0 && human && watched && !state.manager_option(manager, 1)) { + if (forced) { + result.change = DeferredRealityChange{true, opp_team, 0xff, manager}; + result.code = 0x80; + } else if (live_event) { + const size_t group_index = size_t(&g - groups.data()); + live_event(LiveMatchEvent{group_index, m, s, team, opp_team, player, + kind, minute, manager}); + } else if (!leave_screens) { + report.fail("substitution screen of a human manager after an event (PitchScreen)"); + return result; + } + } + // the team's card counters (league-class competitions) and a human manager's card + // statistics by minute (record +0x1ae) + if (kind < 2 && kCompetitionClass.at(g.desc.at(0)) == 0) { + if (state.memory.has(::bmh::layout::DeskRecords_Teams_RuntimeField)) { + const uint32_t at = ::bmh::layout::DeskRecords_Teams_RuntimeField + uint32_t(team) * 2; + state.memory.set16(at, uint16_t(state.memory.u16(at) + card_delta)); + } + if (human) { + const int bucket = std::min(minute, 0x59) / 5; + state.manager_records.at(size_t(manager) * 0xB0C + 0x1ae + size_t(bucket) + size_t((kind == 1) + 2) * 0x12)++; + } + } + + // Red card or injury: the side plays with a different line-up - re-rate it. The minute + // loop keeps using the rhythm and attitudes it read before the event. + if (kind != 0) rerate(g, m, s, report); + result.code |= uint8_t(kEventLogCode[kind] - second_yellow - 2); + return result; +} + +void MatchEngine::side(MatchGroup& g, int m, int& s, int minute, int& own_att, int& opp_att, MinuteReport& report) { + uint8_t* rec = g.records.data() + m * 18; + uint8_t* own = rec + s * 9; + uint8_t* other = rec + (1 - s) * 9; + const int away_penalty = s == 1 ? (g.flags() & 2) >> 1 : 0; // local_b0[side] + show_at(g, m, minute); + + int rhythm = clamp(own[7], 44, 80); // MatchRuntimeField2 + + // --- event roll (AlternateEventRoll selects an alternative range, separately from indoor) --- + bool trigger = alternate_event_roll ? rand.range(0, 10) > 7 : rand.range(0, 220) < rhythm - 30; + if (trigger) { + event(g, m, s, minute, report); + if (report.unsupported) return; + // The synchronous Source event presenter may stage/restore GameState and + // per-match record buffers. Reacquire the record pointers before continuing + // the chance path for this same side/minute. + rec = g.records.data() + m * 18; + own = rec + s * 9; + other = rec + (1 - s) * 9; + } + + // --- chance roll --------------------------------------------------------------------------- + int roll = game.range(0, away_penalty * 4 + 44); + if (int16_t(opp_att + own_att + 3 + (indoor ? 14 : 0)) < roll) return; // no chance + + int team = g.fixtures.at(m * 2 + s), opp_team = g.fixtures.at(m * 2 + 1 - s); + // A side whose record byte 2 (its attack strength) is 0 gets no chance at all: the + // original only notes the two clubs (MatchEngineRuntimeField13/afafe) and skips the whole chance + // block, without the result-screen part after it (WEEK240). + if (own[2] == 0) return; + int attack = int16_t(own[2] + game.range(0, rhythm) / 10 + own_att * 2 - 9); // uVar5 + if (minute < clamp(own[6], 50, 130)) attack = int16_t(attack + game.range(6, 12)); + int defence = int16_t(other[2] + (3 - opp_att) * 2); // local_a0 + if (game.range(0, 100) < other[6]) defence = int16_t(defence + 5); + + // MatchScore (read) + BuildSideRecords2: adapt the attitude to the current score. Called + // 1 in 41 times per chance roll, and always around a chance in the match shown live. + auto update_attitude = [&]() { + // A human manager sets the attitude himself (manager record +0xd2) unless his + // assistant coach is in charge (option byte 2); substitutions need option byte 1. + const int manager = state.manager_of(team); + if (manager >= 0 && !state.manager_option(manager, 2)) { + if (state.manager_records.empty()) { + report.fail("attitude of a human team needs the manager records (savegame)"); + return; + } + own[8] = state.manager_records.at(size_t(manager) * 0xB0C + 0xd2); + return; + } + int home = 0, away = 0; + if (!g.results.empty()) { + home = g.results.at(m) >> 4; + away = g.results.at(m) & 0x0F; + } else if (g.cup_results.size() == size_t(g.matches())) { + home = g.cup_results[m] >> 5 & 0x1F; + away = g.cup_results[m] & 0x1F; + } else { + report.fail("attitude update needs the cup score (not recorded)"); + return; + } + int substitution = -1; + int attitude = attitude_update(own, other, s, m, s == 0 ? home : away, s == 0 ? away : home, minute, rand, substitution); + if (substitution >= 0 && (manager < 0 || state.manager_option(manager, 1))) { + // BuildSideRecords2 calls Injure(team, 0, mode) before storing the attitude. + substitute(team, 0, substitution, report); + if (report.unsupported) return; + } + own[8] = uint8_t(attitude); + }; + + // --- match shown live (local_100) ------------------------------------------------------ + // Team flag 0x80 (of either team): the match is shown on the live desk; the attitude is + // updated at once and the ball position of the display is drawn (local_f4, Watcom + // 10-35, sign = direction of play). Team flag 0x40: ticker mode (local_fc), mode 2. + // LiveDeskDisabled suppresses both. The animated scene (RealityReporterPanel) additionally needs + // LiveSceneVisible and both clubs below the executable squad limit. + int live = 0; + bool ticker = false; + if (!live_desk_disabled) { + const int flags = state.team_morale.at(team) | state.team_morale.at(opp_team); + if (flags & 0x80) { + update_attitude(); + if (report.unsupported) return; + live = 1; + rand.range(10, 35); + } + if (flags & 0x40) { + live = 2; + ticker = true; + } + } + + if (trace && live) std::fprintf(stderr, " live m%d s%d team %d mode %d minute %d\n", m, s, team, live, minute); + if (game.range(0, 40) == 0) { + update_attitude(); + if (report.unsupported) return; + } + // Random substitution; if one happens the side is re-rated (BuildSideRecords3). + if (game.range(0, 40) == 0 && substitute(team, 0, 10, report)) rerate(g, m, s, report); + if (report.unsupported) return; + state.chance_rain = g.desc.at(0x50 + m); + state.chance_temperature = int8_t(g.desc.at(0x30 + m)); + + int quality = int16_t((attack - defence) / 2 + 13 - away_penalty * 8); + if (defence < attack && quality < 20) { + quality = int16_t(quality + ((attack - defence) >> 1)); + if (quality > 20) quality = 20; + } + quality = clamp(quality, 5, 24); + int threshold = kChanceTable[quality]; + if (trace) + std::fprintf(stderr, " attack m%d s%d attack %d defence %d quality %d threshold %d away %d\n", m, s, attack, defence, + quality, threshold, away_penalty); + if (game.range(0, 4 - away_penalty) != 0 && game.range(0, away_penalty * 4 + 56) >= threshold) + return; // the attack comes to nothing + + // --- a real chance ------------------------------------------------------------------------ + int shooter = 0xFFF, assistant = 0xFFF, keeper = 0xFFF; + state.last_shooter = 0xFFF; + bool attempt = false; // local_80 + int kind = 0; // MatchEngineRuntimeField14: 0 open play, 1 free kick, 2 penalty, 3 corner + if (game.range(0, 5) == 0) kind = 1; + if (game.range(0, 6) == 0) kind = 3; + + int keeper_value = 1; // local_a0 from here on + int shot = 0; // uVar5 + int shot_limit = 0; // uVar14 + // local_3c is set after every shooter pick; local_84 only when an assistant is picked, + // otherwise it keeps the value of an earlier chance (it is never initialised) + int shooter_q = 0; + int& assistant_q = stale_assistant_quality; + bool reality_played = false, reality_attempted = false; + int reality_distance = 0; + if (kind == 0 && live == 1 && live_scene_visible && !indoor) { + if (!reality_rules) { + report.fail("Reality chance needs the loaded executable (RealityReporterPanel)"); + return; + } + const auto& exe = *reality_rules; + if (team < exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField) && opp_team < exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) { + const int displacement = (1 - s * 2) * rand.range(21, 45); + if (live_ball && button(::bmh::layout::MatchEngine_Side_ExecutableField3) == 0) + live_ball({minute, show_group, m, displacement}); + auto context = reality_runtime.context; + context.rating = RatingContext{state.chance_rain, state.chance_temperature}; + context.rating.game = &game; context.rating.live_scene = true; + context.retained_cue_actors = state.reality.cue_actors; + context.retained_card_kind = state.reality.card_kind; + context.retained_deflection = state.reality.deflected; + context.retained_distance = state.reality.distance; + // Muted is the Source sound switch; the routine still draws its + // qualified random sound selector, regardless of the observer. + context.muted = button(::bmh::layout::MatchEngine_Side_ExecutableField4) != 0; + context.sound = original_sound; + RealityMatchScene owner; + owner.scene = std::move(reality_runtime); + owner.scene.setup.grid = state.reality.grid; + initialize_reality_match_scene(*this, size_t(show_group), m, s, minute, exe, context, owner); + if (live_reality && owner.scene.setup.ready) + live_reality({LiveRealityStage::begin, minute, show_group, m, s, {}}); + while (!owner.scene.finished) { + auto tick = advance_reality_match_scene(*this, owner, exe, report); + if (report.unsupported) return; + if (live_reality && live_reality({LiveRealityStage::round, minute, show_group, m, s, std::move(tick)}) && + !owner.scene.finished) + exit_reality_scene_after_animation(owner.scene); + } + if (live_reality && owner.scene.setup.ready) + live_reality({LiveRealityStage::settling, minute, show_group, m, s, {}}); + if (owner.scene.result.scene_status == 3 && original_sound) original_sound(18); // RealityReporterPanel. + settle_reality_match_scene(*this, owner, report); + if (report.unsupported) return; + // Assign2(1) clears MatchdaySetupRuntimeField12 at its first active fixture. AutoLineup + // rebuilds the watched list in group/match order and calls the + // existing drawless Int2 for each displayed pair (mode0..7). + state.live_matches.clear(); + for (const auto& group : groups) for (int match = 0; match < group.matches(); ++match) { + if (((group.ended | group.void_mask()) >> match) & 1) continue; + const int home = group.fixtures.at(size_t(match)*2), away = group.fixtures.at(size_t(match)*2+1); + if (live_desk_disabled || state.live_matches.size() >= 4 || + !((state.team_morale.at(size_t(home)) | state.team_morale.at(size_t(away))) & 0x80) || + std::find(state.live_matches.begin(),state.live_matches.end(),home) != state.live_matches.end()) continue; + const int mode = int(state.live_matches.size())*2; + auto_lineup(state,home,mode); auto_lineup(state,away,mode+1); + state.live_matches.push_back(home); + } + if (live_reality && owner.scene.setup.ready) { + RealitySceneTick ended; ended.finished = true; ended.result = owner.scene.result; + live_reality({LiveRealityStage::end, minute, show_group, m, s, std::move(ended)}); + } + const auto result = owner.scene.result; + reality_runtime = std::move(owner.scene); + if (result.return_flags & 0x80) s ^= 1; // also changes EndPhase's next side iteration + team = g.fixtures.at(m * 2 + s); opp_team = g.fixtures.at(m * 2 + 1 - s); + // A genuine human intervention may replace the buffers in place. + rec = g.records.data() + m * 18; own = rec + s * 9; other = rec + (1 - s) * 9; + kind = result.restart; + attempt = (result.return_flags & 0x7f) != 0; + reality_attempted = result.shot_attempted; + shooter = result.shooter; assistant = result.assistant; keeper = result.keeper; + last_shooter_slot = result.shooter_row; last_assist_slot = result.assistant_row; + state.last_shooter = shooter; + reality_distance = result.distance; + state.reality.cue_actors = reality_runtime.context.retained_cue_actors; + state.reality.card_kind = reality_runtime.context.retained_card_kind; + state.reality.deflected = result.deflected; + state.reality.distance = result.distance; + state.reality.grid = reality_runtime.setup.grid; + reality_played = true; + } + } + if (kind != 0 || !reality_played) { + int rating = own[3 + kind]; + shot = rating; + int dice = 0, close = 0; + if (rating == 0) { + shot_limit = 0; + close = 1; + } else { + keeper_value = other[1]; + shot_limit = clamp(rating + 2 - keeper_value, 3, 15); + close = game.range(0, 4); + dice = rand.range(0, 90); + } + if (kind != 0 || close == 0 || dice < shot_limit * 4) { + if (live) rand.range(21, 45); // ball position of the live display + shooter = pick_taker(team, kind == 1 ? 2 : 0, 0xFFE, kind, report); + if (report.unsupported) return; + state.last_shooter = shooter; + shooter_q = uint8_t(last_pick_quality); + if (shooter != 0xFFF && kind != 1) { + assistant = pick_taker(team, (kind == 3 ? 3 : 1) | 0x80, shooter, kind, report); + if (report.unsupported) return; + assistant_q = uint8_t(last_pick_quality); + } + attempt = true; + } + } + + // Goalkeeper of the opponent: the player in squad slot 0 if the formation puts it in goal. + if (!reality_played && (opp_team < 168 || opp_team == kNoTeam)) { + int x = 0, y = 0; + state.formation_position(opp_team, 0, x, y); + if (x == 0 && y == 4) keeper = state.squad_slots.at(squad_range(opp_team).first) & 0x0FFF; + } + + if (kind == 0 && !attempt) { + // An offside/boundary shot has bdb7b=1 but no returned attempt. Source + // logs this miss with its raw grid distance and omits goal rolls/UI. + if (reality_played && reality_attempted) { + g.log.push_back(uint16_t(shooter + 0x1000)); + g.log.push_back(uint16_t(team * 0x80 + minute)); + g.log.push_back(uint16_t(assistant + 0x2000)); + g.log.push_back(uint16_t(team * 0x80 + reality_distance)); + } + return; + } + const int ball_position = live ? (1 - s * 2) * rand.range(40, 50) : 0; + + RatingContext ctx{state.chance_rain, state.chance_temperature}; + int distance = 0; // MatchEngine_Minute_ExecutableField4, shot difficulty + bool deflected = state.reality.deflected; // MatchEngine_Minute_ExecutableField3 + int& penalty_score = stale_set_piece_score; // local_9c is unwritten for a Reality penalty + int shown_distance = 0; // MatchEngineRuntimeField15: distance shown by the live desk (kind 1) + if (reality_played) { + distance = uint8_t(reality_distance * 5 / 2); + } else { + int spread = 30; + if (keeper_value < shot - 20) spread = 30 - (shot - keeper_value); + if (spread < 25) spread = 25; + distance = uint8_t(game.range(9, spread)); + if (distance < 17 && kind != 0) distance = uint8_t(game.range(9, spread)); + deflected = game.range(0, 5) == 0; + } + if (kind == 0) { + if (team >= 168 && team != kNoTeam) { + // clubs without squad: the attack rating (TeamRating, profile 3), drawn + RatingContext drawn; + drawn.rand = &rand; + shot = int16_t(team_rating(state, team, kRatingProfiles[3], drawn)); + } else { + shot = int16_t(player_value(state, shooter, 0x87, 100, team, ctx)); + } + } + if (keeper == 0xFFF) { + if (opp_team >= 168 && opp_team != kNoTeam) { + // clubs without squad: the goalkeeping rating (profile 0), drawn + RatingContext drawn; + drawn.rand = &rand; + keeper_value = int16_t(team_rating(state, opp_team, kRatingProfiles[0], drawn)); + } else { + keeper_value = 0; + } + } else { + int v = player_value(state, keeper, 7, 100, opp_team, ctx); + keeper_value = int16_t(v); + if ((state.players.at(keeper).w364 & 3) != 0 && game.range(10, 25) > distance) + keeper_value = int16_t(int16_t(v) / 4); // not a real goalkeeper in goal + } + if (kind == 0) { + if (deflected && keeper_value < game.range(0, 100)) { + shot = int16_t(80 - distance); + keeper_value = 30; + } + keeper_value = int16_t((keeper_value << 2) / 5); + shot = int16_t(int16_t(shot * (100 - distance) / 100) - distance); + } else { + if (!reality_played && distance > 30) distance = uint8_t(game.range(17, 35)); + if (!reality_played && distance < 17 && kind == 1) { + // The keeper parries the penalty: follow-up shot (kind 2). + kind = 2; + deflected = false; + // OpenBMH deviates from the original: supports designated set-piece takers, the enhanced injury tables, and the extended suspension fields. +// DesignatedSlot2 (supported rule profile): a human manager's designated follow-up taker + // (manager record +0xafe) takes the shot if he plays; the shooter quality is + // then his. It works on the caller's stack frame (shooter quality byte). + if (int preset = designated_slot(team, 0xafe, 0xFFE); preset >= 0) { + int saved = last_pick_quality; + int taker = pick_player(team, 2, 0xFFE, report, preset); + if (report.unsupported) return; + if (taker != 0xFFF) { + shooter = taker; + shooter_q = uint8_t(last_pick_quality); + } else { + last_pick_quality = saved; + } + } + last_pick_quality = int16_t((int16_t(last_pick_quality) + shooter_q) / 2); + // Range5(shooter, 0, 0): success if G(0, 14) > limit, limit G(2, 4) or + // 2 when G(0, 4) < quality / 33 (a good shooter). Success means a penalty score + // of 150, i.e. almost certainly a goal. + int limit = game.range(2, 4); + if (shooter == 0xFFF || game.range(0, 4) < int16_t(last_pick_quality) / 33) limit = 2; + penalty_score = game.range(0, 14) > limit ? 150 : 0; + } + if (kind == 1) { + penalty_score = int16_t((distance - 16) * -2 + 50) + shooter_q / 2; + if (distance > 22) distance = uint8_t((distance / 5) * 5); + if (live) shown_distance = distance; + if (live && indoor) distance >>= 1; // the live desk halves it (also in the log) + } + if (kind == 3) penalty_score = assistant_q / 2 + shooter_q / 2; + if (kind == 1 || kind == 3) { + int half = int16_t(keeper_value / 2); + keeper_value = half; + penalty_score = half < penalty_score ? penalty_score - half : 0; + if (deflected) { + int d = game.range(0, 40) - 20; + int low = int8_t(penalty_score & 0xFF); + penalty_score = (penalty_score & ~0xFF) | uint8_t(clamp(d + low, 0, 100)); + } + } + } + state.reality.deflected = deflected; + state.reality.distance = distance; + if (kind == 0) shot_limit = clamp(int16_t(shot - keeper_value + game.range(5, 20)), 4, 21); + // chances per 5 minutes (record +0x1c0, minutes above 89 count as 89) for the human + // managers of both teams, the defending one first + { + const size_t bucket = size_t(std::min(minute, 0x59) / 5); + for (int t : {opp_team, team}) { + const int mgr = state.manager_of(t); + if (mgr >= 0) state.manager_records.at(size_t(mgr) * 0xB0C + 0x1c0 + bucket)++; + } + } + + bool goal; + auto open_play_roll = [&]() { + return keeper_value == 0 || (kind == 0 && game.range(0, 3) != 0 && game.range(0, 20) < shot_limit); + }; + if (kind == 0) goal = open_play_roll(); + else goal = game.range(1, 150) < int16_t(penalty_score) ? true : open_play_roll(); + + // Event log (Matches) and goal bookkeeping. + auto log = [&](int code, int player, int value) { + g.log.push_back(uint16_t(player + code * 0x1000)); + g.log.push_back(uint16_t(team * 0x80 + value)); + }; + if (trace) + std::fprintf(stderr, " chance m%d s%d team %d kind %d goal %d shooter %x assistant %x distance %d\n", m, s, team, kind, + int(goal), shooter, assistant, distance); + log(goal ? 0 : 1, shooter, minute); + log(kind == 0 ? 2 : kind + 6, assistant, distance); + const LiveChanceEvent chance{LiveChanceStage::preview, minute, show_group, m, s, kind, + shooter, assistant, kind == 0 && indoor ? distance >> 1 : distance, + goal, ticker, deflected}; + // Button + description/pause occur before MatchScore writes the new score. + // The ticker's miss switch suppresses both presentation boundaries only. + if (live_chance && live && (goal || live != 2 || button(::bmh::layout::MatchEngine_Side_ExecutableField5) == 0)) + live_chance(chance); + if (goal) { + uint32_t goals = le32(g.desc, 0xc8) + 1; // descriptor goal counter (b6434) + for (int i = 0; i < 4; i++) g.desc.at(0xc8 + i) = uint8_t(goals >> (8 * i)); + // MatchScore in write mode: add the goal to the current score. + if (!g.results.empty()) { + uint8_t& r = g.results.at(m); + if ((r & 0xCC) != 0xCC) r = uint8_t(r + (s == 0 ? 0x10 : 0x01)); + } else { + if (g.cup_results.size() < size_t(g.matches())) g.cup_results.resize(g.matches(), 0); + uint16_t& r = g.cup_results[m]; + if (r != 0xCCCC) { + int home = (r >> 5 & 0x1F) + (s == 0), away = (r & 0x1F) + (s == 1); + r = uint16_t(g.phase * 0x400 + away + home * 0x20); + } + } + // PlayerStatistic: goal for the shooter, assist (open play and set pieces of kind 3). + const int manager = state.manager_of(team); // MatchEngineRuntimeField16 + if (shooter != 0xFFF) player_statistic(state, g.desc.at(0), shooter, manager, last_shooter_slot, 1, minute); + if ((kind == 0 || kind == 3) && assistant != 0xFFF) + player_statistic(state, g.desc.at(0), assistant, manager, last_assist_slot, 2, 0x5a); + } else if (live == 2 && button(::bmh::layout::MatchEngine_Side_ExecutableField5)) { + live = 0; // ticker mode shows misses only if this button is off + } + + // --- live desk after the chance (layout field-layout field) ------------------------------------ + // Text, pictures and pauses are presentation. Random numbers are drawn by the attitude + // update (with the new score) and by two optional animations. + if (live) { + // Source local_38 is replaced by +/-52 after a goal. BallFrameCount + // checks D5 (MatchEngine_Side_ExecutableField3) inside the presentation routine; disabling it must + // still consume the exact same earlier Watcom draws. + if (!reality_played && live_ball && button(::bmh::layout::MatchEngine_Side_ExecutableField3) == 0) + live_ball({minute, show_group, m, goal ? (1 - s * 2) * 52 : ball_position}); + if (show) { + ShowEvent e{Show::Chance}; + e.side = uint8_t(s), e.kind = uint8_t(kind), e.flag = goal; + e.team = int16_t(team), e.player = int16_t(shooter), e.other = int16_t(assistant); + e.a = indoor ? shown_distance >> 1 : shown_distance; // MatchEngine_Minute_ExecutableField4 as shown + e.b = ticker; + if (shooter != 0xFFF) e.text = state.player_name(shooter); + emit(std::move(e)); + } + update_attitude(); + if (report.unsupported) return; + if (buttons.empty()) { + report.fail("live desk needs the button settings (savegame)"); + return; + } + // LiveSetPieceFrames: animated penalty / follow-up / free kick (button MatchEngine_Side_ExecutableField: 1-2 in + // the live match, 3+ also in ticker mode). + const int set_pieces = button(::bmh::layout::MatchEngine_Side_ExecutableField); + if (set_pieces && kind != 0 && (!ticker || set_pieces >= 3)) { + set_piece_animation(kind, shown_distance, 1 - s, show_group, m, minute); // MatchEngineRuntimeField6 = 1 - side + } + // SetPieceAnimation: animated shot on goal (button MatchEngine_Side_ExecutableField2: 1 set pieces, 2 all + // chances, 3 also set pieces in ticker mode, 4 everything); otherwise only a sound. + const int shots = button(::bmh::layout::MatchEngine_Side_ExecutableField2); + bool animate = false; + if (shots) { + if (kind != 0 && !ticker) animate = true; + else if (shots >= 2 && !ticker) animate = true; + else if (shots >= 3 && ticker && kind != 0) animate = true; + else animate = shots >= 4; + } + if (animate) shot_animation(!goal, kind == 2, s, show_group, m, minute); + else if (original_sound) original_sound(goal ? 19 : 20); // EndPhase: local_a0 + 0x13. + if (live_chance) { + auto result = chance; + result.stage = LiveChanceStage::result; + live_chance(result); + } + } +} + +void MatchEngine::penalty_shootout(MatchGroup& g, int m, MinuteReport& report) { + const int pair[2] = {g.fixtures.at(size_t(m) * 2), g.fixtures.at(size_t(m) * 2 + 1)}; + // shown live (team flag 0x80 or the ticker 0x40 of either team, CupTie2 local_10): + // every kick is animated (below); text/header observers draw no randomness. + const bool live = + (state.team_morale.at(size_t(pair[0])) & 0xC0) || (state.team_morale.at(size_t(pair[1])) & 0xC0); + const int group_index = int(&g - groups.data()); + const uint16_t original_score = g.cup_results.at(size_t(m)); + if (live && live_shootout) + live_shootout({LiveShootoutStage::start,0x79,group_index,m,3,0xfff, + int(original_score >> 5 & 31),int(original_score & 31),0,5}); + // PenaltyShootout + int last_side = 3, kicks = 0; + int goals[2] = {0, 0}; + int rounds_left = 5; // local_14 + int of = 5; // local_18: "of 5", 1 in the sudden death (the live text) + const int first = rand.range(0, 1); + const int order[2] = {first, 1 - first}; + uint8_t forced = uint8_t(game.range(0, 1)); // local_28: bit 7 set = results alternate + int taken[2][12] = {}; + int count[2] = {0, 0}; + while (rounds_left != 0 || goals[0] == goals[1]) { + for (int k = 0; k < 2; k++) { + if (k == 0 && goals[0] == 11 && goals[1] == 11) forced |= 0x80; // no end in sight + forced ^= 1; + const int side = order[k]; + const int team = pair[side]; + int player = 0xFFF; + if (team < 138 || team == kNoTeam) { + // a player who has not taken a penalty yet (after 100 tries the list restarts) + int tries = 0; + bool fresh; + do { + player = pick_player(team, 2, 0xFFE, report); + if (report.unsupported) return; + fresh = true; + for (int i = 0; i < count[side]; i++) + if (taken[side][i] == player) fresh = false; + if (++tries == 100) { + if (count[side] == 0) player = 0xFFF; + else count[side] = 0; + tries = 0; + } + } while (player != 0xFFF && !fresh); + } + if (count[side] < 12) taken[side][count[side]++] = player; + last_side = side; + if (live && live_shootout) + live_shootout({LiveShootoutStage::preview,0x79,group_index,m,side,player, + kicks == 0 ? int(original_score >> 5 & 31) : goals[0], + kicks == 0 ? int(original_score & 31) : goals[1], + int(of == 5) + of - rounds_left,of}); + ++kicks; + // Range5: the kick. The quality check uses the shooter of the last real + // chance of the match loop (MatchEngineRuntimeField17) and the quality of the last pick. + int miss_limit = game.range(2, 4); + bool keep = false; + if (state.last_shooter != 0xFFF) { + const int quality = int16_t(last_pick_quality); + keep = quality / 33 <= game.range(0, 4); + } + if (!keep) miss_limit = 2; + bool goal = miss_limit < game.range(0, 14); + if (forced & 0x80) goal = (forced & 0x7F) != 0; + if (live) { + // Range5 live: the follow-up scene LiveSetPieceFrames(2, 0) with MatchEngineRuntimeField6 = + // the other side, then the shot on goal SetPieceAnimation(miss, 1) - always, no + // button decides here + set_piece_animation(2, 0, 1 - side, int(&g - groups.data()), m, 0x79); + shot_animation(!goal, true, side, int(&g - groups.data()), m, 0x79); + } + if (goal) goals[side]++; + if (show) { + show_at(g, m, 0x79); + ShowEvent e{Show::PenaltyKick}; + e.side = uint8_t(side), e.flag = goal, e.kind = live; + e.team = int16_t(team), e.player = int16_t(player); + e.a = goals[0], e.b = goals[1]; + // ". Elfmeter" (LiveMatchday_FormatError_TextPointer4), "of " (LiveMatchday_FormatError_TextPointer5) + e.c = (of == 5) + (of - rounds_left), e.d = of; + if (player != 0xFFF) e.text = state.player_name(player); + emit(std::move(e)); + } + // event log (Matches): the kick and its result + g.log.push_back(uint16_t(player + (goal ? 0 : 1) * 0x1000)); + g.log.push_back(uint16_t(team * 0x80 + 0x79)); + g.log.push_back(uint16_t(0xFFF + 2 * 0x1000)); + g.log.push_back(uint16_t(team * 0x80 + 1)); + const int own = goals[side], other = goals[1 - side]; + if (rounds_left != 0 && (own + rounds_left - 1 < other || rounds_left + other - k < own)) { + rounds_left = 0; // decided before the five rounds are over + break; + } + } + if (rounds_left != 0 && --rounds_left == 0) of = 1; + } + if (show && live) { + show_at(g, m, 0x79); + ShowEvent e{Show::ShootoutEnd}; + e.a = goals[0], e.b = goals[1]; + e.text = message_text(state, ::bmh::layout::LiveMatchday_FormatError_TextPointer6); + emit(std::move(e)); + } + if (live && live_shootout) + live_shootout({LiveShootoutStage::end,0x79,group_index,m,last_side,0xfff, + goals[0],goals[1],0,of}); + // CupTie2: the shoot-out goals are added to the score (at most 29 together) + uint16_t& r = g.cup_results.at(size_t(m)); + int home = goals[0] + (r >> 5 & 0x1F), away = goals[1] + (r & 0x1F); + while (away + home > 0x1D) away--, home--; + home = std::clamp(int(int8_t(home)), 0, 15); + away = std::clamp(int(int8_t(away)), 0, 15); + if (r != 0xCCCC) r = uint16_t(2 * 0x400 + home * 0x20 + away); +} + +} // namespace bmh diff --git a/src/game/match_engine.hpp b/src/game/match_engine.hpp new file mode 100644 index 0000000..97f7937 --- /dev/null +++ b/src/game/match_engine.hpp @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// Minute-by-minute match simulation, port of the match loop EndPhase. +// +// A matchday consists of up to six match groups (one per competition). Every minute the +// original walks all groups, all matches of a group and both sides of a match: +// +// 1. End of match: after the regular time (last_minute) each running match ends with +// probability 1/2 per minute (WatcomRandom), at last_minute + stoppage at the latest. +// At the end of the first half (minute 45 with no stoppage) this also ends the half. +// 2. Per side, event roll: WatcomRandom::range(0, 220) < rhythm - 30 (indoor: +// range(0, 10) > 7) calls the foul/card/injury routine EventImpl. +// 3. Per side, chance roll: GameRandom::range(0, 44 + 4 * away_penalty) must not exceed +// home attitude + away attitude + 3 (+14 indoor). away_penalty is 1 for the away +// side on league matchdays (descriptor flag bit 1), else 0. +// 4. Chance quality from the side records, the opponent's defence and randomness +// decides via the table at layout field whether a real chance arises; then the kind of +// chance (normal, penalty 1/6, free kick 1/7), shooter and assistant (PickTaker), +// the goalkeeper and finally the goal roll. +// +#include +#include +#include +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "game/presentation.hpp" +#include "game/random.hpp" +#include "game/reality_scene.hpp" +#include "game/state.hpp" + +namespace bmh { +struct PhaseResultRequest; + +// One match group (the original's 0xD0-byte descriptor at MatchdayGroupDescriptors + group * 0xD0 plus the +// heap arrays it points to). +struct MatchGroup { + Bytes desc; // raw descriptor, per-match bytes at 0x10/0x30/0x50 + std::vector fixtures; // home, away team id per match (descriptor +0x7c) + std::vector results; // league: home << 4 | away per match (descriptor +0x08) + // Cups have no league result pointer; each match has a u16 instead (descriptor +0x80, + // one array per leg): bits 0-4 away goals, 5-9 home goals, 10-15 phase + // (0 regular time, 1 extra time). 0xCCCC = not played. See MatchScore. + std::vector cup_results; + // Two-legged ties: the other leg (descriptor +0x84, its match order follows this leg). + std::vector cup_other_leg; + // Where the result arrays live in the original (LE addresses, 0 = none): +0x80, +0x84. + uint32_t cup_result_address[2] = {0, 0}; + int phase = 0; // param_4 of EndPhase, stored with cup goals + std::vector records; // 18 bytes per match (descriptor +0x0c) + std::vector end_minute; // minute a match ended (descriptor +0x04) + std::vector spectators; // attendance per match (descriptor +0xb4) + std::vector log; // event log (Matches, descriptor +0x98) + uint32_t ended = 0; // matches ended in the current phase (local_dc) + uint32_t kickoff_void_mask = 0; // local_70: fixtures excluded from all post-match effects + + int matches() const { return int(fixtures.size() / 2); } + uint8_t flags() const { return desc.at(1); } + uint32_t void_mask() const { return le32(desc, 0xb8); } // matches not played (b6424) +}; + +struct MinuteReport { + bool unsupported = false; + std::string reason; // first unsupported path taken + void fail(const std::string& why) { + if (!unsupported) reason = why; + unsupported = true; + } +}; + +// Exact Source event which requests the watched manager's live line-up (PitchScreen). +// The identity is captured after the event has changed the slot, before play resumes. +struct LiveMatchEvent { + size_t group_index = 0; + int match_index = -1; + int side = -1; + int team = -1; + int opponent = -1; + int player = -1; + int kind = -1; // 1 straight red, 2 injury + int minute = 0; // MatchEngine minute is already 1-based; Source receives minute+1. + int manager_slot = -1; +}; + +// BallFrameCount: an already computed Watcom ball position, at the synchronous +// chance presentation boundary. Observers receive no mutable engine references. +struct LiveBallEvent { + int minute = 0; + int group = 0; + int match = 0; + int displacement = 0; // home positive, away negative; a goal uses +/-52 +}; + +enum class LiveChanceStage { preview, result }; +// Read-only Source chance presentation. The preview precedes the score write; +// the result follows the optional shot/set-piece RNG path. Neither hook decides play. +struct LiveChanceEvent { + LiveChanceStage stage = LiveChanceStage::preview; + int minute = 0, group = 0, match = 0, side = 0, kind = 0; + int shooter = 0xfff, assistant = 0xfff, distance = 0; + bool goal = false, ticker = false, deflected = false; +}; + +// SetPieceAnimation/Range4: retain the picture values from the existing +// Watcom draws. A presenter cannot change the shot or draw additional randomness. +struct LiveShotEvent { + int minute = 0, group = 0, match = 0, acting_side = 0; + int lane = 0, height = 0, end_lane = 0, end_height = 0, keeper_delay = 0; + bool miss = false, mirror_sprites = false; +}; + +struct LiveSetPieceDraw { int low = 0, high = 0, value = 0; }; +// An owned observation of the existing LiveSetPieceFrames draws. The UI replays these +// values to reconstruct figures; it has no GameRandom/WatcomRandom reference. +struct LiveSetPieceEvent { + int minute = 0, group = 0, match = 0, source_side = 0, kind = 0, distance = 0; + std::vector draws; +}; + +// EventImpl/SDLPumpEvents presentation, after the card/injury is recorded and before +// substitution decisions. Source kind: 0 yellow, 1 red, 2 injury, 3 second yellow. +struct LiveBookingEvent { + int minute = 0, group = 0, match = 0, side = 0, kind = 0; + int team = -1, player = 0xfff, season_yellows = 0, ban = 0; +}; + +enum class LiveShootoutStage { start, preview, end }; +// CupTie2/PenaltyShootout: header/text before each existing kick and after the lottery. +// Scores are owned presentation values; observers cannot write cup results. +struct LiveShootoutEvent { + LiveShootoutStage stage = LiveShootoutStage::start; + int minute = 0x79, group = 0, match = 0, side = 3, player = 0xfff; + int home_goals = 0, away_goals = 0, round = 0, of = 5; +}; + +// EventImpl(slot,1,side) stores this request in bdb14/16/18 rather than opening +// a screen or substituting during a Reality scene. The scene owner must drain +// it after the scene ends (RealityReporterPanel). No request means those globals stay put. +struct DeferredRealityChange { + bool human = false; + int team = -1; // opponent for a human request, own team for automatic + int slot = -1; // absolute squad slot; Source 0xff for a human request + int mode = -1; // position+20 for automatic; manager index for human +}; +struct ForcedMatchEvent { + uint8_t code = 0; // Source return: yellow=1, straight red=3, second yellow=2; + // bit7 requests the watched human's post-scene screen + std::optional change; +}; + +enum class LiveRealityStage { begin, round, settling, end }; +// Owned Source observation: presentation receives neither RNG nor mutable scene. +// A true round response requests Source's post-animation exit boundary. +struct LiveRealityEvent { + LiveRealityStage stage = LiveRealityStage::begin; + int minute = 0, group = 0, match = 0, side = 0; + RealitySceneTick tick; +}; + +struct MatchEngine { + MatchEngine(GameState& s, std::vector& gr, GameRandom& gm, WatcomRandom& r, std::vector refs) + : state(s), groups(gr), game(gm), rand(r), referees(std::move(refs)), last_pick_quality(s.last_pick_quality) {} + + GameState& state; + std::vector& groups; + GameRandom& game; + WatcomRandom& rand; + std::vector referees; // RefereeProperties, bits 3-4: strictness (from M3D.MAN) + bool indoor = false; // CareerSessionRuntimeField: adds 14 to the chance threshold + bool alternate_event_roll = false; // AlternateEventRoll: alternative event roll range(0, 10) > 7 + bool match_events_disabled = false; // MatchEventsDisabled: disables the foul/event routine + bool live_scene_visible = false; // LiveSceneVisible (live scene enabled) + bool live_desk_disabled = false; // LiveDeskDisabled: no live desk (both live modes off) + int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5, for the climate effect when re-rating + bool trace = false; // print events and chances to stderr (debugging) + // What the original would show (presentation.hpp); filled only when set. Appending + // draws no random numbers and changes nothing else. + std::vector* show = nullptr; + // The substitution screen (PitchScreen) a watched human team gets after a red card or an + // injury when the assistant may not substitute. An installed live_event presenter handles + // that boundary synchronously; leave_screens preserves the legacy headless path. + bool leave_screens = false; + // Synchronous Source presenter for an actual red-card/injury event. While this runs, + // MatchEngine::event and the outer minute loop retain references into `groups`; + // implementations must not replace, resize, reorder, or otherwise invalidate that + // vector or its MatchGroup objects. The supported live scope mutates only match/player + // state and restores group contents in place on abort. Empty keeps the existing + // leave_screens/headless behavior. + std::function live_event; + std::function live_ball; + std::function live_chance; + std::function live_shot; + std::function live_set_piece; + std::function live_booking; + std::function live_shootout; + // Source sound IDs only, emitted at actual presentation boundaries. This + // observer has no access to game/random generators and never decides play. + std::function original_sound; + const LeImage* reality_rules = nullptr; // borrowed executable, stable during minute() + std::function live_reality; + // EndPhase's existing group result barrier, before its single Source ACK. + // A presenter receives owned scores and const context, never either RNG. + std::function&, + const GameState&)> phase_results; + // Button settings of the desk (block LeaguePresentationOptions, 0xb4 bytes, saved in the .FBM and the .EIN + // files); several switch live-match animations that draw random numbers. + std::vector buttons; + int button(uint32_t address) const { + return buttons.empty() ? 0 : buttons.at(address - ::bmh::layout::LeaguePresentationOptions); + } + + // Simulates one minute of the phase [first_minute, last_minute + stoppage]. + MinuteReport minute(int minute, int last_minute, int stoppage); + // CupTie2 for match m of a group whose tie is level after extra time: the + // penalty shoot-out (PenaltyShootout, kicks Range5); the result is stored with + // phase 2. A match shown live (or in the ticker) animates every kick. + void penalty_shootout(MatchGroup& g, int m, MinuteReport& report); + // EndPhase after the line-up or substitution screen the manager opened during his live + // match (RerateTeam / PitchScreen): his side of that match is rated again + // (BuildSideRecords3). The changes themselves are made on the state before. + void rerate_team(int team, MinuteReport& report); + // Real card effects for the selected Reality offender. Mode1 skips the + // injury roll and random slot selection, suppresses booking message boxes, + // and defers changes. `g` must be a stable member of `groups` as for minute(). + ForcedMatchEvent forced_event(MatchGroup& g, int m, int side, int minute, + int absolute_slot, MinuteReport& report); + // Source scene generators shared by live chances and ShotAnimation replay. + // They own the Watcom draws; UI consumers receive immutable observations. + void shot_animation(bool miss, bool follow_up, int acting_side, int group, int match, int minute); // SetPieceAnimation + void set_piece_animation(int kind, int distance, int side, int group, int match, int minute); // LiveSetPieceFrames + +private: + void side(MatchGroup& g, int m, int& side, int minute, int& own_attitude, int& opp_attitude, MinuteReport& report); + void event(MatchGroup& g, int m, int side, int minute, MinuteReport& report); // EventImpl + ForcedMatchEvent event_impl(MatchGroup& g, int m, int side, int minute, + int fixed_slot, MinuteReport& report); + bool substitute(int team, int off, int mode, MinuteReport& report); // Injure + bool injure(int slot, bool match, int manager, MinuteReport& report); // InjurePlayer + void rerate(MatchGroup& g, int m, int side, MinuteReport& report); // BuildSideRecords3 + int pick_player(int team, int mode, int exclude, MinuteReport& report, int preset = -1); // PickTaker + int pick_taker(int team, int mode, int exclude, int kind, MinuteReport& report); // DesignatedSlot + int designated_slot(int team, int offset, int exclude) const; // Emit + // the match the next ShowEvent belongs to (set where a side, an event or a shoot-out + // starts) + int show_group = 0, show_match = 0, show_minute = 0; + void emit(ShowEvent e) { + if (!show) return; + e.group = uint8_t(show_group), e.match = uint8_t(show_match), e.minute = int16_t(show_minute); + show->push_back(std::move(e)); + } + void show_at(const MatchGroup& g, int m, int minute) { + show_group = int(&g - groups.data()), show_match = m, show_minute = minute; + } + int& last_pick_quality; // MatchEngineRuntimeField (a global: GameState::last_pick_quality) + int last_shooter_slot = 0; // MatchEngineRuntimeField2 + int last_assist_slot = 0; // MatchEngineRuntimeField3 + // Stack slot local_1c of PlayerValue as seen from PickTaker (see + // RatingContext::stale_condition): the condition of the last candidate rated with it. + int pick_stack_condition = 0; + // local_84 of EndPhase: quality of the last assistant picked (free kicks use it). + int stale_assistant_quality = 0; + int stale_set_piece_score = 0; // local_9c, retained for Source Reality restart2 + RealityScene reality_runtime; // persistent grid, cue slots and MatchEngine_Minute_ExecutableField during matchday +}; + +} // namespace bmh diff --git a/src/game/matchday.cpp b/src/game/matchday.cpp new file mode 100644 index 0000000..16ab195 --- /dev/null +++ b/src/game/matchday.cpp @@ -0,0 +1,815 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/matchday.hpp" + +#include +#include +#include +#include + +#include "game/cup.hpp" +#include "game/schedule.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/table.hpp" + +namespace bmh { + +namespace { + +// Competition class of each descriptor type (MatchEngineRuntimeField9): 0 league (cards count per +// team), 1-4 cup competitions with their own card counters, 0xFF = none. +constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255, + 4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0}; +// Clubs per league (LeagueSizes): five leagues of 18, four regional leagues of 12. +// (the clubs per league are kLeagueSizes, schedule.hpp) +// Three points for a win in every league (CareerSession_BeginFriendlyOpponentTable_RuntimeField, index 9 = "no league" reads the +// following table byte 18, also non-zero). +constexpr bool kThreePoints[10] = {true, true, true, true, true, true, true, true, true, true}; +constexpr size_t kClubRecord = 0x4a; +constexpr size_t kManagerRecord = 0xB0C; +constexpr size_t kBoard = 0x840, kBoardSlot = 0x58; + +uint32_t rd32(const std::vector& v, size_t o) { + return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(x >> (8 * i)); +} +uint16_t rd16(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16(std::vector& v, size_t o, uint16_t x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} + +int competition_class(int type) { return type >= 0 && type < 24 ? kCompetitionClass[type] : 255; } + +// TeamLeague2: league (0-8) of a club id, 9 for clubs outside the leagues. +int league_of(int team) { + if (team > 0x164) return 0; + int end = 0; + for (int l = 0; l < 9; l++) { + end += kLeagueSizes[l]; + if (team < end) return l; + } + return 9; +} + +// ClubRecord: record result `idx` of a club. The value of a result is +// home * home_weight - away * away_weight; `lower` keeps the smallest instead of the +// largest value. The stored result uses away_weight 1 if it was negative. +void club_record(GameState& g, int club, int idx, int home, int away, bool lower, int home_weight, int away_weight, int opponent) { + size_t base = size_t(club) * kClubRecord; + uint8_t& r = g.club_table.at(base + 0x15 + idx); + int old_value = (r >> 4) * home_weight - (r & 0x0F) * away_weight; + int new_value = home * home_weight - away * away_weight; + if (!lower ? new_value <= old_value : old_value <= new_value) return; + if (away_weight < 0) away_weight = 1; + r = uint8_t((uint8_t(home * home_weight) << 4) + uint8_t(away * away_weight)); + wr16(g.club_table, base + 0x2a + idx * 2, g.club_ids.at(opponent)); + wr16(g.club_table, base + 0x3a + idx * 2, uint16_t(std::min(g.date, 0xFFFF))); +} + +} // namespace + +bool match_score(const MatchGroup& g, int m, int& home, int& away) { + if (!g.results.empty()) { + home = g.results.at(m) >> 4; + away = g.results.at(m) & 0x0F; + return true; + } + if (g.cup_results.size() == size_t(g.matches())) { + home = g.cup_results[m] >> 5 & 0x1F; + away = g.cup_results[m] & 0x1F; + return true; + } + return false; +} + +int sportschau_source_setting_index(const GameState& state, const MatchGroup& group) { + const uint32_t id = le32(group.desc, 0xcc); + if (id <= 0x14) return id < 5 ? int(id) : std::min(int(id) + 12, 0x13); + const uint32_t source = id + 0x18; + return state.memory.has(source) ? int(uint8_t(state.memory.u8(source) + 5)) : -1; +} + +SportschauFixtureView sportschau_fixture_view(const GameState& state, const MatchGroup& group, + int group_index, int fixture_index, + const std::vector& show_events) { + SportschauFixtureView view; + if (group_index < 0 || group_index > 0xff || fixture_index < 0 || fixture_index > 0xff || + size_t(fixture_index * 2 + 1) >= group.fixtures.size()) + return view; + + view.group = uint8_t(group_index); + view.fixture = uint8_t(fixture_index); + view.competition_type = group.desc.at(0); + view.fixture_flags = group.desc.at(1); + view.source_footer_variant = state.indoor ? 2 : ((group.desc.at(1) & 8) != 0 ? 1 : 0); + view.has_replay_progression_mode = state.memory.has(::bmh::layout::ReplayProgressionMode); + if (view.has_replay_progression_mode) view.replay_progression_mode = state.memory.u8(::bmh::layout::ReplayProgressionMode); + view.has_replay_chance_mode = state.memory.has(::bmh::layout::ReplayChanceMode); + if (view.has_replay_chance_mode) view.replay_chance_mode = state.memory.u8(::bmh::layout::ReplayChanceMode); + view.source_selection_available = state.sportschau_selection_available; + view.competition_id = le32(group.desc, 0xcc); + view.source_setting_index = int16_t(sportschau_source_setting_index(state, group)); + view.home_team = int16_t(group.fixtures.at(size_t(fixture_index * 2))); + view.away_team = int16_t(group.fixtures.at(size_t(fixture_index * 2 + 1))); + view.source_selected = view.source_selection_available && sportschau_selected(state, view.home_team); + if (size_t(fixture_index) < group.end_minute.size()) + view.source_played_minute = group.end_minute[size_t(fixture_index)]; + auto as_bytes = [](const std::string& s) { + return std::vector(s.begin(), s.end()); + }; + auto set_team = [&](int team, std::vector& full, std::vector& short_name, + bool& short_name_available, + bool& requires_font_fit, bool& requires_longest_word, uint16_t& badge_word) { + const std::string name = state.club_name(team); + full = as_bytes(name); + if (team >= 0 && size_t(team) * 2 + 1 < state.club_heap_78.size()) + badge_word = uint16_t(state.club_heap_78[size_t(team) * 2] | + uint16_t(state.club_heap_78[size_t(team) * 2 + 1]) << 8); + if (team >= 0 && team < 0xa8) { + requires_font_fit = true; + if (state.memory.has(::bmh::layout::ClubShortNameOffsets + uint32_t(team))) { + const uint8_t source = state.memory.u8(::bmh::layout::ClubShortNameOffsets + uint32_t(team)); + const size_t offset = source >> 4; + const size_t length = (source & 0x0f) + 1; + if (offset <= full.size()) { + short_name_available = true; + const size_t count = std::min(length, full.size() - offset); + short_name.assign(full.begin() + std::ptrdiff_t(offset), + full.begin() + std::ptrdiff_t(offset + count)); + } + } + } else { + short_name = full; + short_name_available = !short_name.empty(); + requires_font_fit = true; + requires_longest_word = true; + } + }; + set_team(view.home_team, view.home_name, view.home_short_name, view.home_short_name_available, + view.home_name_requires_font_fit, view.home_name_requires_longest_word, view.home_badge_word); + set_team(view.away_team, view.away_name, view.away_short_name, view.away_short_name_available, + view.away_name_requires_font_fit, view.away_name_requires_longest_word, view.away_badge_word); + int home = 0, away = 0; + view.score_known = match_score(group, fixture_index, home, away); + if (view.score_known) { + view.home_goals = uint8_t(home); + view.away_goals = uint8_t(away); + } + + uint16_t ordinal = 0; + for (size_t i = 0; i + 1 < group.log.size(); i += 2) { + const uint16_t code_player = group.log[i]; + const uint16_t team_value = group.log[i + 1]; + const int team = team_value >> 7; + if (team != view.home_team && team != view.away_team) continue; + SportschauLogEvent event; + event.group = view.group; + event.fixture = view.fixture; + event.event_ordinal = ordinal++; + event.source_word_index = uint16_t(i); + event.source_code_player_word = code_player; + event.source_team_value_word = team_value; + event.source_code = uint8_t(code_player >> 12); + event.player_id = uint16_t(code_player & 0x0fff); + event.team_id = int16_t(team); + event.source_value = uint8_t(team_value & 0x7f); + event.consumes_following_pair = event.source_code == 0 || event.source_code == 1; + event.has_following_word = i + 2 < group.log.size(); + event.has_following_pair = i + 3 < group.log.size(); + if (event.has_following_word) { + event.following_code_player_word = group.log[i + 2]; + const int player = event.following_code_player_word & 0x0fff; + if (player != 0x0fff) event.following_player_name = as_bytes(state.player_name(player)); + } + if (event.has_following_pair) event.following_team_value_word = group.log[i + 3]; + if (event.player_id != 0x0fff) event.player_name = as_bytes(state.player_name(event.player_id)); + view.log_events.push_back(std::move(event)); + } + + for (const ShowEvent& event : show_events) + if (event.group == view.group && event.match == view.fixture) view.show_events.push_back(event); + return view; +} + +bool book_money(GameState& g, int manager, int32_t amount, bool force, bool statistics) { + if (g.level == 0) return true; + size_t rec = size_t(manager) * kManagerRecord; + const uint32_t balance = rd32(g.manager_records, rec + 0x314); + const uint32_t credit = rd32(g.manager_records, rec + 0x31c); + // BookMoney2 adds the Native dwords before a signed comparison and subtracts + // the amount in the same 32-bit register width. Preserve that wrap without + // C++ signed-overflow undefined behavior at the account limits. + if (!force && amount >= 0 && std::bit_cast(balance + credit) < amount) return false; + wr32(g.manager_records, rec + 0x314, balance - uint32_t(amount)); + if (statistics) { + if (amount < 0) + wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) - uint32_t(amount)); + else + wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + uint32_t(amount)); + } + return true; +} + +uint32_t pay_bonus(GameState& g, int manager, int board_slot, int index, bool pay) { + size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + uint32_t rate = g.tactics.at(slot + 0x12 + index); + if (rate == 0) return 0; + uint32_t factor = index > 2 ? 5 : 1; + uint32_t amount = factor * (rate * rd32(g.tactics, slot + 0x50)) / 100; + if (pay) { + size_t rec = size_t(manager) * kManagerRecord; + uint32_t tax = g.manager_records.at(rec + 0x172); + if (tax != 0) amount -= ((tax >> 5 & 7) + 3) * amount * 10 / 100; + book_money(g, manager, int32_t(amount), true); + wr32(g.manager_records, rec + 0x334, rd32(g.manager_records, rec + 0x334) + amount); + } + return amount; +} + +void player_statistic(GameState& g, int type, int player, int manager, int slot, int kind, int minute) { + int cls = (type == 0xb && manager >= 0 && !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam) + ? 3 + : int8_t(competition_class(type)); + if (cls < 0 || cls >= 4) return; + Player& p = g.players.at(player); + const uint32_t w364 = p.w364; + const size_t board = manager >= 0 ? size_t(manager) * kBoard + size_t(slot) * kBoardSlot : 0; + if (kind == 0) { // appearance + if (cls == 3 && (g.player_bonus.at(player) & 0x7F) < 0x7F) g.player_bonus.at(player)++; + if (manager >= 0) { + pay_bonus(g, manager, slot, 2, true); + if (cls < 3) g.tactics.at(board + 7 + cls)++; + wr16(g.tactics, board + 0x48, uint16_t(rd16(g.tactics, board + 0x48) + 1)); + } + if (cls == 0) p.w364 = (w364 & 0x03FFFFFFu) | ((w364 >> 26) + 1) << 26; // league games + } else if (kind == 1) { // goal + if (manager >= 0) { + pay_bonus(g, manager, slot, 0, true); + wr16(g.tactics, board + 0x4a, uint16_t(rd16(g.tactics, board + 0x4a) + 1)); + if (cls == 0) g.manager_records.at(size_t(manager) * kManagerRecord + 0x1ae + std::min(minute, 89) / 5)++; + } + // league goals in bits 2-7 (a 64th goal carries into bit 8, as in the original) + if (cls == 0) p.w364 = (w364 & 0xFFFFFF03u) | ((((w364 >> 2) & 0x3F) << 2) + 4); + } else if (kind == 2) { // assist + if (manager >= 0) wr16(g.tactics, board + 0x4c, uint16_t(rd16(g.tactics, board + 0x4c) + 1)); + if (cls == 0) p.w368 = (p.w368 & 0xFF03FFFFu) | ((((p.w368 >> 18) & 0x3F) + 1) << 18); + } +} + +void finish_match(GameState& g, MatchGroup& grp, int m, int minute, GameRandom& game) { + if (grp.end_minute.at(m) == 0) grp.end_minute.at(m) = uint8_t(minute); + for (int side = 0; side < 2; side++) { + int manager = g.manager_of(grp.fixtures.at(m * 2 + side)); + if (manager < 0) continue; + int home = 0, away = 0; + match_score(grp, m, home, away); + int own = side ? away : home, opp = side ? home : away; + int points = 0; + if (own == opp) points = 1; + if (int8_t(own) > int8_t(opp)) points = 2; + for (int slot = 0; slot < 24; slot++) { + size_t at = size_t(manager) * kBoard + size_t(slot) * kBoardSlot; + int start = int8_t(g.tactics.at(at + 0x10)); // minute the player came on + for (int i = 0; i < points; i++) pay_bonus(g, manager, slot, 1, true); + if (start >= 126) continue; + // Getting used to the place: a quarter of the minutes played (half in the + // competitions 5 and 7), at most 99. + int8_t delta = int8_t((minute - start) / 4); + if (grp.desc.at(0) == 5 || grp.desc.at(0) == 7) delta = int8_t(delta / 2); + if (g.indoor) start = int8_t(start) >> 2; + int used = int8_t(g.tactics.at(at + 0xf)) + delta; + g.tactics.at(at + 0xf) = uint8_t(std::clamp(used, 0, 99)); + // The player's own place (bytes 0/1) moves one step towards the board place. + if (game.range(0, 90) < minute - start) { + for (int k = 0; k < 2; k++) { + uint8_t& cur = g.tactics.at(at + k); + uint8_t target = g.tactics.at(at + 0x41 + k); + if (cur < target) cur++; + if (cur > target) cur--; + } + } + } + } +} + +void update_club_table(GameState& g, int home, int away, int hg, int ag) { + if (g.indoor || g.club_table.empty()) return; + const size_t H = size_t(home) * kClubRecord, A = size_t(away) * kClubRecord; + auto add16 = [&](size_t o, int v) { wr16(g.club_table, o, uint16_t(rd16(g.club_table, o) + v)); }; + // Only the first league and the regional leagues keep points in this table (the + // condition tests the home club only). + const bool league = home < kLeagueSizes[0] || (home >= 90 && home < 138); + const int win_points = kThreePoints[league_of(home)] ? 3 : 2; + if (league) { + add16(H + 0x20, hg); + add16(H + 0x22, ag); + add16(A + 0x20, ag); + add16(A + 0x22, hg); + } + uint8_t h[21], a[21]; // streaks: t * 3 + (0 all, 1 home, 2 away) + std::copy_n(g.club_table.begin() + H, 21, h); + std::copy_n(g.club_table.begin() + A, 21, a); + club_record(g, home, 2, hg, ag, false, 1, 0, away); // most goals scored at home + club_record(g, away, 7, hg, ag, false, 1, 0, home); // most goals conceded away + club_record(g, home, 3, hg, ag, false, 0, -1, away); // most goals conceded at home + club_record(g, away, 6, hg, ag, false, 0, -1, home); // most goals scored away + auto bump = [](uint8_t* s, int t, int j) { s[t * 3 + j]++, s[t * 3]++; }; + auto clear = [](uint8_t* s, int t, int j) { s[t * 3 + j] = 0, s[t * 3] = 0; }; + // streak 5: without conceding, 6: without scoring + if (ag == 0) bump(h, 5, 1), bump(a, 6, 2); + else clear(h, 5, 1), clear(a, 6, 2); + if (hg == 0) bump(h, 6, 1), bump(a, 5, 2); + else clear(h, 6, 1), clear(a, 5, 2); + if (ag < hg) { // home win + if (league) { + add16(H + 0x1e, win_points); + add16(H + 0x24, 1); + add16(A + 0x28, 1); + } + bump(h, 0, 1); + for (int t = 1; t < 4; t++) clear(h, t, 1); + club_record(g, home, 0, hg, ag, false, 1, 1, away); // biggest home win + club_record(g, away, 5, hg, ag, false, 1, 1, home); // biggest away defeat + bump(h, 4, 1); + clear(a, 0, 2), clear(a, 2, 2), clear(a, 4, 2); + bump(a, 1, 2), bump(a, 3, 2); + } else if (hg == ag) { // draw + if (league) { + add16(H + 0x1e, 1); + add16(A + 0x1e, 1); + add16(H + 0x26, 1); + add16(A + 0x26, 1); + } + clear(h, 0, 1), clear(h, 1, 1); + for (int t = 2; t < 5; t++) bump(h, t, 1); + clear(a, 0, 2), clear(a, 1, 2); + for (int t = 2; t < 5; t++) bump(a, t, 2); + } else { // away win + if (league) { + add16(A + 0x1e, win_points); + add16(H + 0x28, 1); + add16(A + 0x24, 1); + } + bump(a, 0, 2); + for (int t = 1; t < 4; t++) clear(a, t, 2); + clear(h, 0, 1), clear(h, 2, 1), clear(h, 4, 1); + bump(a, 4, 2); + bump(h, 1, 1), bump(h, 3, 1); + club_record(g, home, 1, hg, ag, true, 1, 1, away); // biggest home defeat + club_record(g, away, 4, hg, ag, true, 1, 1, home); // biggest away win + } + std::copy_n(h, 21, g.club_table.begin() + H); + std::copy_n(a, 21, g.club_table.begin() + A); + // Human managers keep their club's best streaks (manager record +0x5e). + for (int side = 0; side < 2; side++) { + int club = side ? away : home; + const uint8_t* s = side ? a : h; + for (size_t k = 0; k < g.manager_teams.size(); k++) { + if (g.manager_teams[k] != club) continue; + for (int i = 0; i < 21; i++) { + uint8_t& best = g.manager_records.at(k * kManagerRecord + 0x5e + i); + if (best < s[i]) best = s[i]; + } + } + } +} + +void update_morale(GameState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand) { + uint8_t& morale = g.team_morale.at(team); + const int value = morale & 0x3F; + int sign = 1; + int diff = int16_t(side + (own_goals - opp_goals) + (5 - value / 5)); + int step = std::abs(25 - value) / 5; + if (diff < 0 || (diff == 0 && value > 25)) { + sign = -1; + diff = -diff; + } + // Far from the middle (25) morale moves slowly towards the extremes. + if ((sign == 1 && value > 12) || (sign == -1 && value < 37)) step = 5 - step; + if (int16_t(step) == 0) step = 1; + diff = std::clamp(diff, 1, 3); + int range = int16_t(step * diff); + if (range > 12) range = 12; + if (range == 0) return; + int v = int16_t(value + sign * int16_t(rand.range(1, range))); + v = std::clamp(v, 0, 0x2f); + morale = uint8_t(v | (morale & 0xC0)); +} + +void develop_players(GameState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand) { + const int type = grp.desc.at(0); + for (int side = 0; side < 2; side++) { + const int team = grp.fixtures.at(m * 2 + side); + if (!(team < 168 || team == kNoTeam)) continue; + const uint8_t cls = (type == 0xb && team == kNoTeam) ? 3 : uint8_t(competition_class(type)); + const int manager = g.manager_of(team); + const SquadRange range = squad_range(team); + + // 1 in 11: the team gets the next trend of the rotation (none/down, neutral, up); + // the rotation is steered by the balance of all attribute changes so far. + if (game.range(0, 10) == 0) { + if (g.development_balance < -50) g.trend_rotation = 2; + if (g.development_balance > 50) g.trend_rotation = 0; + uint16_t& f = g.team_flags.at(team); + f = uint16_t(((f & 0xFFF8) + g.trend_rotation * 2) & 0xFFFF); + if (++g.trend_rotation == 3) g.trend_rotation = 0; + } + const int8_t trend = int8_t(((g.team_flags.at(team) >> 1) & 3) - 1); + int capped = 0; // local_30: attributes that hit 99 (carries over between players) + + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0x0FFF; + if (player == 0xFFF) break; + Player& p = g.players.at(player); + const int odds = manager >= 0 ? 6 : 3; + + if (trend != 0 && game.range(0, 3) == 0) { + int8_t d = trend; + if (rand.range(0, 4) == 0) d = int8_t(-trend); + // form (shift 0, kept within 35-65), technique (7), condition (14) + uint32_t w = p.w35c; + for (int sh = 0; sh < 15; sh += 7) { + if (sh >= 7 && capped == 0 && game.range(0, odds) != 0) continue; + const int8_t old = int8_t((w >> sh) & 0x7F); + int8_t v = int8_t(old + d); + if (capped != 0 || game.range(0, 1) != 0) v = int8_t(v + d); + if (sh != 0) { + if (v < 0) v = 0; + if (v > 99) { + // Quirk of the original: the first attribute to pass 99 restarts + // the loop - 99 is written to the form and technique and + // condition are processed (again). + if (capped == 0) sh = 0; + v = 99; + capped++; + } else if (capped != 0) { + capped--; + } + } else { + v = int8_t(std::clamp(v, 0x23, 0x41)); + } + if (sh != 0) g.development_balance += v - old; + w = (w & ~(0x7Fu << sh)) + (uint32_t(int32_t(v)) << sh); + } + p.w35c = w; + // the seven skills follow the team trend (1 in 9 each) + uint32_t k = p.w368; + for (int sh = 0; sh < 13; sh += 2) { + if (game.range(0, 8) != 0) continue; + int v = int((p.w368 >> sh) & 3) + trend; + v = std::clamp(v, 0, 3); + k = (k & ~(3u << sh)) + (uint32_t(v) << sh); + } + p.w368 = k; + } + if (p.w364 & 0x1000) // played in this match + player_statistic(g, type, player, manager, int(s - range.first), 0, 0x5a); + if (p.w35c >> 27) continue; // injured players are handled elsewhere + + if (cls != 0xFF) { + const int duration = (p.w364 >> 16) & 0xF; + if (duration != 0 && !(p.w364 & 0x100000)) { + // injury (not a ban) heals by one match; in cups the card counter restarts + if (cls != 0) { + if (p.w368 >> 24 & 1) p.w368 &= 0xF8FFFFFFu; + else p.w368 = (p.w368 & 0xF8FC3FFFu) | 0x4000u; + } + p.w364 = (p.w364 & 0xFFE0FFFFu) | uint32_t(duration - 1) << 16; + } else if (cls == 0) { + // league: every fifth yellow card (booked in this match) bans for one match + int yellow = (p.w368 >> 14) & 0xF; + if ((g.squad_slots.at(s) & 0x1000) && yellow > 4 && yellow % 5 == 0) p.w364 |= 0x10000u; + } + } + g.squad_slots.at(s) &= 0xCFFF; // clear the booked/substituted slot flags + if (cls == 0) continue; + + // Cups: move the card counters of this competition into the player's card word + // and load those of the next competition (the w368 card bits are shared). + if (p.w368 >> 24 & 1) p.w368 |= 0xC000u; + uint16_t& cards = g.player_cards.at(player); + switch (cls) { + case 1: p.w364 = (p.w364 & 0xFFFFFCFFu) | ((p.w368 >> 14) & 3) << 8; break; + case 2: p.w364 = (p.w364 & 0xFFFFF3FFu) | ((p.w368 >> 14) & 3) << 10; break; + case 3: cards = uint16_t((cards & 0x3FFF) | (p.w368 & 0xC000)); break; + case 4: cards = uint16_t((cards & 0xCFFF) | ((p.w368 >> 14) & 3) << 12); break; + default: break; + } + p.w368 = (p.w368 & 0xF8FC3FFFu) | uint32_t((cards >> 5) & 0xF) << 14 | uint32_t((cards >> 9) & 7) << 24; + if (p.w35c >> 27 == 0) p.w364 = (p.w364 & 0xFFE0FFFFu) | ((p.w364 >> 13) & 7) << 16; + } + } +} + +void process_group(GameState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay) { + auto owned = grp; + process_group(g, owned, game, rand, report, group_index, sportschau, show_events, replay, nullptr); +} + +void process_group(GameState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay, + const SportschauRatingTables* ratings) { + const int type = grp.desc.at(0); + auto store_awards = [&] { + if (group_index < 0 || group_index >= 6) return; + const uint32_t base = ::bmh::layout::MatchdayGroupDescriptors + uint32_t(group_index) * 0xd0; + for (size_t i = 0; i < 11; ++i) { + if (g.memory.has(base + 0x70 + uint32_t(i))) + g.memory.set8(base + 0x70 + uint32_t(i), grp.desc.at(0x70 + i)); + if (g.memory.has(base + 0x9c + uint32_t(i * 2 + 1))) + g.memory.set16(base + 0x9c + uint32_t(i * 2), le16(grp.desc, 0x9c + i * 2)); + } + }; + if (ratings) { + // FinishEvent/BuildSideRecords reset eleven score bytes, retaining old slot ids. + std::fill_n(grp.desc.begin() + 0x70, 11, uint8_t(0)); + store_awards(); + } + // The original walks the fixtures with a pointer (puVar2) that only moves on in the + // morale step of a played match. After a match that was not played, the club records and + // the morale of every following match are therefore booked on the teams of the match + // before it (the player development and the manager records use the match index). + size_t cursor = 0; + for (int m = 0; m < grp.matches(); m++) { + // The original keeps local_70 (kickoff_void_mask) separately from the descriptor: + // desc+0xb8 also gains ended-match bits as the minute loop runs. Its fixture pointer + // advances only for played matches, so a void fixture must not advance `cursor`. + if (grp.kickoff_void_mask & (1u << m)) continue; + // A postponed league match can also retain its 0xCD result byte. + if (!grp.results.empty() && (grp.results.at(size_t(m)) & 0xCC) == 0xCC) continue; + int home = 0, away = 0; + if (!match_score(grp, m, home, away)) { + report.fail("matchday processing needs the score"); + return; + } + const int ht = grp.fixtures.at(cursor), at = grp.fixtures.at(cursor + 1); + cursor += 2; + if (type == 0 || type == 10) update_club_table(g, ht, at, home, away); + // MatchdayIntro sits between table updates and morale. Core owns its enabled + // replay scene draws; the old fixture callback remains a pure observer. + if ((sportschau || replay || ratings) && group_index >= 0) { + const auto view = sportschau_fixture_view(g, grp, group_index, m, + show_events ? *show_events : std::vector{}); + if (replay) present_sportschau_replay(g, grp, view, game, rand, *replay); + if (ratings) { rate_sportschau_players(g, grp, view, rand, *ratings); store_awards(); } + if (sportschau) sportschau(g, view); + } + update_morale(g, ht, home, away, 0, rand); + update_morale(g, at, away, home, 1, rand); + manager_match_record(g, grp, m, home, away, report); + if (report.unsupported) return; + develop_players(g, grp, m, game, rand); + } +} + +void stir_random(GameRandom& game, WatcomRandom& rand) { + int n = int16_t(rand.range(100, 300)); + for (int i = 0; i < n; i++) game.range(0, 1); +} + +bool league_screen_shown(const std::vector& buttons, int param_1, int param_2, int league) { + if (param_2 == 0 || param_2 >= 200) return true; // called from the desk: always shown + int kind = param_1 - 1; + if (param_1 == 2 && (param_2 == 90 || param_2 == 120)) kind = 2; + int row = league; + if (league > 4) row = std::min(league + 12, 19); + if (param_2 == 45 && kind == 0) return false; + return buttons.at(size_t(kind + row * 9)) == 0; +} + + +int table_position(const GameState& g, int team) { + if (team >= 138) return 2; + int league = league_of(team); + int rounds = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0; + if (rounds == 0) return -1; + unsigned u = unsigned(rounds - 1); + int word = int16_t(rd16(g.position_history, (size_t(u / 3) + size_t(team) * 13) * 2)); + return (word >> ((u % 3) * 5)) & 0x1F; +} + +void rate_manager(GameState& g, int manager, int rating, int competition) { + uint8_t* hist = g.manager_ratings.data() + size_t(competition) * 10 + size_t(manager) * 0x3c; + std::copy_backward(hist, hist + 9, hist + 10); // Int16T: shift the last 9 up + hist[0] = uint8_t(rating); + int sum = 0; + for (int s = 0; s < 10; s++) sum = int16_t(sum + ((100 - 10 * s) * hist[s]) / 100); + wr16(g.manager_records, size_t(manager) * kManagerRecord + 0x8aa + size_t(competition) * 2, uint16_t(sum)); +} + +void manager_match_record(GameState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report) { + const int type = grp.desc.at(0); + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const size_t rec = k * kManagerRecord; + int side = -1, opponent = 0; + for (int s = 0; s < 2; s++) + if (g.manager_teams[k] == grp.fixtures.at(m * 2 + s)) { + side = s; + opponent = grp.fixtures.at(m * 2 + 1 - s); + break; + } + if (side < 0) continue; + // opponent id as the original keeps it: its low byte (0xFE for ids >= 256) + const int opp = opponent < 0x100 ? opponent : 0xFE; + // last results (home | away << 4) and fixtures, newest first + std::copy_backward(g.manager_records.begin() + rec + 0x212, g.manager_records.begin() + rec + 0x217, + g.manager_records.begin() + rec + 0x218); + std::copy_backward(g.manager_records.begin() + rec + 0x292, g.manager_records.begin() + rec + 0x2a6, + g.manager_records.begin() + rec + 0x2aa); + g.manager_records.at(rec + 0x212) = uint8_t(home_goals + (away_goals << 4)); + for (int i = 0; i < 2; i++) wr16(g.manager_records, rec + 0x292 + i * 2, uint16_t(grp.fixtures.at(m * 2 + i))); + int own = side ? away_goals : home_goals, against = side ? home_goals : away_goals; + int rating = side ? 110 : 90; // an away game counts more + if (uint8_t(own) > uint8_t(against)) { + // league win bonus from the sponsor (record +0x173 thousands, less for + // higher +0x210 levels) + int bonus = g.manager_records.at(rec + 0x173); + if (type == 0 && bonus != 0) { + int level = g.manager_records.at(rec + 0x210); + if (level > 2) level--; + int32_t amount = (4 - level) * bonus * 1000; + if (g.level != 0) { + wr32(g.manager_records, rec + 0x314, rd32(g.manager_records, rec + 0x314) + uint32_t(amount)); + wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) + uint32_t(amount)); + } + } + rating += 20; + } + if (uint8_t(own) < uint8_t(against)) rating -= 20; + // MatchdayRuntimeField (u16 every 4 bytes): competitions that rate the manager. A league match + // counts the table place; a cup match its weight plus twice the rounds played in the + // stage and in every earlier one (link +0x15). All go into the league history (0). + static const uint16_t kRatingWeight[14] = {1, 12, 16, 20, 18, 0, 0, 0, 0, 14, 1, 0, 12, 10}; + const uint16_t weight = type < 14 ? kRatingWeight[type] : 0; + if (weight != 0) { + if (type != 0) { + int add = weight; + uint32_t e = le32(grp.desc, 0xcc); + for (int guard = 0; guard < 64; guard++) { + add += g.memory.u8(e + 0x1d) * 2; + const int8_t previous = int8_t(g.memory.u8(e + 0x15)); + if (previous == -1) break; + e = cup_entry_address(previous); + } + rating += int16_t(add); + } else { + int league = league_of(g.manager_teams[k]); + int size = league < 9 ? kLeagueSizes[league] : 0; + rating += (size - table_position(g, g.manager_teams[k])) * 4; + } + rating = std::clamp(int16_t(rating), int16_t(0), int16_t(200)); + rate_manager(g, int(k), rating, 0); + } + if (opp < 0xa8) { + size_t at = k * 0x690 + size_t(opp) * 10 + (side == 1 ? 5 : 0); + std::copy_backward(g.manager_results.begin() + at, g.manager_results.begin() + at + 4, + g.manager_results.begin() + at + 5); + g.manager_results.at(at) = uint8_t(own + (against << 4)); + } + } +} + + +// TicketPriceDraws: per human manager on a first league matchday. It once let the three +// ticket prices drift; in this version its stores were turned into comparisons (CMP +// instead of MOV), so only the random numbers remain. +void ticket_price_draws(const GameState& g, int manager, WatcomRandom& rand) { + uint8_t step[0x2c]; + int b = 4; + for (int i = 0; i < 0x2c; i++) { + step[i] = uint8_t(b); + if (b != 0 && rand.range(0, 8) == 0) b--; + } + (void)g; + (void)manager; + const int round = g.league_rounds.empty() ? 0 : g.league_rounds[0]; + for (int i = 0; i < 3; i++) { + // the direction terms depend on the prices, but only as values, not as draw counts + if (rand.range(0, 4) == 0) rand.range(0, 2); + rand.range(0, 30); + rand.range(0, 2); + if (rand.range(0, 4) == 0) rand.range(0, 2); + if (rand.range(0, 3) != 0) rand.range(1, 18); + rand.range(1, step[round < 0x2c ? round : 0x2b]); + } +} + +// ManagerOf(manager, 0, value): the manager's position of this season. +static void store_season_position(GameState& g, int manager, int value) { + int season = std::min(g.season, 0x31); + g.manager_records.at(size_t(manager) * kManagerRecord + 0xda + size_t(season) * 3) = uint8_t(value); +} + +// StoreStrengthHistory: strength and position history of a human manager's club (38 entries). +static void store_strength_history(GameState& g, int manager) { + const size_t rec = size_t(manager) * kManagerRecord; + const int team = g.manager_teams.at(manager); + int n = g.manager_records.at(rec + 0x284); + if (n < 0x26) { + g.manager_records.at(rec + 0x284) = uint8_t(n + 1); + } else { + std::copy(g.manager_records.begin() + rec + 0x223, g.manager_records.begin() + rec + 0x248, + g.manager_records.begin() + rec + 0x222); + std::copy(g.manager_records.begin() + rec + 0x249, g.manager_records.begin() + rec + 0x26e, + g.manager_records.begin() + rec + 0x248); + n = 0x25; + } + g.manager_records.at(rec + 0x222 + n) = uint8_t(team_average(g, team, 0xFF).value); + int pos = table_position(g, team); + if (pos == -1) pos = (kLeagueSizes[g.manager_records.at(rec + 0x210)] - 1) >> 1; + g.manager_records.at(rec + 0x248 + n) = uint8_t(pos); +} + +void advance_league_rounds(GameState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report, + const CompetitionWinnerHook& winner) { + // CalendarFirstLeague / CalendarLeagueCounts: first league and league count of competition bits 0-7 + const uint8_t* kFirst = kGroupLeague; // (schedule.hpp: the groups of the loaded game) + const uint8_t* kCount = kGroupLeagues; + for (int bit = 0; bit < 19; bit++) { + if (!(competitions >> bit & 1)) continue; + if (bit >= 5) { + report.fail("cup round bookkeeping (AdvanceCup)"); + return; + } + const int end = bit < 4 ? bit + 1 : 8; + for (int c = bit; c < end; c++) { + for (int league = kFirst[c]; league < kFirst[c] + kCount[c]; league++) { + if (league == 0) { + for (size_t m = 0; m < g.manager_teams.size(); m++) { + ticket_price_draws(g, int(m), rand); + const size_t rec = m * kManagerRecord; + if (g.league_rounds.at(0) == 0x10) wr32(g.manager_records, rec + 0x320, rd32(g.manager_records, rec + 0x308)); + uint8_t& d = g.manager_records.at(rec + 0x220); // point deduction countdown + if (d >> 5 == 1) d = (d & 0x1F) < 2 ? 0 : uint8_t((d & 0xE0) | ((d & 0x1F) - 1)); + } + } + const int round = g.league_rounds.at(league); + g.league_rounds.at(league) = uint8_t(round + 1); + LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, kThreePoints[league] ? 1 : 0); + const int first = league_first_team(league); + for (int i = 0; i < t.size; i++) { + const int team = first + i; + const int rank = t.rank(i); + size_t at = (size_t(round / 3) + size_t(team) * 13) * 2; + wr16(g.position_history, at, uint16_t(rd16(g.position_history, at) | rank << ((round % 3) * 5))); + const int manager = g.manager_of(team); + if (manager >= 0) { + int base = first; + if (league_first_team(3) <= base) base -= 18; + store_season_position(g, manager, base + rank + 1); + store_strength_history(g, manager); + } + } + // OnceSecondDivisionLeagueHasPlayedAll, once the second division (league 2) has played all its rounds + // (in the last competition of the loop, after each of its leagues): the + // clubs placed 1-2 in leagues 2 and 3 (TablePosition, positions counted from 0) + // go into the team list of the promotion play-off (Teams), its results + // (MatchdayGroupWorkspace) are cleared and competition MatchdayRuntimeField2 (0xd) starts + if (c + 1 == end && g.league_rounds.at(2) == league_matchdays(2)) { + uint32_t n = 0; + for (int l = 2; l < 4; l++) + for (int team = league_first_team(l); team < league_first_team(l) + kLeagueSizes[l]; team++) { + const uint8_t pos = uint8_t(table_position(g, team)); + if (pos != 0 && pos < 3) g.memory.set16(::bmh::layout::Teams + n++ * 2, uint16_t(team)); + } + for (uint32_t i = 0; i < 0x20; i++) g.memory.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc); + for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xd) + if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == 0xd) break; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, 0xd); + break; + } + } + } + // the first division is over: its leader (OnTableJust(0, 0) on the table just + // computed) is champion - the winner screen (CompetitionWinnerScreen(0, 0), clears + // CareerSession_BeginFriendlyOpponentTable_ExecutableField2), the list of title holders (ListTitleHoldersAf(club, 0)), a human + // champion's record (+0x8a4) and Cup_AdvanceCup_RuntimeField6 + if (league == 0 && g.league_rounds.at(0) == league_matchdays(0)) { + int champion = -1; + for (int i = 0; i < t.size && champion < 0; i++) + if (t.rank(i) == 0) champion = first + i; + if (champion < 0) champion = 0; // (OnTableJust returns 0 when none is found) + if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner) + winner(g, {0, uint16_t(champion)}); + if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) g.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0); + g.memory.set16(::bmh::layout::Titles + uint32_t(std::min(g.season, 0x31)) * 2, uint16_t(champion)); + const int manager = g.manager_of(champion); + if (manager >= 0) { + const size_t at = size_t(manager) * kManagerRecord + 0x8a4; + wr16(g.manager_records, at, uint16_t(rd16(g.manager_records, at) + 1)); + } + g.memory.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, uint16_t(champion)); + } + } + } + } +} + +} // namespace bmh diff --git a/src/game/matchday.hpp b/src/game/matchday.hpp new file mode 100644 index 0000000..8be42b0 --- /dev/null +++ b/src/game/matchday.hpp @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// What happens to a matchday after the final whistle (BMH.exe V2.24 + supported rule profile patch). +// +// The matchday driver (the function around 0x39xxx that calls EndPhase for every +// phase) continues after the last phase with, per match group and match: +// 1. UpdateClubTable league record of both clubs (points, goals, streaks, records) +// 2. morale both teams' morale moves towards the result (Watcom rand) +// 3. ManagerMatchRecord a human manager's match record, bonuses and rating +// 4. DevelopPlayers player development: team trends move form/technique/condition and +// skills (game RNG), appearances, injuries heal by one matchday, +// yellow card bans, card counters per competition +// Before that, the end of every phase calls FinishMatch per match: it stores the end +// minute and lets a human manager's players get used to their places on the tactics +// board and earn their bonus (game RNG). + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/state.hpp" + +namespace bmh { + +// Score of match m of a group (MatchScore, read mode): league result byte or the cup +// result of the current leg. Returns false if the score is not known. +bool match_score(const MatchGroup& g, int m, int& home, int& away); + +// BookMoney2: books `amount` from a human manager's account (record +0x314). Without +// `force` a payment larger than balance + credit (+0x31c) is refused (the original shows a +// message). Game level 0 has no money at all. +// With `statistics` (the caller sets FinanceStatisticsEnabled) the amount is also added to the +// income (+0x874, negative amounts) or expense (+0x8a0) statistics. +bool book_money(GameState& g, int manager, int32_t amount, bool force, bool statistics = false); + +// PayBonus: bonus of one player on the tactics board: the board's bonus rate for +// `index` (slot byte 0x12 + index: 0 goal, 1 point, 2 appearance, ...) times the player's +// bonus base (slot +0x50) / 100, five-fold for index > 2. With `pay` the tax (record +// +0x172) is deducted and the amount is paid. Returns the amount. +uint32_t pay_bonus(GameState& g, int manager, int board_slot, int index, bool pay); + +// PlayerStatistic: statistics of one player. kind 0 appearance, 1 goal, 2 assist. +// competition_type = descriptor byte 0; `manager` = human manager of the player's team +// or -1; `slot` = the player's slot relative to the squad start (tactics board index). +void player_statistic(GameState& g, int competition_type, int player, int manager, int slot, int kind, int minute); + +// FinishMatch for match m at the end of a phase lasting `minute` minutes. +void finish_match(GameState& g, MatchGroup& grp, int m, int minute, GameRandom& game); + +// UpdateClubTable: league record of home and away club after a result. +void update_club_table(GameState& g, int home, int away, int home_goals, int away_goals); + +// Morale step of the matchday driver for one side (0 home, 1 away) of a finished match. +void update_morale(GameState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand); + +// DevelopPlayers: player development and bookkeeping for both teams of match m. +void develop_players(GameState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand); + +// Steps 1, 2 and 4 for every match of a group that was played (voided matches, e.g. +// awarded 0:2, are skipped). Human records and bonuses use manager_match_record. +void process_group(GameState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index = -1, const SportschauFixtureHook& sportschau = {}, + const std::vector* show_events = nullptr, + const SportschauReplayHooks* replay = nullptr); +// Loaded Source caller retains mutable descriptor award ownership; legacy raw +// probes without executable policy keep their existing immutable input API. +void process_group(GameState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + int group_index, const SportschauFixtureHook& sportschau, + const std::vector* show_events, const SportschauReplayHooks* replay, + const SportschauRatingTables* ratings); + +// ManagerMatchRecord: a human manager's record of match m (last results and fixtures, league +// win bonus, the manager rating via ManagerMatchRecord2 and the results per opponent). +void manager_match_record(GameState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report); +// TablePosition: current table position of a team (-1 before the first round). +int table_position(const GameState& g, int team); +// ManagerMatchRecord2: adds a match rating (0-200) to a manager's history of competition +// `competition` and stores the weighted average in the manager record (+0x8aa). +void rate_manager(GameState& g, int manager, int rating, int competition); + +// StirRandom: when a result or table screen (LeagueScreenShown) is left, the game stirs its +// random numbers: WatcomRandom(100, 300) game draws are thrown away. +void stir_random(GameRandom& game, WatcomRandom& rand); + +// LeagueScreenShown(param_1, param_2): whether the screen is shown at all. param_1 1 = table, +// 2 = results; param_2 = the phase end minute (90 / 120 / 45 ...); league = descriptor +// +0xcc (CareerSession_BeginFriendlyOpponentTable_RuntimeField2). The desk buttons (block LeaguePresentationOptions, 9 bytes per league) switch it off. +bool league_screen_shown(const std::vector& buttons, int param_1, int param_2, int league); + +// The rest of AdvanceTurn after a matchday: for every competition bit of the day (bits +// 0-4 = leagues) the round counter LeagueRoundCounters advances, the table is recomputed and +// each club's rank is added to the position history (*LeagueRankHistory); human managers get their +// season position and strength history updated. This API accepts league bits only; +// finish_event dispatches bits 5+ separately through advance_cup. +void advance_league_rounds(GameState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report, + const CompetitionWinnerHook& winner = {}); +// TicketPriceDraws: the random draws of a human manager's (disabled) ticket price drift. +void ticket_price_draws(const GameState& g, int manager, WatcomRandom& rand); + +} // namespace bmh diff --git a/src/game/matchday_setup.cpp b/src/game/matchday_setup.cpp new file mode 100644 index 0000000..a266d50 --- /dev/null +++ b/src/game/matchday_setup.cpp @@ -0,0 +1,1227 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/matchday_setup.hpp" +#include "game/trace.hpp" + +#include "game/national.hpp" + +#include +#include +#include +#include +#include + +#include "game/cup.hpp" +#include "game/lineup.hpp" +#include "game/match.hpp" +#include "game/matchday.hpp" +#include "game/schedule.hpp" +#include "game/messages.hpp" +#include "game/table.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kManagerRecord = 0xB0C; +constexpr size_t kDescriptorSize = 0xD0; +// Competition class per descriptor type (MatchEngineRuntimeField9): which card counters apply. +constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255, + 4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0}; +// League groups per competition bit 0-4 (CalendarFirstLeague first league, CalendarLeagueCounts count; +// the arrays are indexed with the bit for bits 0-3 and with 4..7 for bit 4). +// (kGroupLeague / kGroupLeagues: schedule.hpp, the calendar groups of the loaded game) +// Crowd interest per descriptor type (MatchdaySetupRuntimeField). +constexpr uint8_t kTypeInterest[24] = {5, 5, 10, 15, 12, 10, 5, 10, 5, 10, 5, 31, 10, 10, 10, 0, 0, 1, 0, 0, 0, 12, 0, 0}; +// Number of clubs taking part in league play (CareerSession_DispatchLineup_RuntimeField). +constexpr int kLeagueClubCount = 0x8a; +// Squad slots checked by the driver (CareerRuntimeField). +constexpr size_t kSquadSlotCount = 0xb70; + +// The attendance tables MatchdaySetup_Attendance_ExecutableField .. MatchdaySetupRuntimeField2 as one block, because the original +// indexes them with league classes 0-7 although they only have four entries: classes 4-7 +// (the regional leagues) read the next table. Offsets relative to MatchdaySetup_Attendance_ExecutableField. The dword at +// MatchdaySetupRuntimeField6 is written at run time by the human home path (Attendance at layout field) and is +// only reached here as MatchdaySetup_Attendance_ExecutableField3[4], which is multiplied by 0 for the regional leagues. +constexpr uint8_t kAttendanceTables[0x6a] = { + 0xb8, 0x88, 0x00, 0x00, 0x98, 0x3a, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x70, 0x17, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField capacity + 0x10, 0x27, 0x00, 0x00, 0x88, 0x13, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField2 base + 0xf0, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x96, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, // MatchdaySetup_Attendance_ExecutableField3 per strength + 0x00, 0x00, 0x00, 0x00, 0x30, 0x75, 0x00, 0x00, 0x30, 0x75, 0x00, 0x00, 0xa8, 0x61, 0x00, 0x00, // MatchdaySetupRuntimeField6 stadium steps + 0x20, 0x4e, 0x00, 0x00, 0xd8, 0x59, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x98, 0x3a, 0x00, 0x00, + 0x20, 0x4e, 0x00, 0x00, 0xa8, 0x61, 0x00, 0x00, // (a3f0a) + 0x46, 0x30, 0x1d, 0x0e, // MatchdaySetup_Attendance_ExecutableField4 strength offset + 0xa6, 0x82, 0x50, 0x20, // MatchdaySetup_Attendance_ExecutableField5 interest divisor + 0x14, 0x12, 0x10, 0x0e, // MatchdaySetup_Attendance_ExecutableField6 ticket price + 0x0c, 0x0f, // MatchdaySetupRuntimeField9 + 0x6e, 0x3c, 0x1e, 0x0a, // MatchdaySetup_Attendance_ExecutableField7 +}; +int32_t table_u32(uint32_t address, int index) { + size_t at = address - ::bmh::layout::MatchdaySetup_Attendance_ExecutableField + size_t(index) * 4; + return int32_t(kAttendanceTables[at] | kAttendanceTables[at + 1] << 8 | kAttendanceTables[at + 2] << 16 | + uint32_t(kAttendanceTables[at + 3]) << 24); +} +int table_u8(uint32_t address, int index) { return kAttendanceTables[address - ::bmh::layout::MatchdaySetup_Attendance_ExecutableField + size_t(index)]; } + +void put32(Bytes& b, size_t o, uint32_t v) { + for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i)); +} + +uint32_t rd32(const Bytes& b, size_t o) { + return uint32_t(b.at(o) | b.at(o + 1) << 8 | b.at(o + 2) << 16) | uint32_t(b.at(o + 3)) << 24; +} +void wr32(Bytes& b, size_t o, uint32_t v) { put32(b, o, v); } +void wr16(Bytes& b, size_t o, uint16_t v) { b.at(o) = uint8_t(v), b.at(o + 1) = uint8_t(v >> 8); } + +// TeamLeague2: league of a club, 0 for the special ids above 0x164, 9 outside the leagues. +int league_of(int team) { + if (team > 0x164) return 0; + return team_league(team); +} + +// RestoreForfeitSquad, called once per side after FinishEvent detects a forfeited fixture. +void restore_forfeit_squad(GameState& g, int team) { + const SquadRange range = squad_range(team); + for (size_t slot_index = range.first; slot_index < range.first + range.count; slot_index++) { + const uint16_t slot = g.squad_slots.at(slot_index); + const size_t player = slot & 0x0fff; + if (player == 0x0fff || player >= g.players.size() || player >= g.player_cards.size()) continue; + Player& p = g.players[player]; + if ((p.w35c >> 27) != 0) continue; + const uint16_t cards = g.player_cards[player]; + p.w368 = (p.w368 & 0xf8fc3fffu) | + (uint32_t(cards >> 9 & 7) << 24) | + (uint32_t(cards >> 5 & 0xf) << 14); + p.w364 &= 0xffe0ffffu; + p.w364 |= uint32_t(p.w364 >> 13 & 7) << 16; + } +} + +// BookMoney(manager, attendance, 0): income of the stadium's kiosks and restaurants: +// per facility 0-13 that exists, BalancePlanRuntimeField7[k] * attendance * level / 100 (level of +// facility 0 = its size step), then scaled by W(85, 115) %. +int32_t catering_income(const GameState& g, int manager, int32_t spectators, WatcomRandom& rand) { + static const uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2}; // BalancePlanRuntimeField7 + const size_t rec = size_t(manager) * kManagerRecord; + uint32_t sum = 0; + for (int k = 0; k < 14; k++) { + const uint8_t v = g.manager_records.at(rec + size_t(k)); + if (v == 0) continue; + const uint32_t level = k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + sum += kPerVisitor[k] * uint32_t(spectators) * level / 100; + } + if (sum != 0) sum = uint32_t(rand.range(0x55, 0x73)) * sum / 100; + return int32_t(sum); +} + +} // namespace + +namespace { +uint8_t sportschau_capacity(const GameState& g) { + const auto capacity = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField) ? g.memory.u8(::bmh::layout::CareerSession_FormatError_RuntimeField) : 0; + if (capacity > 9) throw std::invalid_argument("Sportschau A8 exceeds the Original nine-match capacity"); + return capacity; +} +} + +void reset_sportschau_selection(GameState& g) { + const auto capacity = sportschau_capacity(g); + std::fill_n(g.sportschau_priorities.begin(), capacity, uint8_t(0xff)); + g.sportschau_selection_available = true; +} + +bool consider_sportschau_fixture(GameState& g, const MatchGroup& group, + int home, int away, WatcomRandom& rand) { + const int setting = sportschau_source_setting_index(g, group); + if (setting < 0 || setting >= 20 || !g.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) || + g.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return false; + const uint8_t capacity = sportschau_capacity(g); + int16_t priority = 0; + for (int team : {home, away}) { + if (g.memory.has(::bmh::layout::MatchdaySetup_ConsiderSportschauFixture_RuntimeField) && g.memory.u8(::bmh::layout::MatchdaySetup_ConsiderSportschauFixture_RuntimeField) == 0 && g.manager_of(team) >= 0) + priority = int16_t(priority - 300); + const auto average = team_average(g, team, 0x1ff, &rand); + priority = int16_t(priority + ((100 - int(uint16_t(average.value))) >> 1)); + const int position = std::max(0, int(int8_t(table_position(g, team)))); + const int threshold = g.sportschau_club_threshold; + priority = int16_t(priority + position + (team >= threshold ? 50 : 0) + league_of(team) * 10); + } + if (priority <= 0) priority = 1; + g.sportschau_priorities[capacity] = uint8_t(priority); // low byte, not a clamp + g.sportschau_homes[capacity] = uint16_t(home); + for (int i = capacity; i > 0; --i) { + if (g.sportschau_priorities[size_t(i)] < g.sportschau_priorities[size_t(i - 1)]) { + std::swap(g.sportschau_priorities[size_t(i)], g.sportschau_priorities[size_t(i - 1)]); + std::swap(g.sportschau_homes[size_t(i)], g.sportschau_homes[size_t(i - 1)]); + } + } + return true; +} + +bool sportschau_selected(const GameState& g, int home) { + const auto capacity = sportschau_capacity(g); + return std::find(g.sportschau_homes.begin(), g.sportschau_homes.begin() + capacity, + uint16_t(home)) != g.sportschau_homes.begin() + capacity; +} + +void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand) { + const int home = grp.fixtures.at(size_t(m) * 2), away = grp.fixtures.at(size_t(m) * 2 + 1); + const int region = team_region(home); + int8_t base = int8_t(month_temperature(ctx.month) + region_temperature(region)); + const uint8_t temperature = uint8_t(rand.range(0, 6) + base - 3); + grp.desc.at(0x30 + size_t(m)) = temperature; + int rain = rand.range(0, 5); + // the temperature is compared as an unsigned byte: only 0 and 1 degrees bring snow + if (temperature < 2 && rain > 3) rain += 2; + grp.desc.at(0x50 + size_t(m)) = uint8_t(rain); + if (int16_t(home) < kNoTeam && uint16_t(away) < kNoTeam && !(grp.desc.at(1) & 0x80)) { + // Range(1): a referee not yet chosen today + std::vector& refs = *ctx.referees; + int r; + do { + r = game.range(1, 0x31); + } while (refs.at(size_t(r)) & 0x80); + refs.at(size_t(r)) |= 0x80; + grp.desc.at(0x10 + size_t(m)) = uint8_t(r); + } +} + +void prepare_team(GameState& g, int team, int cls, int index) { + uint16_t& flags = g.team_flags.at(size_t(team)); + flags = uint16_t((flags & 0xFF0F) | ((index % 2) << 4)); + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + uint16_t& slot = g.squad_slots.at(s); + slot &= 0xCFFF; + if ((slot & 0x0FFF) == 0x0FFF) break; + const int player = slot & 0x0FFF; + Player& p = g.players.at(size_t(player)); + if (p.w35c >> 27) continue; // not available (loaned out or similar) + uint16_t& cards = g.player_cards.at(size_t(player)); + // keep the league yellow cards of this season (bits 5-8 and 9-11) + cards = uint16_t((cards & 0xF01F) | ((p.w368 >> 14) & 0xF) << 5); + cards = uint16_t(cards | ((p.w368 >> 24) & 7) << 9); + uint8_t injury = 0; + if (cls != 0) { + // the card counters of this competition replace the league ones for the match + p.w368 &= 0xF8FC3FFFu; + const uint8_t k = uint8_t(cls - 1); + if (k <= 3) { + uint32_t v = k == 0 ? p.w364 >> 8 : k == 1 ? p.w364 >> 10 : k == 2 ? uint32_t(cards >> 14) : uint32_t(cards >> 12); + p.w368 |= (v & 3) << 14; + } + if (int8_t(cls) != -1 && ((p.w368 >> 14) & 3) > 1) injury = 1; // banned + } else { + injury = uint8_t((p.w364 >> 16) & 0xF); + } + p.w364 &= 0xFFFF0FFFu; + p.w364 |= ((p.w364 >> 16) & 7) << 13; + p.w364 &= 0xFFE0FFFFu; + if (injury) { + slot &= 0x0FFF; + p.w364 |= uint32_t(injury) << 16; + } + } +} + +// Postponed league matches (Postponed): 40 entries of 6 bytes - the day of the replay +// (u16, 0 = free entry), the league round (+2), the league (+3) and the match (+4). +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; +constexpr int kPostponedEntries = 0x28; +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day +// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break (static data, no +// replays are scheduled in between) +constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8; +constexpr uint8_t kPostponedMark = 0xcd; // result byte of a postponed match + +uint16_t calendar_entry(const GameState& g, int day) { return g.memory.u16(kCalendar + uint32_t(day) * 2); } + +// RescheduleLeagueMatch (with param_5 = -0x33): finds a replay day for match `m` of round `round` in +// `league`, starting five days after `day`. A day qualifies when it and both neighbours are +// free in the calendar (the day before may carry bit 4), or when it already is a replay day +// (0x4000); a coin toss of the game generator may still refuse it, as may eight replays or a +// team clash on that day. Records the replay in entry `slot`, marks the result byte and the +// calendar day. +bool schedule_replay(GameState& g, int day, int league, int m, int slot, int round, GameRandom& game) { + for (int date = day + 5;; date++) { + if (date > 0x11e) return false; + if (date >= kWinterBreakFirst && date <= kWinterBreakLast) date = kWinterBreakLast + 1; + const bool free = (calendar_entry(g, date) == 0 && (calendar_entry(g, date - 1) & 0xffef) == 0 && + calendar_entry(g, date + 1) == 0) || + calendar_entry(g, date) == 0x4000; + if (!free) continue; + bool ok = true; + if (game.range(0, 1) == 0) { + int same_day = 0; + for (int e = 0; e < kPostponedEntries && ok; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != date) continue; + if (++same_day == 8) { + ok = false; + break; + } + // The original generates the other replay's fixtures with the parameters of + // `league`, whatever league that entry belongs to, and compares only the low + // bytes of the team ids. + const std::vector other = generate_fixtures(league_table_teams(league), g.memory.u8(at + 2) + 1, + league_matchdays(league) / 2, league_first_team(league)); + const std::vector own = + generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league)); + const Fixture& o = other.at(g.memory.u8(at + 4)); + const Fixture& f = own.at(size_t(m)); + const uint8_t oh = uint8_t(o.home), oa = uint8_t(o.away), fh = uint8_t(f.home), fa = uint8_t(f.away); + if (fh == oh || fa == oa || fa == oh || fh == oa) ok = false; + } + } else { + ok = false; + } + if (ok) { + const uint32_t at = kPostponed + uint32_t(slot) * 6; + g.memory.set16(at, uint16_t(date)); + g.memory.set8(at + 2, uint8_t(round)); + g.memory.set8(at + 3, uint8_t(league)); + g.memory.set8(at + 4, uint8_t(m)); + g.results.at(size_t(m) + size_t(round) * 10 + size_t(league) * 0x17C) = kPostponedMark; + g.memory.set8(kCalendar + uint32_t(date) * 2 + 1, g.memory.u8(kCalendar + uint32_t(date) * 2 + 1) | 0x40); + return true; + } + } +} + +// WinterPostponements: winter postponements of a league matchday (leagues 0-4, season days +// 0x6e..0xe6, unless MatchdaySetup_WinterPostponements_RuntimeField2 is set). The number of postponed matches peaks around day +// 0xaa and is capped by the option byte MatchdaySetup_WinterPostponements_RuntimeField. +void winter_postponements(GameState& g, int day, int league, GameRandom& game, WatcomRandom& rand) { + if (g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField2) != 0 || league >= 5 || day <= 0x6d || day >= 0xe7) return; + const int16_t distance = int16_t(std::abs(day - 0xaa) / 10); + int16_t most = int16_t(9 - distance); + if (most != 0 && rand.range(0, 1) != 0) most = int16_t(8 - distance); + int16_t count = int16_t(rand.range(0, most)); + if (int16_t(g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField)) < count) count = int16_t(g.memory.u8(::bmh::layout::MatchdaySetup_WinterPostponements_RuntimeField)); + const int round = g.league_rounds.at(size_t(league)); + int16_t before; + do { + before = count; + if (count == 0) return; + for (int slot = 0; slot < kPostponedEntries; slot++) { + if (g.memory.u16(kPostponed + uint32_t(slot) * 6) != 0) continue; + const int m = rand.range(0, kLeagueSizes[league] / 2 - 1); + if ((g.results.at(size_t(m) + size_t(round) * 10 + size_t(league) * 0x17C) & 0xcf) == 0xcc && + schedule_replay(g, day, league, m, slot, round, game)) { + count--; + break; + } + } + } while (before != count); +} + +// ClubName3(team, buffer): the longest word of a club's name (separators MatchdaySetupRuntimeField5 +// " %.1-"; of words with the same length the last one), written to `out` at `at`; a word +// ending in "ER" loses the "ER" ("HER": only the "R"). +void longest_word(const GameState& g, int team, std::vector& out, size_t at) { + static constexpr char kSeparators[] = {' ', '%', '.', '1', '-'}; + const std::string name = g.club_name(team); + int start = 0, longest = 0; + for (int i = 0; i <= int(name.size()); i++) { + const char c = i < int(name.size()) ? name[size_t(i)] : '\0'; + for (char sep : kSeparators) { + if (sep != c && c != '\0') continue; + if (longest <= i - start) { + longest = i - start; + for (int k = 0; k < longest; k++) out.at(at + size_t(k)) = uint8_t(name[size_t(start + k)]); + out.at(at + size_t(longest)) = 0; + } + start = i + 1; + } + } + if (longest >= 3 && out.at(at + size_t(longest) - 1) == 'R' && out.at(at + size_t(longest) - 2) == 'E') + out.at(at + size_t(longest + (out.at(at + size_t(longest) - 3) == 'H') - 2)) = 0; +} + +// AddCompetition(id): puts a competition on the list of running ones (ActiveSelectors, 8 bytes, +// 0x14 = free); false if it is there already. +bool add_competition(GameState& g, int id) { + for (uint32_t i = 0; i < 8; i++) { + if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == id) return false; + if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(id)); + return true; + } + } + return true; +} + +// IndoorTournamentDraw (with Cup_AdvanceCup_RuntimeField4 = CupRuntimeField = 0): the draw of the indoor tournament +// after the first half of the season. Eight clubs: at random one of the regional leagues +// (teams 90-137), 5-7 of the first league and the rest of the second, none twice; the second +// club drawn names the tournament. A human manager's club gets a starting bonus of 100 000. +// The order is then shuffled (PrepareEvent) and the tournament's strength class computed +// (IndoorTournamentReset). +void indoor_tournament_reset(GameState& g) { + StaticMemory& mem = g.memory; + if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4) == 0) // the first tournament: Masters points and invitations + for (uint32_t i = 0; i < 0x50; i++) mem.set8(::bmh::layout::Cup_AdvanceCup_ExecutableField + i, 0), mem.set8(::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField + i, 0); + if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0); + const std::string in = message_text(g, ::bmh::layout::MatchdaySetup_IndoorTournamentReset_TextPointer); // "In " + for (size_t i = 0; i <= in.size() && i < 0x24; i++) g.tournament_name[i] = i < in.size() ? uint8_t(in[i]) : 0; + for (uint32_t i = 0; i < 0x20; i++) mem.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc); + for (int i = 0x19; i < 0x1e; i++) mem.set8(::bmh::layout::MatchdaySetup_IndoorTournamentReset_RuntimeField + uint32_t(i) * 0x28, 0); // played counters +} + +void indoor_tournament_draw(GameState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + constexpr uint32_t kTeams = ::bmh::layout::Teams, kInvitations = ::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField; // u16 per club < 0x28 + const int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4); // tournaments played so far (Cup_AdvanceCup_RuntimeField4) + indoor_tournament_reset(g); + uint8_t attempts = 0; + const int guest = rand.range(0, 1); + if (guest != 0) mem.set16(kTeams, uint16_t(rand.range(90, 137))); + int count = guest != 0; + int n = rand.range(5, 7); + uint8_t lo = 0, hi = uint8_t(kLeagueSizes[0]); + uint32_t previous; + do { + for (int s = 0; s < n; s++) { + bool again; + uint16_t t; + do { + again = false; + attempts++; + t = uint16_t(rand.range(lo, hi - 1)); + if (int16_t(t) < 0x28 && int16_t(mem.u16(kInvitations + uint32_t(t) * 2)) > 1) { + again = true; + if (attempts > 0x14) attempts = 0xf, hi++; + } else { + if (count == 1) { + // the second club drawn hosts the tournament, not a host of before + longest_word(g, t, g.tournament_name, 3); + for (int k = 0; k < held; k++) + if (t == mem.u8(::bmh::layout::LiveMatchday_FormatError_RuntimeField14 + uint32_t(k))) again = true; + mem.set8(::bmh::layout::LiveMatchday_FormatError_RuntimeField14 + uint32_t(held), uint8_t(t)); + } + for (int k = 0; k < count; k++) + if (mem.u16(kTeams + uint32_t(k) * 2) == t) again = true; + } + } while (again); + if (count < 8) mem.set16(kTeams + uint32_t(count++) * 2, t); + } + n = 8 - count; + previous = hi; + lo = hi; + hi = uint8_t(hi + kLeagueSizes[1]); + } while (previous < uint32_t(kLeagueSizes[0] + kLeagueSizes[1])); + std::string title; + for (size_t i = 3; i < g.tournament_name.size() && g.tournament_name[i]; i++) title.push_back(char(g.tournament_name[i])); + for (uint32_t k = 0; k < 8; k++) { + const uint16_t t = mem.u16(kTeams + k * 2); + const int manager = g.manager_of(t); + if (manager >= 0) { + post_composed(g, manager, std::string(kIndoorInvitationText) + title); + book_money(g, manager, -100000, true, true); + } + if (t < 0x28) mem.set16(kInvitations + uint32_t(t) * 2, uint16_t(mem.u16(kInvitations + uint32_t(t) * 2) + 1)); + } + for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams) + const uint32_t j = uint32_t(game.range(0, 7)); + const uint16_t a = mem.u16(kTeams + i * 2); + mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2)); + mem.set16(kTeams + j * 2, a); + } + int sum = 0; // IndoorTournamentReset + for (uint32_t k = 0; k < 8; k++) { + const int t = mem.u16(kTeams + k * 2); + const int league = t > 0x164 ? 0 : team_league(t); // TeamLeague2 + if (league < 2) sum += (0x26 - table_position(g, t)) - kLeagueSizes[0] * league; + else if (league < 5) sum += 1; + else sum += 0x19; + } + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField3, uint8_t(int16_t(sum + 7) / 8)); +} + +uint32_t day_competitions(const GameState& g, uint16_t entry) { + uint32_t v = entry & 0x7fff; + if (g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2) != 0) v = entry & 0x7fef; + // (German: the indoor option off removes the indoor days; the English CycleManagerOptions2 has no + // such test - its 0x4002 days are the League Cup) + if (!kEnglishCompetitions && g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField) != 0 && v == 0x4002) v = 0; + if ((v & 0x4001) == 0x4001) v = (v & 0xff0) | 0x8000; + if (v == 0x4002) v = 0x10000; + if (v == 0x4004) v = 0x40000; + if (v == 0x4006) v = (g.memory.u8(::bmh::layout::CompetitionSelection) & 2) ? 0x800000 : 0; + // the international tournament of the year (bits 9-12) turns with the season; the English + // CycleManagerOptions2 counts from 1995 and adds 3 ((season + 3) % 4) to stay in step + if (v & 0x1e00) v &= 1u << (0xc - (g.season + (kEnglishCompetitions ? 3 : 0)) % 4); + return v; +} + +void cycle_manager_options(GameState& g) { + for (size_t k = 0; k < g.manager_teams.size(); k++) { + uint8_t option = g.manager_options.at(k * 5); + const uint8_t enabled = g.manager_records.at(k * kManagerRecord + 0x218 + (g.indoor ? 1 : 0)); + if (option != 0 && enabled != 0) + while (!((enabled >> (option - 1)) & 1)) { + option++; + if (option > 8) option = 1; + } + g.manager_options.at(k * 5) = option; + } +} + +// DayConflict(team, other, calendar entry, day): whether a friendly day concerns the team. +// A calendar entry other than 0 and 0x4001 without the top bit always does; otherwise the +// friendly list (FriendlyDays: 30 days, FriendlyTeams: the two teams of each) is searched +// for a friendly on `day` with the national team, `team` or `other`. +static bool national_friendly(const GameState& g, int team, int other, int16_t entry, int day) { + if (entry != 0 && entry != 0x4001 && !(uint16_t(entry) & 0x8000)) return true; + const StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams)) return false; + for (int i = 0; i < 0x3c; i += 2) { + if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i / 2) * 2)) != day) continue; + for (int k = 0; k < 2; k++) { + const int t = int16_t(mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i + k) * 2)); + if (t == kNoTeam || t == team || t == other) return true; + } + } + return false; +} + +bool matchday_needs_manager_desks(const GameState& g, uint16_t calendar_entry, + const std::vector& groups) { + if (g.manager_teams.empty()) return false; + const auto& mem = g.memory; + const bool opening = g.season_day() == 0; + const bool closing = mem.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && mem.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0; + int request = mem.u8(::bmh::layout::MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField) + int(opening) + int(closing); + if (mem.u32(::bmh::layout::CompetitionSelection) == 2) request = 0; + if (day_competitions(g, calendar_entry) == 0x8000 && + national_friendly(g, kNoTeam, 500, int16_t(calendar_entry), g.season_day())) + request = 4; + + // MatchdayNeedsManagerDesks assigns local_44 only to actual participants. League results + // must still be 0xcc; setup has already changed postponed 0xce to 0xcd. + // Cup descriptors instead obtain the context from their entry's +0x18. + for (const auto& group : groups) { + const uint32_t competition = rd32(group.desc, 0xcc); + for (size_t fixture = 0; fixture < size_t(group.matches()); ++fixture) { + if (competition < 0x14) { + const size_t result = size_t(competition) * 0x17c + + size_t(g.league_rounds.at(competition)) * 10 + fixture; + if (g.results.at(result) != 0xcc) continue; + } else if (int8_t(mem.u8(competition + 0x18) + 5) >= 0x1e) { + continue; + } + if (g.manager_of(group.fixtures.at(fixture * 2)) >= 0 || + g.manager_of(group.fixtures.at(fixture * 2 + 1)) >= 0) + request = 1; + } + } + return (mem.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) && mem.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField) != 0) || + (request != 0 && (request == 4 || !groups.empty() || closing || opening)); +} + +std::vector setup_matchday(GameState& g, uint32_t competitions, const MatchdayContext& ctx, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + std::vector groups; + // AdvanceTurn first: after the first half of the Bundesliga season (17 rounds) the + // indoor tournament (competition 0xb) is drawn once, unless switched off (CalendarState_FormatError_RuntimeField) + if (g.league_rounds.at(0) == 0x11 && g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField) == 0 && add_competition(g, 0xb)) { + g.memory.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, 0); // Cup_AdvanceCup_RuntimeField4: the first tournament of the season + turn_step = "setup: indoor tournament draw"; + indoor_tournament_draw(g, game, rand); + } + // AdvanceTurn keeps the day's competition bits (DayCompetitions of the calendar entry) in + // SavedCompetition; the savegame carries the value of the last prepared matchday. + g.memory.set32(::bmh::layout::SavedCompetition, competitions); + // the Bundestrainer: on an international match day (competition bits 0x1e00) or a friendly + // day of the national team (local_28 == 4), not on season day 0 and not after the season + // end, he takes the national team over (SwapManagerSlots2) unless he already has; on any other + // day a take-over in effect ends (NationalCoachHandBack). (ActiveManager at this point: what the day + // step's manager loop left, the number of managers.) + if (!ctx.national_team_day) { + const bool national_day = + (competitions & 0x1e00) || + (competitions == 0x8000 && + national_friendly(g, kNoTeam, 500, int16_t(g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(ctx.season_day) * 2)), ctx.season_day)); + if (national_day && !(g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) && ctx.season_day != 0) { + if (!national_coach_active(g)) + national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(ctx.season_day)); + } else if (national_coach_active(g)) { + national_coach_hand_back(g); + } + } + g.indoor = false; + for (uint8_t& r : *ctx.referees) r &= 0x7F; // Range(0) + for (int bit = 0; bit < 0x13; bit++) { + if (!((competitions >> bit) & 1)) continue; + if (bit >= 5) { + turn_step = "setup: cup groups"; + setup_cup_groups(g, bit - 5, groups, report); // SetupCupGroups(bit - 5) + continue; + } + const int from = bit, to = bit < 4 ? bit + 1 : 8; + for (int k = from; k < to; k++) { + // FixturesFromGenerateFixtures(k) + for (int league = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; league++) { + turn_step = "setup: winter postponements"; + winter_postponements(g, ctx.season_day, league, game, rand); + const int round = g.league_rounds.at(size_t(league)); + const int size = kLeagueSizes[league]; + MatchGroup grp; + grp.desc = group_descriptor(g, groups.size()); + for (const Fixture& f : generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league))) { + grp.fixtures.push_back(f.home); + grp.fixtures.push_back(f.away); + } + const size_t at = size_t(league) * 0x17C + size_t(round) * 10; + for (int m = 0; m < size / 2; m++) { + uint8_t& r = g.results.at(at + size_t(m)); + if ((r & 0xCF) == 0xCE) r = 0xCD; // postponed -> to be replayed later + } + grp.desc.at(0) = 0; // league + grp.desc.at(1) = 2; + grp.desc.at(2) = uint8_t(size / 2); + put32(grp.desc, 0xcc, uint32_t(league)); + // MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a) + for (int i = 0; i < size; i++) + for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++) + if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * kManagerRecord + 0x28a) = uint8_t(i % 2); + groups.push_back(grp); + } + // before the 17th Bundesliga matchday every manager is reminded that the balance + // sheets go to the DFB at the end of the first half of the season (MatchdaySetup_SetupMatchday_TextPointer) + if (k == 0 && g.league_rounds.at(0) == 0x10) post_text(g, -1, text_id(::bmh::layout::MatchdaySetup_SetupMatchday_TextPointer)); + } + } + turn_step = "setup: teams"; + for (MatchGroup& grp : groups) { + const int cls = kCompetitionClass[grp.desc.at(0)]; + for (int i = 0; i < grp.matches() * 2; i++) { + if (i < grp.matches()) match_weather(grp, i, ctx, game, rand); + const int team = grp.fixtures.at(size_t(i)); + prepare_team(g, team, cls, i); + try { + auto_lineup(g, team, 100); + } catch (const std::invalid_argument& e) { + report.fail(e.what()); + } + } + } + for (int team = 0; team < kLeagueClubCount; team++) + if (g.team_flags.at(size_t(team)) & 1) auto_lineup(g, team, 100); + turn_step = "setup: options"; + cycle_manager_options(g); + store_group_descriptors(g, groups); + return groups; +} + +int match_mode_bits(const GameState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report) { + const int type = grp.desc.at(0); + uint8_t bits = kTypeInterest[type]; + if (type == 0) { + const int league = int(le32(grp.desc, 0xcc)); + const int matchdays = league_matchdays(league), rounds = g.league_rounds.at(size_t(league)); + // the last four rounds draw more spectators + if (rounds > matchdays - 4) bits = uint8_t(bits + uint8_t(0xF - uint8_t((matchdays - rounds) * 3))); + } else if (type != 9 && type != 0xb) { + // cups: more interest in the last round of a stage, even more in the final + const uint32_t e = le32(grp.desc, 0xcc); + if (g.memory.u8(e + 0x1d) + 1 >= g.memory.u8(e + 0x1b)) { + bits = uint8_t(bits + 5); + if (g.memory.u8(e + 0x16) == 0) bits = uint8_t(bits + 10); + } + } + int result = bits; + if (ctx.weekday == 4 && type == 10) result |= 0x20; + if (!(grp.desc.at(1) & 2)) result |= 0x80; + if (type == 1) result |= 0x100; + if (type > 1 && type < 5) result |= 0x200; + return result; +} + +int attendance(GameState& g, int home, int away, int bits, int temperature, int rain, int competition_type, + GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int team[2] = {home, away}; + int strength[2] = {0, 0}, position[2] = {0, 0}, league[2] = {0, 0}; // local_6c[2..3], local_7c + int best_half_sum = 0; // CareerSession_FormatError_ExecutableField3 (home side) + for (int i = 1; i >= 0; i--) { + const TeamAverage avg = team_average(g, team[i], 0x1f7, &rand); + strength[i] = uint16_t(avg.value); + best_half_sum = avg.best_half_sum; + position[i] = table_position(g, team[i]); + if (position[i] < 0) position[i] = rand.range(2, 5); + if (uint16_t(team[i]) >= 0x5a) { + league[i] = 0; + } else { + league[i] = league_of(team[i]); + if (league[i] > 2) league[i]--; + } + } + const int home_manager = g.manager_of(home), away_manager = g.manager_of(away); // local_20, local_14 + const size_t rec = size_t(home_manager) * 0xB0C; // EDI / puVar10: the home manager's record + auto r8 = [&](size_t off) { return int(g.manager_records.at(rec + off)); }; + auto r16 = [&](size_t off) { return int(g.manager_records.at(rec + off) | g.manager_records.at(rec + off + 1) << 8); }; + auto r32 = [&](size_t off) { return int32_t(rd32(g.manager_records, rec + off)); }; + auto w32 = [&](size_t off, int32_t v) { wr32(g.manager_records, rec + off, uint32_t(v)); }; + + int32_t n; // ESI: the attendance + int price; // local_38: ticket price + if ((home_manager < 0 || home != kNoTeam) && !(bits & 0x80)) { + const int lh = league[0], la = league[1]; + n = table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField2, lh); + int prestige = 0x32, performance = 0x226; // local_24, local_2c + if (home_manager < 0) { + price = table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField6, lh); + } else { + if (strength[0] < best_half_sum - 10) n += 2000; // a team with stars draws more + prestige = r8(0x211); + performance = r16(0x8aa); + price = r8(0x26e); + } + int sum = 0, sum_above = 0; // local_50, local_30 + for (int i = 0; i < 2; i++) { + sum += strength[i]; + int16_t above = int16_t(strength[i] - table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField4, league[i])); + if (above < 0) above = 0; + if (above > 30) above = 30; + sum_above += above; + } + const int32_t from_strength = sum_above * table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField3, lh); + int x = (40 - position[0] - position[1]) * 2; // local_5c + if (lh + la == 0 && rand.range(60, 66) < x) x = x * rand.range(110, 125) / 100; + prestige = uint8_t(prestige / (lh + 1)); + performance = uint16_t(performance / 5 / (lh + 1)); + x += (performance >> 2) + (prestige >> 2); + n = (x + 80) * (n + from_strength) / 100; + if (la < lh) + n += lh * -2000 + la * -500 + 10000; + else if (lh < la) + n += (4 - la) * -4000; + int capacity; // local_3c + if (home_manager < 0) { + const int a = table_u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField, lh); + capacity = rand.range(a - (a >> 2), a + (a >> 2)) / 500 * 500; + if ((bits & 0x180) == 0x180) capacity = 76000; + } else { + // the manager's stadium: facilities, size steps, roofs against the rain + int covered = 0; // local_64: covered share of the stands + const int facilities = facility_rating(g, home_manager, &covered, &rand) - table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField7, lh); // local_44 + static const int32_t kStadiumSteps[10] = {0, 30000, 30000, 25000, 20000, 23000, 10000, 15000, 20000, 25000}; + for (int k = 0; k < 10; k++) { + const int v = r8(size_t(k)); + // MatchdaySetupRuntimeField6[0] is overwritten with the step of the stadium size + const int32_t step = k == 0 ? int32_t(v / 0x55 * 25000) : kStadiumSteps[k]; + if (step < n && (v == 0 || k == 0)) n -= n / rand.range(10, 20); + } + const int wet = int(uint32_t(100 - covered) * uint32_t(uint8_t(rain)) * 8) / 100; + n = (((n >> 1) + (100 - wet) * (n >> 1) / 100) * (int8_t(temperature) + 0x5a)) / 100 >> 1; + n += n * rand.range(facilities + 0x5a, facilities + 0x6e) / 100; + capacity = r8(0x5c) * 1000; + } + const int level_bonus = (9 - g.level) * 2; // Range3 returns 1 in this version + const int form = rand.range(level_bonus + 0x55, level_bonus + 0x5f); + int interest = bits & 0x1f; + if (interest == 0x1f) { + interest = -10; + bits = 0; + } + if (interest > 20) interest = 20; + int demand = sum * ((bits & 0x1f) + 100) / 100; + if (demand < 0) demand = 0; + if (demand > 180) demand = 180; + int price_index = price * 100 / table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField6, lh); + int demand_index = demand * 100 / table_u8(::bmh::layout::MatchdaySetup_Attendance_ExecutableField5, lh); + if (price_index < demand_index) price_index += price_index >> 3; + if (demand_index < 30) demand_index = 30; + if (demand_index > 180) demand_index = 180; + n = ((interest * 3 + 100) * (n * form / 100) / 100) * (demand_index + 100 - price_index) / 100; + int standing = 1, seated = 1; // local_4c, local_48: places of the open stands + if (home_manager >= 0) { + // stands that differ much from an eighth of the stadium put people off + int unevenness = 0; // local_60 + int unit = r8(0x5c) >> 3; + if (unit == 0) unit = 1; + for (int k = 0; k < 8; k++) { + const int places = r8(0x34 + size_t(k)) == 0 ? r8(0x4c + size_t(k)) : 0; + unevenness += std::abs(100 - places * 100 / unit); + if (r8(0x3c + size_t(k)) & 1) + seated += places; + else + standing += places; + } + unevenness >>= 3; + if (rand.range(0x8c, 0xb4) < unevenness) { + unevenness = unevenness < 0x96 ? 0x96 : unevenness > 0xfa ? 0xfa : unevenness; + unevenness -= 0x96; + n -= (unevenness >> 1) * n / 100; + } + } + if (bits & 0x20) n = rand.range(n - (n >> 2), n + (n >> 2)); + if (n < 100) n = rand.range(100, 500); + n = (n + 100) / 100 * 100; + if (n > capacity) n = capacity; + if (home_manager >= 0 && capacity * rand.range(0x4b, 100) / 100 < n && rand.range(0, r8(0x210) + 1) == 0) { + // a full house: few seats make riots likely (record +0x289 then costs the team at + // kick-off, see rate_side); the damage is paid by the club + const int share = seated * 100 / standing; + g.manager_records.at(rec + 0x289) = share < 0x1e; + if (share < game.range(0x50, 0x78) && r8(0x43) < 3 && rand.range(0, r8(0x43) << 2) == 0) { + const int32_t damage = rand.range(n / 0x1e, n / 10) * 100; + post_composed(g, home_manager, message_text(g, ::bmh::layout::MatchdaySetup_Attendance_TextPointer) + format_amount(g, damage) + message_text(g, ::bmh::layout::CareerSession_Int32T_TextPointer)); + book_money(g, home_manager, damage, true, true); + } + } + } else { + n = (rand.range(3, 10) + (bits & 0x1f)) * 2500; + if ((bits & 0x40) && n > 74000) n = 74000; + price = 0x16; + } + int32_t income = price * n; // local_5c: ticket income + if (bits & 0x180) income >>= 1; + if (home_manager + away_manager != -2 && (bits & 0x100)) { + // cup matches with a human club: TV and advertising rights raise the (shared) gate + // by W(12, 15) / 10; both human managers get the message "... erhöhten sich Ihre + // Einnahmen auf (+ )." (MatchdaySetup_Attendance_TextPointer2, MatchdaySetupRuntimeField7 " (+ ", MatchdaySetupRuntimeField8 ").") + const int32_t raised = income * rand.range(12, 15) / 10; // MatchdaySetupRuntimeField9, MatchdaySetupRuntimeField10 + const std::string text = message_text(g, ::bmh::layout::MatchdaySetup_Attendance_TextPointer2) + format_amount(g, raised) + " (+ " + + format_amount(g, raised - income) + ")."; + int64_t mask = 0x80000000LL; + if (home_manager >= 0) mask |= 1LL << home_manager; + if (away_manager >= 0) mask |= 1LL << away_manager; + post_composed(g, mask, text); + income = raised; + } + int kind = ((bits & 0x200) ? 2 : 0) + ((bits & 0x100) ? 1 : 0); // 0 league, 1 cup, 2 other + if (kind > 2) { + report.fail("attendance: invalid competition bits"); + kind = 2; + } + if (home_manager >= 0 && r16(0x290) != kNoTeam) { + book_money(g, home_manager, -income, true); + w32(0x868, r32(0x868) + income); + const int32_t catering = catering_income(g, home_manager, n, rand); // BookMoney + book_money(g, home_manager, -catering, true); + w32(0x38c + 2 * 4, catering); // indexed by a stale loop counter (2) in the original + w32(0x86c, r32(0x86c) + catering); + if (kind != 0 || competition_type == 0 || competition_type == 0xe || competition_type == 0xa) { + g.manager_records.at(rec + 0x28c + size_t(kind))++; + w32(0x748 + size_t(kind) * 4, r32(0x748 + size_t(kind) * 4) + n); + w32(0x754 + size_t(kind) * 4, r32(0x754 + size_t(kind) * 4) + income); + if (n > r32(0x718 + size_t(kind) * 8)) { // record attendance + w32(0x718 + size_t(kind) * 8, n); + w32(0x71c + size_t(kind) * 8, int32_t(g.date)); + wr16(g.manager_records, rec + 0x8c0 + size_t(kind) * 2, g.club_ids.at(size_t(away))); + } + if (income > r32(0x730 + size_t(kind) * 8)) { // record income + w32(0x730 + size_t(kind) * 8, income); + w32(0x734 + size_t(kind) * 8, + int32_t(uint32_t(g.season_day()) + uint32_t(g.memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)))); + wr16(g.manager_records, rec + 0x8c6 + size_t(kind) * 2, g.club_ids.at(size_t(away))); + } + if (kind == 0) { + // the last 19 league home matches: attendance (+0x340) and ticket price (+0x270) + auto& m = g.manager_records; + int k = int8_t(r8(0x283)); + if (k < 0x13) { + m.at(rec + 0x283) = uint8_t(k + 1); + } else { + std::copy(m.begin() + long(rec + 0x344), m.begin() + long(rec + 0x344 + 0x48), m.begin() + long(rec + 0x340)); + std::copy(m.begin() + long(rec + 0x271), m.begin() + long(rec + 0x271 + 0x12), m.begin() + long(rec + 0x270)); + // (only 0x12 bytes of the u32 list +0x38c are moved) + std::copy(m.begin() + long(rec + 0x390), m.begin() + long(rec + 0x390 + 0x12), m.begin() + long(rec + 0x38c)); + k = 0x12; + } + w32(0x340 + size_t(k) * 4, n); + m.at(rec + 0x270 + size_t(k)) = uint8_t(price); + // season ticket holders (+0x2ac) have paid already: 70 % of their tickets + // are taken back from the gate income + const int holders = std::min(r16(0x2ac), int(n)); + const int32_t refund = price * (holders * 0x46 / 100); + book_money(g, home_manager, refund, true); + w32(0x754, r32(0x754) - refund); + w32(0x868, r32(0x868) - refund); + } + } + } + if (away_manager >= 0 && (bits & 0x180)) { + // a shared gate (cups, bits 7/8): the human away club gets the same half and counts + // the match in its attendance statistics (no catering, no records) + const size_t away_rec = size_t(away_manager) * 0xB0C; + auto& m = g.manager_records; + if ((m.at(away_rec + 0x290) | m.at(away_rec + 0x291) << 8) != kNoTeam) { + book_money(g, away_manager, -income, true); + wr32(m, away_rec + 0x868, rd32(m, away_rec + 0x868) + uint32_t(income)); + m.at(away_rec + 0x28c + size_t(kind))++; + wr32(m, away_rec + 0x748 + size_t(kind) * 4, rd32(m, away_rec + 0x748 + size_t(kind) * 4) + uint32_t(n)); + wr32(m, away_rec + 0x754 + size_t(kind) * 4, rd32(m, away_rec + 0x754 + size_t(kind) * 4) + uint32_t(income)); + } + } + return n; +} + +namespace { + +// AutoLineup: a match with a human team (morale byte bit 7) is shown live, unless the +// option LiveDeskDisabled is set or 4 matches are already chosen. Returns true if chosen (the +// original also loads the club colours then, which is display only). +bool select_live_match(GameState& g, int home, int away) { + if (!(g.team_morale.at(size_t(home)) & 0x80) && !(g.team_morale.at(size_t(away)) & 0x80)) return false; + for (int t : g.live_matches) + if (t == home) return false; + const bool no_live = g.memory.has(::bmh::layout::LiveDeskDisabled) && g.memory.u8(::bmh::layout::LiveDeskDisabled) != 0; + if (no_live || g.live_matches.size() >= 4) return false; + g.live_matches.push_back(home); + return true; +} + +// KickOff(own manager, own team, other manager, other team, 50, rate): man marking. +// The other team's midfielders and forwards in the line-up are ranked (forwards first, +// then strength, depth preference, shooting skill and experience); each of them is marked +// with a probability of 50 % (+30/20/10 % for the best three). The marker is drawn from the +// own defenders and midfielders not marking yet, ranked by strength, tackling skill and +// how close their board places are; each candidate in turn takes the job with `rate` %. +// Human managers record the pairs on their tactics boards (slot +0x44 = the player the +// slot marks, +0x46 = the player marking the slot); computer teams just draw. A human +// manager only takes part with option byte 3 (MatchdaySetupRuntimeField11) set; his rate comes from +// record +0x8ac / 16 + 40. +void man_marking(GameState& g, int own_manager, int own, int other_manager, int other, int chance, int rate, + WatcomRandom& rand) { + constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField + if (g.indoor || own >= kLeagueTeams || other >= kLeagueTeams || (own_manager < 0 && other_manager < 0)) return; + if (other_manager >= 0) + for (size_t s = 0; s < 24; s++) { + const size_t at = size_t(other_manager) * 0x840 + s * 0x58 + 0x46; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + if (own_manager >= 0) { + if (!g.manager_option(own_manager, 3)) return; + for (size_t s = 0; s < 24; s++) { + const size_t at = size_t(own_manager) * 0x840 + s * 0x58 + 0x44; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + const size_t rec = size_t(own_manager) * 0xB0C + 0x8ac; + rate = uint8_t((int16_t(g.manager_records.at(rec) | g.manager_records.at(rec + 1) << 8) >> 4) + 0x28); + } + bool marking[24] = {}; // local_70: own slots already marking + const SquadRange own_range = squad_range(own), other_range = squad_range(other); + int16_t targets[24]; + uint32_t target_key[24]; + int n = 0; // local_38 + for (size_t s = 0; s < other_range.count; s++) { + const uint16_t slot = g.squad_slots.at(other_range.first + s); + if (!(slot & kSlotInLineup)) continue; + const Player& p = g.players.at(slot & 0x0FFF); + const int position = int(p.w364 & 3); + if (position < 2) continue; + targets[n] = int16_t(s); + target_key[n] = uint32_t(((position - 2) << 6) + int16_t(p.strength(false)) + int(p.w35c >> 21 & 7) * 8 + + int(p.w368 >> 18 & 0x3F) * 4 + int(p.w364 >> 2 & 0x3F) * 8); + n++; + } + if (n == 0) return; + quicksort_by_key(targets, target_key, n); + for (int k = 0; k < n; k++) { + const int bonus = k < 3 ? (3 - k) * 10 : 0; + if (!(100 - chance < rand.range(0, 100) + bonus)) continue; + const int target = targets[k]; // local_34 + int tx = 0, ty = 0; + g.formation_position(other, target, tx, ty); + int16_t candidates[24]; + uint32_t candidate_key[24]; + int m = 0; // local_20 + for (size_t s = 0; s < own_range.count; s++) { + const uint16_t slot = g.squad_slots.at(own_range.first + s); + if (marking[s] || !(slot & kSlotInLineup)) continue; + const Player& p = g.players.at(slot & 0x0FFF); + const int position = int(p.w364 & 3); + if (position != 1 && position != 2) continue; + int ox = 0, oy = 0; + g.formation_position(own, int(s), ox, oy); + candidates[m] = int16_t(s); + candidate_key[m] = uint32_t(int16_t(p.strength(false)) + int(p.w368 >> 8 & 3) * 0x10 + + int16_t((0x19 - std::abs(tx - ox)) + std::abs(ty - oy)) * 0x10); + m++; + } + if (m == 0) return; + quicksort_by_key(candidates, candidate_key, m); + for (int j = 0; j < m; j++) { + if (!(rand.range(0, 100) < rate)) continue; + const int marker = candidates[j]; + if (other_manager >= 0) { + const uint16_t id = g.squad_slots.at(own_range.first + size_t(marker)) & 0x0FFF; + const size_t at = size_t(other_manager) * 0x840 + size_t(target) * 0x58 + 0x46; + g.tactics.at(at) = uint8_t(id), g.tactics.at(at + 1) = uint8_t(id >> 8); + } + if (own_manager >= 0) { + const uint16_t id = g.squad_slots.at(other_range.first + size_t(target)) & 0x0FFF; + const size_t at = size_t(own_manager) * 0x840 + size_t(marker) * 0x58 + 0x44; + g.tactics.at(at) = uint8_t(id), g.tactics.at(at + 1) = uint8_t(id >> 8); + } + marking[marker] = true; + break; + } + } +} + +} // namespace + +void kick_off(GameState& g, std::vector& groups, const MatchdayContext& ctx, WatcomRandom& rand, + GameRandom& game, MinuteReport& report, bool select_sportschau, uint16_t club_threshold) { + // LiveSceneVisible = 1 - CareerSession_DispatchLiveTactic_RuntimeField3, set by the caller of DayCompetitions2 right after the + // matchday setup; MatchdaySetupRuntimeField12 = 0 (no live match chosen yet). + g.live_scene = uint8_t(1 - (g.memory.has(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) ? g.memory.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3) : 0)) != 0; + g.live_matches.clear(); + g.sportschau_selection_available = false; + g.sportschau_club_threshold = club_threshold; + if (select_sportschau) reset_sportschau_selection(g); + for (size_t s = 0; s < kSquadSlotCount && s < g.squad_slots.size(); s++) { + const uint16_t slot = g.squad_slots[s]; + if ((slot & 0x0FFF) != 0x0FFF) g.players.at(slot & 0x0FFF).w364 &= ~0x1000u; // not played yet + } + // tactics board byte 0x10: 0 starts, 0x7f on the bench, 0x7e not in the squad + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const SquadRange range = squad_range(g.manager_teams[k]); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t slot = g.squad_slots.at(s); + if ((slot & 0x0FFF) == 0x0FFF) break; + g.tactics.at(k * 0x840 + (s - range.first) * 0x58 + 0x10) = slot & 0x8000 ? 0 : slot & 0x4000 ? 0x7f : 0x7e; + } + } + for (MatchGroup& grp : groups) { + const int n = grp.matches(); + const int league = int(le32(grp.desc, 0xcc)); + put32(grp.desc, 0xb8, 0); + for (size_t i = 0xbc; i < 0xcc; i++) grp.desc.at(i) = 0; // bookings, sendings-off, crowd, goals (Assign) + grp.records.assign(size_t(n) * 18, 0); + grp.end_minute.assign(size_t(n), 0); + grp.spectators.assign(size_t(n), 0); + uint32_t void_mask = 0; + if (grp.desc.at(0) != 0) { + // cups: no league result bytes; the results of this leg start at 0:0 + grp.results.clear(); + grp.cup_results.assign(size_t(n), 0); + } else { + grp.results.assign(size_t(n), 0); + const size_t at = size_t(league) * 0x17C + size_t(g.league_rounds.at(size_t(league))) * 10; + for (int m = 0; m < n; m++) { + uint8_t& r = g.results.at(at + size_t(m)); + if (r == 0xCC) + r = 0; // 0:0 before kick-off + else + void_mask |= 1u << m; + grp.results[size_t(m)] = r; + } + } + put32(grp.desc, 0xb8, void_mask); + grp.kickoff_void_mask = void_mask; + for (int m = 0; m < n; m++) { + if (void_mask & (1u << m)) continue; + const int home = grp.fixtures.at(size_t(m) * 2), away = grp.fixtures.at(size_t(m) * 2 + 1); + const bool live = select_live_match(g, home, away); + if (!live && select_sportschau) consider_sportschau_fixture(g, grp, home, away, rand); + int forfeit_side = -1; + for (int side = 0; side < 2; side++) { + // the original swaps home and away after each pass + const int t = side ? away : home, opponent = side ? home : away; + const int own_manager = g.manager_of(t), other_manager = g.manager_of(opponent); + if ((own_manager >= 0 || other_manager >= 0) && (other_manager < 0 || g.manager_option(other_manager, 3))) { + const int rate = rand.range(0x46, 0x50); + man_marking(g, own_manager, t, other_manager, opponent, 0x32, rate, rand); + } + const TeamAverage fit = team_average(g, t, 0x1f1, &rand); + if ((t < kLeagueClubCount || t == kNoTeam) && (fit.players & 0xFF) < 8) { + // FinishEvent sets this fixture's local void bit and BuildSideRecords writes + // the awarded 0:2/2:0 score before continuing to the next fixture. + forfeit_side = side; + const int manager = g.manager_of(t); + if (manager >= 0) book_money(g, manager, 200000, true, true); // BookMoney2 + if (g.memory.has(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2)) + g.memory.set8(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2, + uint8_t(g.memory.u8(::bmh::layout::MatchdaySetup_KickOff_RuntimeField + uint32_t(t) * 2) + 1)); + } + } + if (forfeit_side >= 0) { + restore_forfeit_squad(g, home); + restore_forfeit_squad(g, away); + void_mask |= 1u << m; + grp.kickoff_void_mask |= 1u << m; + put32(grp.desc, 0xb8, void_mask); + const int home_goals = forfeit_side == 0 ? 0 : 2; + const int away_goals = forfeit_side == 0 ? 2 : 0; + if (grp.desc.at(0) == 0) { + const size_t at = size_t(league) * 0x17C + + size_t(g.league_rounds.at(size_t(league))) * 10 + size_t(m); + const uint8_t score = uint8_t((home_goals << 4) | away_goals); + g.results.at(at) = score; + grp.results.at(size_t(m)) = score; + } else { + grp.cup_results.at(size_t(m)) = uint16_t((home_goals << 5) | away_goals); + } + continue; + } + const int bits = match_mode_bits(g, grp, ctx, report); + int spectators; + if (g.indoor) + spectators = 10000; + else + spectators = attendance(g, home, away, int16_t(bits), int8_t(grp.desc.at(0x30 + size_t(m))), + grp.desc.at(0x50 + size_t(m)), grp.desc.at(0), game, rand, report); + put32(grp.desc, 0xc4, le32(grp.desc, 0xc4) + uint32_t(spectators)); + grp.spectators[size_t(m)] = uint32_t(spectators); + MatchSetup setup; + setup.home = home; + setup.away = away; + setup.match_index = m; + setup.climate_effect = (grp.desc.at(1) & 2) != 0; + setup.temperature = int8_t(grp.desc.at(0x30 + size_t(m))); + setup.spectators = spectators; + setup.month = ctx.month; + const std::array sides = build_side_records(g, setup, rand, &game); + for (int s = 0; s < 2; s++) + for (int b = 0; b < 9; b++) grp.records[size_t(m) * 18 + size_t(s) * 9 + size_t(b)] = sides[size_t(s)].b[size_t(b)]; + } + } + store_group_descriptors(g, groups); +} + +} // namespace bmh + +namespace bmh { + +std::vector shuffle_manager_order(GameState& g, GameRandom& game) { + constexpr uint32_t kOrder = ::bmh::layout::NextDeskManager; // u16 per manager + const int n = int(g.manager_teams.size()); + std::vector order(static_cast(n)); + for (int i = 0; i < n; i++) order[size_t(i)] = g.memory.has(kOrder) ? g.memory.u16(kOrder + uint32_t(i) * 2) : i; + for (int i = 0; i < n; i++) std::swap(order[size_t(i)], order[size_t(game.range(0, n - 1))]); + if (g.memory.has(kOrder)) + for (int i = 0; i < n; i++) g.memory.set16(kOrder + uint32_t(i) * 2, uint16_t(order[size_t(i)])); + return order; +} + +} // namespace bmh + +namespace bmh { + +Bytes group_descriptor(const GameState& g, size_t index) { + constexpr uint32_t kGroups = ::bmh::layout::MatchdayGroupDescriptors; + Bytes d(kDescriptorSize, 0); + const uint32_t at = kGroups + uint32_t(index) * kDescriptorSize; + if (g.memory.has(at)) + for (size_t i = 0; i < kDescriptorSize; i++) d[i] = g.memory.u8(at + uint32_t(i)); + return d; +} + +void store_group_descriptors(GameState& g, const std::vector& groups, bool with_log) { + constexpr uint32_t kGroups = ::bmh::layout::MatchdayGroupDescriptors; + for (size_t gi = 0; gi < groups.size() && gi < 6; gi++) { + const uint32_t at = kGroups + uint32_t(gi) * kDescriptorSize; + if (!g.memory.has(at)) continue; + const Bytes& d = groups[gi].desc; + auto copy = [&](size_t from, size_t to) { + for (size_t i = from; i < to; i++) g.memory.set8(at + uint32_t(i), d.at(i)); + }; + copy(0, 4); // type, flags, matches + copy(0x10, 0x70); // referees, temperatures, rain + copy(0xb8, 0xcc); // void mask, attendance + copy(0x94, 0x96); // event log entries + // cup groups keep their fixtures in the descriptor (SetupCupGroups) + if (d.at(0) != 0 && !(d.at(1) & 4)) copy(0x88, 0x88 + size_t(d.at(2)) * 4); + if (with_log) g.memory.set16(at + 0x94, uint16_t(groups[gi].log.size())); + // league number, or the guest pointer to the cup table entry + const uint32_t v = le32(d, 0xcc); + g.memory.set32(at + 0xcc, d.at(0) == 0 ? v : v + kGuestDataBase); + } +} + +} // namespace bmh + +namespace bmh { + +namespace { + +// MatchScore (read): the current score of match m as the original reads it, including the +// "not played" markers (0xCC -> 12:12, 0xCCCC -> 6:12). +void raw_score(const GameState& g, const MatchGroup& grp, int m, int& home, int& away) { + if (grp.desc.at(0) == 0) { + const int league = int(le32(grp.desc, 0xcc)); + const uint8_t r = g.results.at(size_t(league) * 0x17C + size_t(g.league_rounds.at(size_t(league))) * 10 + size_t(m)); + home = r >> 4, away = r & 0xF; + } else { + const uint16_t r = grp.cup_results.at(size_t(m)); + home = (r >> 5) & 0x1F, away = r & 0x1F; + } +} + +} // namespace + +void build_pools_coupon(GameState& g, const std::vector& groups, WatcomRandom* rand) { + g.pools_open = true; // PoolsOpenFlag = 0xcc + int n = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && n != 0x16; m++) { + int home = 0, away = 0; + raw_score(g, grp, m, home, away); + if (!((home == 0xc || home == 6) && away == 0xc)) continue; + const int a = uint16_t(team_average(g, grp.fixtures.at(size_t(m) * 2), 0x1ff, rand).value); + const int b = uint16_t(team_average(g, grp.fixtures.at(size_t(m) * 2 + 1), 0x1ff, rand).value); + if (std::abs(a - b) >= 0x12) continue; + for (int s = 0; s < 2; s++) g.memory.set16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(n++) * 2, uint16_t(grp.fixtures.at(size_t(m) * 2 + size_t(s)))); + } + if (n == 0x16) break; + } + g.memory.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(n >> 1)); // CareerSession_DispatchToto_RuntimeField: matches on the coupon +} + +void evaluate_pools_coupon(GameState& g, const std::vector& groups) { + if (!g.pools_open) return; // (PoolsOpenFlag != 0xcc: evaluated already) + g.pools_open = false; + int k = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && k < 0xb; m++) { + if (grp.fixtures.at(size_t(m) * 2) != int(g.memory.u16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(k) * 4))) continue; + int home = 0, away = 0; + match_score(grp, m, home, away); + g.memory.set8(::bmh::layout::MatchdaySetup_EvaluatePoolsCoupon_RuntimeField + uint32_t(k), uint8_t(away < home ? 1 : home == away ? 0 : 2)); + k++; + } + if (k >= 0xb) break; + } + g.memory.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(k)); // CareerSession_DispatchToto_RuntimeField: matches evaluated +} + +void settle_pools_coupon(GameState& g, const std::vector& groups) { + StaticMemory& mem = g.memory; + if (!mem.has(::bmh::layout::Coupon) || !mem.has(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField)) return; + // the coupon's matches among today's (in the order of the coupon, home team at +0) + int k = 0; + for (const MatchGroup& grp : groups) { + for (int m = 0; m < grp.matches() && k < 0xb; m++) + if (grp.fixtures.at(size_t(m) * 2) == int(mem.u16(::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField + uint32_t(k) * 4))) k++; + if (k >= 0xb) break; + } + if (mem.has(::bmh::layout::CareerSession_DispatchToto_RuntimeField)) mem.set8(::bmh::layout::CareerSession_DispatchToto_RuntimeField, uint8_t(k)); + if (k <= 10) return; + static constexpr uint8_t kQuota[12] = {11, 10, 0, 20, 11, 10, 0, 1, 0, 10, 20, 50}; // MatchdaySetupRuntimeField13 + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const uint32_t at = ::bmh::layout::Coupon + uint32_t(m) * 0x14; + if (mem.u8(at + 3) & 0x80) mem.set32(at, 0); + const uint32_t stake = mem.u32(at); + if ((stake & 0x7fffffff) == 0) continue; + if (!book_money(g, int(m), int32_t(stake), false, true)) { + post_composed(g, int(m), message_text(g, ::bmh::layout::MatchdaySetup_SettlePoolsCoupon_TextPointer)); + } else { + int hits = 0; + for (uint32_t i = 0; i < 0xb; i++) + if (mem.u8(at + 8 + i) == mem.u8(::bmh::layout::MatchdaySetup_EvaluatePoolsCoupon_RuntimeField + i)) hits++; + uint32_t win = 0; + if (hits > 8) win = stake * kQuota[hits]; + mem.set32(at + 4, win); + mem.set8(at + 0x13, uint8_t(hits)); + book_money(g, int(m), -int32_t(win), true, true); + } + mem.set32(at, 0); // (also clears the "settled" bit 7 of byte 3 just set) + } +} + +} // namespace bmh diff --git a/src/game/matchday_setup.hpp b/src/game/matchday_setup.hpp new file mode 100644 index 0000000..208dc65 --- /dev/null +++ b/src/game/matchday_setup.hpp @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// Before the first minute of a matchday (BMH.exe V2.24 + supported rule profile patch). +// +// When "Weiter" reaches a day with a calendar event, AdvanceTurn prepares the matchday: +// 1. DayCompetitions2 builds one match group per league playing today (FixturesFromGenerateFixtures): +// fixtures of the next round, the result bytes of that round, and per match the +// weather and the referee (MatchWeather). Every team is then prepared for the match +// (PrepareTeam: cards of this competition, injuries, line-up flags) and gets an +// automatic line-up (Int2 mode 100). CycleManagerOptions advances the human +// managers' option byte 0 to the next enabled setting. +// 2. CurrentMatchday = WatcomRandom(0, 10000); PrepareEvent shuffles the order in which +// the human managers see their pre-match desks (one game draw per manager). +// 3. The matchday driver FinishEvent (called through the supported rule profile wrapper +// MatchdaySetupOperation) starts: "played" flags are cleared, the human tactics boards note who +// starts, every group's unplayed result bytes are set to 0:0 (anything else voids +// the match), and per match the attendance (Attendance) and the side records +// (BuildSideRecords3 + BuildSideRecords2) are computed. +// After that the minute loop (match_engine.hpp) runs. +// +// Ported for league matchdays of computer teams. Cups, indoor tournaments, the winter +// break postponements, human teams in a match (pre-match desk, own stadium, income) and +// Teams with fewer than 8 fit players receive the original 0:2 forfeit award. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// Globals of the original that the preparation reads but that are not part of GameState. +struct MatchdayContext { + int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5: index into the monthly temperature table + int season_day = 0; // DaysIntoSeason: day since 1 July (winter break test) + int weekday = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField6: weekday code of the day (the last DeskDate2 call of the day step) + // RefereeProperties: 50 referees from M3D.MAN; bit 7 marks "already chosen today". + std::vector* referees = nullptr; + // the national team day (DayCompetitions -> national-only flag): AdvanceTurn skips the Bundestrainer + // check of the other days (no take-over, no hand-back) + bool national_team_day = false; +}; + +// The 0xD0-byte descriptor of match group `index` as it is left in memory (block MatchdayGroupDescriptors) from +// the previous matchday: the preparation only overwrites what it needs, so for example +// the referee bytes of matches without referee keep old values. +Bytes group_descriptor(const GameState& g, size_t index); +// Writes the descriptors back (the per-match bytes, void mask, attendance, league/cup). +void store_group_descriptors(GameState& g, const std::vector& groups, bool with_log = false); + +// MatchWeather: temperature (descriptor +0x30), rain (+0x50) and referee (+0x10) of +// match m of a group. +void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand); + +// PrepareTeam: prepares the squad of `team` before a match of a competition of class +// `cls` (MatchEngineRuntimeField9[type]: 0 league, 1-4 cups with their own card counters, 0xFF none). +// `index` is the team's position in the flat fixture list (home 0, away 1, ...). +void prepare_team(GameState& g, int team, int cls, int index); + +// DayCompetitions2(..., 1): builds the match groups of the competitions in `competitions` +// (SavedCompetition) and prepares all teams. Returns the groups in the order of the original. +// DayCompetitions: the competitions of a day from its calendar entry (CompetitionCalendar): the low +// 15 bits, with special entries mapped (0x4001 group -> 0x8000, 0x4002 -> layout field indoor +// tournament, 0x4004 -> layout field, 0x4006 -> national-only flag or nothing) and the four league +// groups 0x1e00 rotating with the season. +uint32_t day_competitions(const GameState& g, uint16_t entry); + +// IndoorTournamentDraw: the draw of an indoor tournament (eight clubs, the host names it). +void indoor_tournament_draw(GameState& g, GameRandom& game, WatcomRandom& rand); +// The part of IndoorTournamentDraw that also runs before the Masters (CupRuntimeField != 0, no draw): +// before the first tournament the Masters points (Cup_AdvanceCup_ExecutableField) and invitations +// (MatchdaySetup_IndoorTournamentDraw_RuntimeField) are cleared; the name becomes "In ", the results of block MatchdayGroupWorkspace 0xCC and +// the played counters of the cup entries 25-29 0. +void indoor_tournament_reset(GameState& g); + +std::vector setup_matchday(GameState& g, uint32_t competitions, const MatchdayContext& ctx, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// MatchdayNeedsManagerDesks / AdvanceTurn: after preparation and manager-order shuffling, +// F6 (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField == 0) admits the whole manager desk loop only if a manager plays. +// Postponed/already played league fixtures do not count. Opening/closing season +// desks, national friendlies and the Source auto-continue latch retain their gates. +// Read-only; callers still simulate an event whose desks are skipped. +bool matchday_needs_manager_desks(const GameState&, uint16_t calendar_entry, + const std::vector&); + +// CycleManagerOptions: option byte 0 of every human manager moves on to the next setting that +// is enabled in the manager record (+0x218, a bit mask of settings 1-8). +void cycle_manager_options(GameState& g); + +// MatchModeBits plus the flags added by BuildSideRecords: the "mode bits" passed to the +// attendance. Bits 0-4 a crowd interest value (per competition type, rising towards the +// end of the league season), 0x20 random spread, 0x80 no league match, 0x100 cup of +// class 1, 0x200 other cups. +int match_mode_bits(const GameState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report); + +// Attendance: attendance of a match. For a human home club also the gate and kiosk +// income, the attendance statistics of its record and a possible riot (message, damage). +// competition_type = byte 0 of the group descriptor (MatchdaySetupRuntimeField14). Bits 0x180 +// select cup gate sharing, including the away human manager's income/statistics. +int attendance(GameState& g, int home, int away, int bits, int temperature, int rain, int competition_type, + GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// PrepareEvent(ManagerCount, NextDeskManager): shuffles the order of the human managers' pre-match +// desks in place - the order of the matchday before is shuffled again, not 0, 1, ... - and +// returns it (manager indices). One game draw per manager: entry i swaps with entry G(0, n - 1). +std::vector shuffle_manager_order(GameState& g, GameRandom& game); + +// The start of FinishEvent up to the first minute: flags, void masks, attendance and side +// records for every match of every group, including the live match choice (AutoLineup) and +// the man marking of human managers (KickOff). Human teams draw from `game` in their +// ratings (team_rating). +void kick_off(GameState& g, std::vector& groups, const MatchdayContext& ctx, WatcomRandom& rand, + GameRandom& game, MinuteReport& report, bool select_sportschau = false, + uint16_t club_threshold = 90); + +} // namespace bmh + +namespace bmh { + +// CurrentMatchday = WatcomRandom(0, 10000), drawn by AdvanceTurn after the preparation (kept +// in the savegame). +inline void draw_matchday_number(GameState& g, WatcomRandom& rand) { + const int v = rand.range(0, 10000); + if (g.memory.has(::bmh::layout::CurrentMatchday)) g.memory.set32(::bmh::layout::CurrentMatchday, uint32_t(v)); +} + +} // namespace bmh + +namespace bmh { + +// BuildPoolsCoupon, at a human manager's pre-match desk: the pools coupon (block DeskActions_SubmitPoolsCoupon_RuntimeField) - up +// to 11 of today's matches between clubs of similar strength (team_average 0x1ff within +// 17); CareerSession_DispatchToto_RuntimeField = their number. +// Teams without a squad (national teams) draw their average from `rand` (TeamRating). +void build_pools_coupon(GameState& g, const std::vector& groups, WatcomRandom* rand = nullptr); + +// EvaluatePoolsCoupon(0) at full time of that matchday: the results of the coupon's matches, +// MatchdaySetup_EvaluatePoolsCoupon_RuntimeField[i] = 1 home win, 0 draw, 2 away win. +void evaluate_pools_coupon(GameState& g, const std::vector& groups); + +// EvaluatePoolsCoupon(1) at the end of the matchday: with 11 matches on the coupon every human +// manager's tip (Coupon + manager * 0x14: stake u32, tips +8..+0x12) is settled - the +// stake is booked (BookMoney2, may fail: "Ihr Tototipp wurde nicht berücksichtigt ..." +// MatchdaySetup_SettlePoolsCoupon_TextPointer), the hits counted (+0x13), from 9 on the stake times the quota +// (MatchdaySetupRuntimeField13: 10, 20, 50) is won (+4) and booked; the stake is cleared. The coupon's +// matches are counted again in the groups of the matchday (CareerSession_DispatchToto_RuntimeField; the outcomes stay +// those read after the second half, PoolsOpenFlag / MatchdaySetup_EvaluatePoolsCoupon_RuntimeField). The toto screen +// it shows (LeagueTableRangeDialog) draws nothing. +void settle_pools_coupon(GameState& g, const std::vector& groups); + +} // namespace bmh diff --git a/src/game/memory.hpp b/src/game/memory.hpp new file mode 100644 index 0000000..cfcd813 --- /dev/null +++ b/src/game/memory.hpp @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The static data of the original (its data object, LE addresses GermanDataSegmentBegin-layout field) as far +// as the savegame stores it. +// +// Many parts of the original work on small global tables that point at each other, e.g. +// the cup table at CupTable whose entries hold pointers to team lists and result arrays in +// other globals. Porting every one of them into a typed field would lose that structure, +// so they are kept here as raw memory addressed like in the original. The pointers stored +// in such tables are guest linear addresses: data address + kGuestDataBase. +// +// Blocks that GameState also decodes into typed fields (squads, players, results, ...) +// must be read and written through those fields; their copies here are not kept current. + +#include +#include +#include +#include +#include +#include + +#include "formats/savestate.hpp" + +namespace bmh { + +// Offset between the LE addresses of the data object and the guest linear addresses the +// original stores in pointers (DOS/4GW loads the data object at relocated data-segment base). +constexpr uint32_t kGuestDataBase = 0x1a2000; + +class StaticMemory { +public: + StaticMemory() = default; + // All non-heap blocks of a savegame. + explicit StaticMemory(const SaveState& save) { + for (const SaveBlock& b : save.blocks()) + if (!b.heap && b.size != 0 && !blocks_.count(b.address)) + blocks_[b.address].assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size); + } + + // A global the savegame does not store (e.g. a work list the original rebuilds before + // use): created zeroed unless it is there already. + void add_block(uint32_t address, size_t size) { + if (!has(address)) blocks_[address].assign(size, 0); + } + + bool has(uint32_t address) const { + auto it = blocks_.upper_bound(address); + if (it == blocks_.begin()) return false; + --it; + return address - it->first < it->second.size(); + } + uint8_t& at(uint32_t address) { + auto it = blocks_.upper_bound(address); + if (it != blocks_.begin()) { + --it; + if (address - it->first < it->second.size()) return it->second[address - it->first]; + } + throw std::out_of_range("static memory: address " + hex(address) + " is not in the savegame"); + } + uint8_t u8(uint32_t a) const { return const_cast(this)->at(a); } + uint16_t u16(uint32_t a) const { return uint16_t(u8(a) | u8(a + 1) << 8); } + uint32_t u32(uint32_t a) const { return uint32_t(u16(a) | uint32_t(u16(a + 2)) << 16); } + void set8(uint32_t a, uint8_t v) { at(a) = v; } + void set16(uint32_t a, uint16_t v) { at(a) = uint8_t(v), at(a + 1) = uint8_t(v >> 8); } + void set32(uint32_t a, uint32_t v) { set16(a, uint16_t(v)), set16(a + 2, uint16_t(v >> 16)); } + // A pointer stored in the original's memory, as an LE data address (0 stays 0). + uint32_t pointer(uint32_t a) const { + uint32_t p = u32(a); + return p == 0 ? 0 : p - kGuestDataBase; + } + void set_pointer(uint32_t a, uint32_t address) { set32(a, address == 0 ? 0 : address + kGuestDataBase); } + +private: + static std::string hex(uint32_t v) { + char b[16]; + std::snprintf(b, sizeof b, "0x%x", v); + return b; + } + std::map> blocks_; +}; + +} // namespace bmh diff --git a/src/game/messages.cpp b/src/game/messages.cpp new file mode 100644 index 0000000..ea4813f --- /dev/null +++ b/src/game/messages.cpp @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/messages.hpp" + +#include +#include + +namespace bmh { + +namespace { + +uint32_t rd32(const std::vector& v, size_t o) { + return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16) | uint32_t(v.at(o + 3)) << 24; +} +void wr32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i)); +} + +} // namespace + +void post_message(GameState& g, int64_t recipients, const std::vector& text) { + std::vector& box = g.mailbox; + if (box.size() < kMailboxEntries * kMailboxEntry) return; // no mailbox loaded + size_t index = 0; + while (index < kMailboxEntries && rd32(box, index * kMailboxEntry) != 0) index++; + size_t at; + if (index == kMailboxEntries) { + // DropOldestMessage: drop the oldest entry, unread ones count as newer + uint32_t best = 0x7FFFFFFF, key = 0; + size_t oldest = 0; + for (size_t k = 0; k < kMailboxEntries; k++) { + const size_t e = k * kMailboxEntry; + if (rd32(box, e + 4) != 0) key = 0xF0000; + key |= uint32_t(box[e + 8]) << 8 | box[e + 9]; + if (key < best) best = key, oldest = k; + } + if (oldest != kMailboxEntries - 1) + std::copy(box.begin() + long((oldest + 1) * kMailboxEntry), box.end(), box.begin() + long(oldest * kMailboxEntry)); + at = (kMailboxEntries - 1) * kMailboxEntry; + box[at] = 0; + } else { + at = index * kMailboxEntry; + } + uint32_t mask; + if (recipients == -1) mask = (0xFFFFFFFFu >> (32 - g.manager_teams.size())) | 0x80000000u; + else if (recipients & 0x80000000) mask = uint32_t(recipients); + else mask = 1u << uint32_t(recipients); + // PostMessage ORs the recipient mask into MailboxRecipientMask. It is a runtime + // global absent from normal FBMs; add_block deliberately keeps it out of + // save serialization while preserving the Source address and bit layout. + g.memory.add_block(::bmh::layout::MailboxRecipientMask, 4); + g.memory.set32(::bmh::layout::MailboxRecipientMask, g.memory.u32(::bmh::layout::MailboxRecipientMask) | mask); + wr32(box, at, mask); + wr32(box, at + 4, 0); + const uint16_t date = uint16_t(std::min(g.date, 0xFFFF)); + box[at + 8] = uint8_t(date >> 8); + box[at + 9] = uint8_t(date); + for (size_t i = 0; i < kMailboxText; i++) box[at + 10 + i] = i < text.size() ? text[i] : 0; +} + +void post_text(GameState& g, int64_t recipients, size_t text_id) { + if (!g.texts) return; + post_message(g, recipients, g.texts->raw(text_id, kMailboxText)); +} + +void post_composed(GameState& g, int64_t recipients, const std::string& text) { + post_message(g, recipients, std::vector(text.begin(), text.end())); +} + +int compare_mailbox(const std::vector& ours, const std::vector& theirs, std::string* first) { + int diffs = 0; + for (size_t k = 0; k < kMailboxEntries && (k + 1) * kMailboxEntry <= std::min(ours.size(), theirs.size()); k++) { + const size_t e = k * kMailboxEntry; + bool same = std::equal(ours.begin() + long(e), ours.begin() + long(e + 10), theirs.begin() + long(e)); + for (size_t i = 10; i < kMailboxEntry && same; i++) { + if (ours[e + i] != theirs[e + i]) same = false; + if (theirs[e + i] == 0) break; // end of the text + } + if (rd32(theirs, e) == 0 && rd32(ours, e) == 0) same = true; // both empty + if (!same) { + if (diffs == 0 && first) { + char b[64]; + std::snprintf(b, sizeof b, "entry %zu", k); + *first = b; + } + diffs++; + } + } + return diffs; +} + +} // namespace bmh + +namespace bmh { + +std::string message_text(const GameState& g, uint32_t pointer_variable) { + return g.texts ? (*g.texts)[text_id(pointer_variable)] : std::string(); +} + +std::string message_text_following(const GameState& g, uint32_t pointer_variable) { + if (!g.texts) return {}; + const size_t id = text_id(pointer_variable); + if (id >= g.texts->offsets.size()) return {}; + const auto& bytes = g.texts->blob; + size_t at = g.texts->offsets[id]; + if (at >= bytes.size()) return {}; + while (at < bytes.size() && bytes[at] != 0) ++at; + if (at == bytes.size()) return {}; + ++at; + std::string text; + while (at < bytes.size() && bytes[at] != 0) text.push_back(char(bytes[at++])); + return text; +} + +std::string format_number(const GameState& g, int32_t value, int flags) { + if (flags & 0x100) { + // ConvertCurrency: currency conversion (1/1 unless the savegame says otherwise) + const int32_t mul = g.memory.has(::bmh::layout::CurrencyMultiplier) ? int32_t(g.memory.u32(::bmh::layout::CurrencyMultiplier)) : 1; + const int32_t div = g.memory.has(::bmh::layout::CurrencyDivisor) ? int32_t(g.memory.u32(::bmh::layout::CurrencyDivisor)) : 1; + if (div != 0) value = value * mul / div; + } + // FormatGroupedDigits: digits from the right; with grouping (bit 0x40 clear) a dot before the + // 4th, 8th and 12th character; padded to the width (bits 0-5), leading blanks for the + // dots a wide field reserves + const bool group = !(flags & 0x40); + const int width = flags & 0x3F; + int blanks = group && width > 3 ? (width - 4) / 3 + 1 : 0; + const bool negative = value < 0; + uint32_t v = negative ? uint32_t(-int64_t(value)) : uint32_t(value); + std::string reversed; + int dots = 0; + while (v != 0) { + const size_t n = reversed.size(); + if (group && (n == 3 || n == 7 || n == 11)) reversed.push_back('.'), blanks--, dots++; + reversed.push_back(char('0' + v % 10)); + v /= 10; + } + if (!group) blanks = 0; + while (int(reversed.size()) < width + dots - (negative ? 1 : 0)) reversed.push_back(reversed.empty() ? '0' : '%'); + for (int i = 0; i < blanks; i++) reversed.push_back(' '); + if (negative) reversed.push_back('-'); + std::string s(reversed.rbegin(), reversed.rend()); + if (flags & 0x100) { + // FLTD FormatAmount uses the pound prefix at CurrencyPrefixText. + if (g.currency_suffix == " &") s = "& " + s; + else s += g.currency_suffix; // CurrencySuffixText + } + return s; +} + +std::string format_amount(const GameState& g, int32_t value) { return format_number(g, value, 0x101); } + +} // namespace bmh diff --git a/src/game/messages.hpp b/src/game/messages.hpp new file mode 100644 index 0000000..9606a82 --- /dev/null +++ b/src/game/messages.hpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// The managers' mailbox (heap block *ManagerMailbox, saved in the savegame). +// +// 40 entries of 0xA0 bytes (PostMessage): +// +0x00 u32 recipients: bit n = human manager n, bit 31 = a general message +// +0x04 u32 read by (bit per manager) +// +0x08 date (CalendarDay) as big-endian u16 +// +0x0a 0x96 bytes of text, copied blindly from the source - for texts taken straight +// from TEXTD.BLK the following texts come along; for composed messages the rest +// of the caller's buffer (not reproducible, see compare_mailbox) +// When the box is full the oldest entry (read ones first) is dropped (DropOldestMessage). + +#include +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +constexpr size_t kMailboxEntries = 40; +constexpr size_t kMailboxEntry = 0xA0; +constexpr size_t kMailboxText = 0x96; + +// PostMessage. recipients: a manager index, -1 = all managers, or a mask with bit 31 set. +void post_message(GameState& g, int64_t recipients, const std::vector& text); +// A text of TEXTD.BLK as the original posts it (0x96 bytes from its start). +void post_text(GameState& g, int64_t recipients, size_t text_id); +// A composed message (only the text itself is known; the rest of the entry is zero). +void post_composed(GameState& g, int64_t recipients, const std::string& text); + +// Differences between two mailboxes, comparing the text of each entry only up to its NUL +// (the bytes after it may be stack contents of the original). +int compare_mailbox(const std::vector& ours, const std::vector& theirs, std::string* first = nullptr); + +} // namespace bmh + +namespace bmh { + +// Text id of a pointer variable of the text table TextPointerTable (e.g. Weekly_AdvertisingOffers_TextPointer). +constexpr size_t text_id(uint32_t pointer_variable) { return (pointer_variable - ::bmh::layout::TextPointerTable) / 4; } + +} // namespace bmh + +namespace bmh { + +// Text of a pointer variable of the text table (TEXTD.BLK), empty without texts. +std::string message_text(const GameState& g, uint32_t pointer_variable); +// The next NUL-delimited string in the same loaded text block; empty if absent. +std::string message_text_following(const GameState& g, uint32_t pointer_variable); + +// Contract warning loaded from the selected game image. +inline std::string kContractEndsSoonText; +inline std::string kMastersQualificationText; +inline std::string kMastersWinnerText; +inline std::string kIndoorInvitationText; +inline std::string kChampionshipBonusText; +inline std::string kFriendlyPayerPrefixText; + +// FormatNumber(buf, value, 0x101, ""): an amount of money as the messages show it: the +// value converted with CurrencyMultiplier / CurrencyDivisor, digits grouped by dots, then " EU". +std::string format_amount(const GameState& g, int32_t value); + +// FormatNumber(buf, value, flags, ""): bits 0-5 the field width, bit 0x40 no dot grouping, +// bit 0x100 an amount of money (converted, " EU" appended). +std::string format_number(const GameState& g, int32_t value, int flags); + +} // namespace bmh diff --git a/src/game/month.cpp b/src/game/month.cpp new file mode 100644 index 0000000..718bdb7 --- /dev/null +++ b/src/game/month.cpp @@ -0,0 +1,1007 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/month.hpp" +#include "game/trace.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "game/lineup.hpp" +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/prediction.hpp" +#include "game/schedule.hpp" +#include "game/season.hpp" +#include "game/weekly.hpp" +#include "game/human_buyer_sale.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; +constexpr uint32_t kListEntry = 0x58; +constexpr int kPoolFirst = 0xb70; // CareerRuntimeField: the transfer list (40 slots + 4) +constexpr int kFreeAgents = 0xb9c; // CareerRuntimeField2: free agents (80 slots) +constexpr int kForeignAgents = 0xbec; // MonthRuntimeField: foreign free agents (20 slots) +constexpr int kPoolEnd = 0xc00; // LargeSquadClubCount +constexpr int kBigSquadClubs = 90; // TeamsWithSquads +constexpr int kLeagueClubs = 0x8a; // CareerSession_DispatchLineup_RuntimeField + +// MonthRuntimeField2: development steps by strength / 10; the ten bytes after it (PlayerCard_PlayerCardMarketValue_RuntimeField) +// are the extra value above 500 points. +constexpr uint8_t kDevelopment[20] = {6, 6, 6, 5, 5, 5, 4, 4, 3, 1, 10, 15, 20, 30, 40, 45, 55, 75, 85, 95}; +// BalancePlanRuntimeField5: value of the facilities (maintenance per month), u16 per facility. +constexpr uint16_t kFacilityValue[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; +// BalancePlanRuntimeField6: monthly income of facilities 0-5 per level. +constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000}; +// MonthRuntimeField3: share of the new list entries per kind (free agents, big clubs, foreign +// agents, small clubs), percent. +constexpr int16_t kListShare[4] = {47, 35, 10, 8}; +// MonthRuntimeField4 / MonthRuntimeField5: players a club wants per position (big / small squads). +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; + +uint32_t rd32(const std::vector& v, size_t o) { + return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16) | uint32_t(v.at(o + 3)) << 24; +} +void wr32(std::vector& v, size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i)); +} +void add32(std::vector& v, size_t o, int32_t x) { wr32(v, o, rd32(v, o) + uint32_t(x)); } + +// BoughtEntry: index + 1 of a player in the table of players bought for later / on loan +// (Career_RemoveJoinLoans_RuntimeField), 0 if none. +int bought_entry(const GameState& g, int player) { + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xFFF) == player) return k + 1; + } + return 0; +} + +// PlayerOnTransferListFirstPoolSlots: index + 1 of the list entry of the player in an absolute squad slot (the +// first 44 pool slots), 0 if he is not on the list. +int list_index(const GameState& g, int slot) { + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + for (int s = kPoolFirst; s < kPoolFirst + 0x2c; s++) + if ((g.squad_slots[size_t(s)] & 0xFFF) == player) return s - kPoolFirst + 1; + return 0; +} + +// FirstFreeSlotSquad(start, count): first empty squad slot from `start`, -1 if none. +int free_slot(const GameState& g, int start, int count) { + for (int s = start; s < start + count && s < int(g.squad_slots.size()); s++) + if (g.squad_slots[size_t(s)] == 0xFFF) return s; + return -1; +} + +// ListPlayer: puts the player in an absolute squad slot on the transfer list: the first +// free list slot, asking price and demand percentages, 5-8 weeks, the market value; human +// managers with a matching search profile are told. +bool list_player(GameState& g, int slot, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + if (bought_entry(g, player) != 0) { + report.fail("transfer list: the player is bought for later (internal error 0x38)"); + return false; + } + if (list_index(g, slot) != 0) { + report.fail("transfer list: the player is listed already (ListPlayer message box)"); + return false; + } + // (the original passes 0xb70 + 0x28 as the count: the search runs on past the list) + const int free = free_slot(g, kPoolFirst, kPoolFirst + 0x28); + if (free == -1) return false; // message box MonthRuntimeField6 + if (free >= kPoolFirst + 0x2c) { + report.fail("transfer list: the free slot lies beyond the list (the original overwrites memory)"); + return false; + } + g.squad_slots[size_t(free)] = uint16_t(player); + const uint32_t e = kTransferList + uint32_t(free - kPoolFirst) * kListEntry; + if (slot < kPoolFirst) { + const int seller = slot_team(slot); + uint16_t field = uint16_t(seller); + mem.set16(e + 8, field); + if (g.manager_of(seller) >= 0) mem.set8(e + 9, uint8_t(mem.u8(e + 9) | 0x80)); + mem.set8(e + 0x54, uint8_t(rand.range(0x4b, 0x7a))); + mem.set8(e + 0x55, uint8_t(rand.range(0x5c, 100))); + if (seller >= kBigSquadClubs) mem.set8(e + 0x54, uint8_t(mem.u8(e + 0x54) + rand.range(5, 0xf))); + } else { + mem.set16(e + 8, 0xFFF); + mem.set8(e + 0x54, uint8_t(rand.range(0x46, 0x69))); + mem.set8(e + 0x55, uint8_t(rand.range(0x3c, 0x60))); + } + mem.set8(e + 0x56, uint8_t(rand.range(5, 8))); + uint32_t fee = 0, salary = 0; + market_value(g, slot, 0, mem.u8(e + 0x54), fee, salary, 1, 0, rand); + mem.set32(e + 0x2c, fee); + mem.set32(e + 0x30, salary); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + for (size_t m = 0; m < g.manager_teams.size(); m++) search_profile_news(g, int(m), e, g.squad_slots[size_t(free)]); + return true; +} + +// PickFreeAgent(from, to): a random free agent in the pool slots from..to-1 who is not on +// the list and not bought for later. +int pick_free_agent(const GameState& g, int from, int to, WatcomRandom& rand, MinuteReport& report) { + std::vector slots; + for (int s = from; s < to; s++) { + const int p = g.squad_slots.at(size_t(s)) & 0xFFF; + if (p != 0xFFF && list_index(g, s) == 0 && bought_entry(g, p) == 0) slots.push_back(s); + } + if (slots.empty()) { + report.fail("transfer list: no free agent (internal error 0x26)"); + return -1; + } + return slots[size_t(rand.range(0, int(slots.size()) - 1))]; +} + +// InPseudoSquad: the player of a slot also plays in the squad of the pseudo club 0x165. +bool in_pseudo_squad(const GameState& g, int slot) { + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const SquadRange r = squad_range(kNoTeam); + for (size_t s = r.first; s < r.first + r.count; s++) + if ((g.squad_slots[s] & 0xFFF) == player) return true; + return false; +} + +// Int5(first, last): a computer club (every second one, starting alternately at the +// first or second, MonthRuntimeField7) with too many goalkeepers or too many players in a line +// puts one of them on the list. With no club found in first..last the search is repeated +// over the big clubs. +void list_club_player(GameState& g, int first, int last, WatcomRandom& rand, MinuteReport& report) { + const int8_t* wanted = first < kBigSquadClubs ? kWantedBig : kWantedSmall; // Attempt + for (;;) { + int16_t teams[138]; + uint32_t keys[138]; + int n = 0; // local_14 + g.list_toggle = g.list_toggle + 1 == 2 ? 0 : g.list_toggle + 1; + int best_line = 0; // local_1c, keeps its value between the clubs + for (int team = first + g.list_toggle; team < last; team += 2) { + if (g.manager_of(team) >= 0) continue; + const SquadRange range = squad_range(team); + int8_t count[4] = {0, 0, 0, 0}; // local_50 + const int players = int16_t(squad_count(g, team, 3)); + for (int s = 0; s < players; s++) { + const int p = g.squad_slots.at(range.first + size_t(s)) & 0xFFF; + if (p != 0xFFF) count[g.players.at(size_t(p)).w364 & 3]++; + } + int key_base = 0, line = 0; + bool add = false; + if (rand.range(0, 1) + 2 < count[0]) { + // three or four goalkeepers + line = 0; + key_base = count[0] + 100; + add = true; + } else if (players > 0xd) { + const int flags = (g.team_flags.at(size_t(team)) >> 0xc) & 3; + if (rand.range(0, flags * 2 + 2) != 0) { + int8_t most = 0; // local_28 + for (int k = 1; k < 4; k++) { + const int8_t over = int8_t(count[k] - wanted[k]); + if (most < over) most = over, best_line = k; + } + int chosen = best_line; + if (most == 0) chosen = rand.range(1, 3); + key_base = most * 8; + const int8_t room = int8_t(range.count - ((team < kBigSquadClubs ? 1 : 0) + 2)); + if (room < players) key_base += (players - room) * 4; + line = chosen; + add = true; + } + } + if (add) { + const int a = rand.range(0, 5), b = rand.range(0, 5); + keys[n] = uint32_t((key_base + a - b) * 4 + int8_t(line)); + teams[n] = int16_t(team); + n++; + } + } + int pick = 0x8a; // sVar11 + int slot = -1; // unaff_EDI: the slot tried last + if (n != 0) { + quicksort_by_key(teams, keys, n); + for (pick = 0; pick < n; pick++) { + const int team = teams[pick]; + const SquadRange range = squad_range(team); + const int players = int16_t(squad_count(g, team, 2)); + const int line = int(keys[pick] & 3); + int tries = 0; + bool again; + do { + slot = int(range.first) + rand.range(0, players - 1); + const int p = g.squad_slots.at(size_t(slot)) & 0xFFF; + const bool taken = bought_entry(g, p) != 0 || list_index(g, slot) != 0; + tries++; + again = int(g.players.at(size_t(p)).w364 & 3) != line || in_pseudo_squad(g, slot) || taken; + } while (tries < 0x23 && again); + if (tries < 0x23) break; + } + // (when no club had a fitting player the slot tried last is listed all the same) + } + if (pick < 0x8a) { + list_player(g, slot, rand, report); + return; + } + if (first == 0) { + report.fail("transfer list: no club to take a player from (internal error 0x28)"); + return; + } + first = 0; + last = kBigSquadClubs; + } +} + +// CareerFirstSteps: new players on the transfer list. The number depends on how full the list +// is (at most 37 entries); free agents of the pool are preferred while there are many. +void new_list_entries(GameState& g, WatcomRandom& rand, MinuteReport& report) { + uint8_t count[5] = {0, 0, 0, 0, 0}; // local_18: listed, free agents, foreign, listed of both + for (int s = kPoolFirst; s < kPoolEnd; s++) { + if (g.squad_slots.at(size_t(s)) == 0xFFF) continue; + if (!(s < kPoolFirst + 0x28 || kPoolFirst + 0x2c <= s)) continue; + const int cls = s < kFreeAgents ? 0 : s < kForeignAgents ? 1 : 2; + count[cls]++; + if (cls != 0 && list_index(g, s) != 0) count[cls + 2]++; + } + uint8_t add[4] = {0, 0, 0, 0}; // local_10 + const int r = rand.range(2, 0x16); + uint8_t n = uint8_t(r); + if (count[0] + int8_t(r) >= 0x26) { + n = uint8_t(0x25 - count[0]); + if (int8_t(n) <= 0) return; + } + count[1] = uint8_t(count[1] - count[3]); + count[2] = uint8_t(count[2] - count[4]); + for (int16_t u = count[1]; n != 0 && u > 0x36; u--) n--, add[0]++; + for (int16_t u = count[2]; n != 0 && u > 0xe; u--) n--, add[2]++; + for (int k = 0; k < 4; k++) add[k] = uint8_t(add[k] + int8_t(kListShare[k] * int8_t(n) / 100)); + if (count[1] < add[0]) { + add[1] = uint8_t(add[1] + ((add[0] - count[1]) >> 1)); + add[0] = count[1]; + } + if (count[2] < add[2]) { + add[3] = uint8_t(add[3] + ((add[2] - count[2]) >> 1)); + add[2] = count[2]; + } + int8_t total = 0; + for (int k = 0; k < 4; k++) total = int8_t(total + add[k]); + if (total < 4) add[1] = uint8_t(add[1] + rand.range(2, 4)); + if (add[3] == 0 && add[1] != 0 && rand.range(0, 10) == 5) add[3]++, add[1]--; + // (MonthRuntimeField8, a debug switch for club players only, is 0) + for (int k = 0; k < 4 && !report.unsupported; k++) { + uint8_t left = add[k]; + if (left == 0) continue; + switch (k) { + case 0: + case 2: + while (left != 0 && !report.unsupported) { + const int slot = k == 0 ? pick_free_agent(g, kFreeAgents, kForeignAgents, rand, report) + : pick_free_agent(g, kForeignAgents, kPoolEnd, rand, report); + if (slot < 0) return; + if (list_player(g, slot, rand, report)) left--; + } + break; + case 1: + while (left-- != 0 && !report.unsupported) list_club_player(g, 0, kBigSquadClubs, rand, report); + break; + case 3: + while (left-- != 0 && !report.unsupported) list_club_player(g, kBigSquadClubs, kLeagueClubs, rand, report); + break; + } + } +} + +// Loaned players whose time is up go back to their clubs (part of DayStepRest2). +void return_loans(GameState& g, WatcomRandom& rand, GameRandom* game, MinuteReport& report) { + StaticMemory& mem = g.memory; + for (int s = 0; s < kPoolFirst && !report.unsupported; s++) { + const int player = g.squad_slots.at(size_t(s)) & 0xFFF; + if (player == 0xFFF) continue; + const int k = bought_entry(g, player) - 1; + if (k < 0) continue; + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + const int owner = int(e >> 12 & 0x3FF), club = int(e >> 22 & 0x3FF); // local_30, local_28 + const int owner_manager = g.manager_of(owner); + const int borrower_manager = g.manager_of(club); + // Human owners have a saved tactics-board row in ClubInfo_FormatError_RuntimeField and a matching + // player ID/manager in Career_CareerManagersEnd_RuntimeField/ClubInfo_FormatError_RuntimeField2 (Fail). Restore it on expiry; + // AI owners have no snapshot. Stage the complete return so malformed state + // or a failed lineup cannot lose the loan ledger first. + if (owner_manager >= 0 || borrower_manager >= 0) { + const uint8_t remaining = mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k)); + if (remaining != 1) { + // Source decrements an unsigned byte and returns only when the + // decremented byte is zero (DayStepRest2). A malformed/stale zero + // therefore wraps to 0xff instead of expiring immediately. + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), uint8_t(remaining - 1)); + continue; + } + if ((owner_manager >= 4) || (owner_manager >= 0 && + (!mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b) || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager))))) { + report.fail("month change: human-owner loan record is incomplete"); + return; + } + int snapshot_slot = -1; + if (owner_manager >= 0) { + for (int i = 0; i < 12; ++i) { + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2) == uint16_t(player) && + mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(i)) == uint8_t(owner_manager)) { + snapshot_slot = i; + break; + } + } + } + const SquadRange owner_range = squad_range(owner); + const int owner_slot = free_slot(g, int(owner_range.first), int(owner_range.count)); + const SquadRange borrower_range = squad_range(club); + bool borrower_has_player = false; + for (size_t i = 0; i < borrower_range.count; ++i) + if ((g.squad_slots.at(borrower_range.first + i) & 0x0fff) == player) borrower_has_player = true; + if ((owner_manager >= 0 && snapshot_slot < 0) || owner_slot < 0 || !borrower_has_player || + (owner_manager >= 0 && size_t(owner_manager) * kBoard + + size_t(owner_range.count) * kBoardSlot > g.tactics.size())) { + report.fail("month change: human-owner loan cannot be restored safely"); + return; + } + if (borrower_manager >= 0 && !g.loan_return_screen) { + report.fail("month change: expiring human-borrower loan needs its Source return dialog owner"); + return; + } + GameState staged = g; + try { + staged.memory.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), 0); + staged.memory.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0); + staged.squad_slots.at(size_t(owner_slot)) = uint16_t(player); + if (!remove_from_seller(staged, club, player, report)) return; + if (owner_manager >= 0) { + const size_t board = size_t(owner_manager) * kBoard + + size_t(owner_slot - int(owner_range.first)) * kBoardSlot; + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(snapshot_slot) * uint32_t(kBoardSlot); + for (size_t b = 0; b < kBoardSlot; ++b) + staged.tactics.at(board + b) = staged.memory.u8(snapshot + uint32_t(b)); + staged.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(snapshot_slot) * 2, 0x0fff); + const uint8_t count = staged.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager)); + if (count == 0) { + report.fail("month change: human-owner loan count is inconsistent"); + return; + } + staged.memory.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager), uint8_t(count - 1)); + } + // DayStepRest2 posts the return notice to whichever owner/borrower + // managers exist. + const std::string notice = message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer) + staged.player_name(player) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer2) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer3) + staged.club_name(club) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer4) + staged.club_name(owner) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer5); + if (borrower_manager >= 0) { + const int keep = staged.loan_return_screen(staged, borrower_manager, + notice + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer6)); + if (keep < 0) { + report.fail("month change: human-borrower loan return dialog stopped"); + return; + } + if (keep != 0) { + // DayStepRest2 makes the borrower the active manager before + // RowWhose/Range2. The two W(90,100) draws occur even + // when all four special offer slots are occupied. + staged.memory.set8(::bmh::layout::ActiveManager, uint8_t(borrower_manager)); + int offer = 0; + while (offer < 4 && staged.memory.u32(::bmh::layout::OfferSlots + uint32_t(offer) * 4) != 0xffffffffu) + ++offer; + if (offer < 4 && (!game || !staged.loan_return_offer_screen)) { + report.fail("month change: OpenTransferEditor return-offer editor has no typed runtime owner"); + return; + } + WatcomRandom offer_rand = rand; + std::optional offer_game; + if (game) offer_game = *game; + const int percent = offer_rand.range(90, 100); + const int demand = offer_rand.range(90, 100); + if (offer < 4) { + const uint32_t entry = kTransferList + uint32_t(40 + offer) * kListEntry; + uint16_t team_word = uint16_t(owner); + if (owner_manager >= 0) team_word |= 0x8000; + staged.memory.set16(entry + 8, team_word); + for (int bid = 0; bid < 4; ++bid) + staged.memory.set16(entry + uint32_t(bid) * 2, 0xffff); + staged.memory.set8(entry + 0x54, uint8_t(percent)); + staged.memory.set8(entry + 0x55, uint8_t(demand)); + uint32_t fee = 0, salary = 0; + market_value(staged, owner_slot, 0, uint8_t(percent), fee, salary, 1, 0, offer_rand); + staged.memory.set32(entry + 0x2c, fee); + staged.memory.set32(entry + 0x30, salary); + const int source_slot = kPoolFirst + 40 + offer; + staged.squad_slots.at(size_t(source_slot)) = uint16_t(player); + staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4, + uint32_t(player) * 0x400 + uint32_t(borrower_manager)); + // A modal may replace staged (and its hook) while paused. + // Own the active callable until the synchronous invocation returns. + const auto present_return_offer = staged.loan_return_offer_screen; + const int submitted = present_return_offer(staged, *offer_game, offer_rand, + borrower_manager, source_slot, 40 + offer, HumanBuyerSaleHooks{}); + if (submitted < 0) { + report.fail("month change: OpenTransferEditor return-offer editor stopped"); + return; + } + // The original month caller performs this cleanup only + // after OpenTransferEditor has returned from the actual editor. + staged.squad_slots.at(size_t(kPoolFirst + 40 + offer)) = 0x0fff; + staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4, 0xffffffffu); + } + rand = offer_rand; + if (game && offer_game) *game = *offer_game; + } + } + std::string return_notice = notice; + if (borrower_manager >= 0) { + const SquadRange returned_borrower_range = squad_range(club); + for (size_t i = 0; i < returned_borrower_range.count; ++i) { + if ((staged.squad_slots.at(returned_borrower_range.first + i) & 0x0fff) == player) { + return_notice += message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer7) + staged.club_name(club) + + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer8); + break; + } + } + } + uint32_t managers = 0x80000000u; + if (borrower_manager >= 0) managers = 1u << borrower_manager; + if (owner_manager >= 0) managers |= 1u << owner_manager; + post_composed(staged, int64_t(managers), return_notice); + auto_lineup(staged, owner, owner_manager >= 0 ? 0xe4 : 100); + auto_lineup(staged, club, borrower_manager >= 0 ? 0xe4 : 100); + } catch (const std::exception&) { + report.fail("month change: human-owner loan cannot be restored safely"); + return; + } + g = std::move(staged); + continue; + } + const uint8_t months = uint8_t(mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k)) - 1); + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), months); + if (months != 0) continue; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0); + const SquadRange range = squad_range(owner); + const int slot = free_slot(g, int(range.first), int(range.count)); + if (slot == -1) { + report.fail("month change: no room for a returning player (internal error 0x2e)"); + return; + } + g.squad_slots[size_t(slot)] = uint16_t(player); + if (!remove_from_seller(g, club, player, report)) return; + lineup_after_transfer(g, owner); + lineup_after_transfer(g, club); + } +} + +// OpenBMH deviates from the original: omits the two discontinued youth-group cost categories from monthly accounts. +// OriginalFinancePreview(1): the month's expenses of a human manager: facility maintenance +// (BMHExeXa), record +0x854/+0x858, the wages of the squad (MonthlyPay with flags +// 14), the six running costs of Spending (the youth work capped per league by the +// supported rule profile patch MonthlyExpenses, which also drops the youth groups 0 and 2) and the debt +// service (+0x179 x 1000); each booked in the statistics. +int32_t monthly_expenses(GameState& g, int m) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + int32_t sum = 0; + for (int i = 0; i < 0xe; i++) sum += kFacilityValue[i]; + for (int i = 0xe; i < 0x16; i++) sum += (r.at(rec + 0x2e + size_t(i)) & 7) * kFacilityValue[i]; + add32(r, rec + 0x87c, sum); + for (int k = 1; k < 3; k++) { + const int32_t v = int32_t(rd32(r, rec + 0x850 + size_t(k) * 4)); + add32(r, rec + 0x890 + size_t(k) * 4, v); + sum += v; + } + // MonthlyPay(manager, 14): salaries (+0x50) and bonus bases (+0x4e) of the board + int32_t wages = 0; + uint32_t bonus = 0; + for (size_t s = 0; s < 24; s++) { + const size_t slot = size_t(m) * kBoard + s * kBoardSlot; + if (g.tactics.at(slot + 0x3d) == 0xFF) continue; + bonus = uint32_t(g.tactics.at(slot + 0x4e) | (g.tactics.at(slot + 0x4f) & 0x7F) << 8); + const int32_t salary = int32_t(rd32(g.tactics, slot + 0x50)); + add32(r, rec + 0x338, salary); + add32(r, rec + 0x33c, int32_t(bonus)); + wages += salary + int32_t(bonus); + } + sum += wages; + for (int k = 0; k < 6; k++) { + int32_t v = int32_t(g.memory.u32(::bmh::layout::Spending + uint32_t(m) * 0x24 + uint32_t(k) * 4)); + // OpenBMH deviates from the original: omits the two discontinued youth-group cost categories from monthly accounts. +// MonthlyExpenses (supported rule profile patch): the two other youth groups (items 0 and 2) cost + // nothing any more, whatever the saved value + if (k == 0 || k == 2) v = 0; + if (k == 1 && v != 0) { + // TeamLeague3: the limit of the league (1.5 M, 1 M, 580000, 280000); the full + // limit is paid while +0x880 is below it, nothing after + const int league = team_league(g.manager_teams.at(size_t(m))); + const uint32_t limit = league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000; + v = rd32(r, rec + 0x880) < limit ? int32_t(limit) : 0; + } + if (k >= 3 && k <= 5) add32(r, rec + 0x878 + size_t(k) * 4, v); + else add32(r, rec + 0x880, v); + sum += v; + } + const int debt = r.at(rec + 0x179); + if (debt != 0) { + add32(r, rec + 0x8a0, debt * 1000); + sum += debt * 1000; + } + return sum < 0 ? 0 : sum; +} + +// FinanceTotalsFromGame3(1): the month's income: facilities (FacilityIncome) and the 16 advertising +// contracts (record +0xa34), booked in the statistics. +int32_t monthly_income(GameState& g, int m) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + int32_t sum = 0; + for (int k = 0; k < 6; k++) { + const uint8_t v = r.at(rec + size_t(k)); + if (v == 0) continue; + const int level = k == 0 ? ((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + sum += level * kFacilityIncome[k]; + } + add32(r, rec + 0x86c, sum); + for (int k = 0; k < 16; k++) { + const int32_t v = int32_t(rd32(r, rec + 0xa34 + size_t(k) * 0xc)); + add32(r, rec + (k < 14 ? 0x860 : k == 14 ? 0x85c : 0x864), v); + sum += v; + } + return sum; +} + +// The monthly bookkeeping of the players on a human manager's tactics board. +void board_month(GameState& g, int m, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + std::vector& r = g.manager_records; + const size_t rec = size_t(m) * kRecord; + const SquadRange range = squad_range(g.manager_teams.at(size_t(m))); + auto board = [&](int s) { return size_t(m) * kBoard + size_t(s) * kBoardSlot; }; + // the value history has 12 months; when it is full it moves on by one + int month = r.at(rec + 0x286); // local_24 + if (month < 0xc) { + r.at(rec + 0x286) = uint8_t(month + 1); + } else { + for (int s = 0; s < 24; s++) { + if (g.squad_slots.at(range.first + size_t(s)) == 0xFFF) continue; + for (int k = 0; k < 3; k++) { + const size_t at = board(s) + 0x19 + size_t(k) * 0xc; + std::copy(g.tactics.begin() + long(at + 1), g.tactics.begin() + long(at + 0xc), g.tactics.begin() + long(at)); + } + } + month = 0xb; + } + for (int s = 0; s < 24; s++) { + // (a player who leaves closes the gap: the same row is looked at again, or after the + // contracts screen all rows from the first one - those done are marked 0x80) + next_player: + const size_t b = board(s); + const int player = g.squad_slots.at(range.first + size_t(s)) & 0xFFF; + if (player == 0xFFF || (g.tactics.at(b + 0xb) & 0x80)) continue; + g.tactics.at(b + 0xb) |= 0x80; + if (rand.range(0, 0xb) == 0) { + const uint32_t limit = uint32_t(rand.range(0x11, 0x17)); + if (limit < (g.players.at(size_t(player)).w364 >> 21 & 0x1F) && !(g.tactics.at(b + 0xb) & 0x20)) { + // he wants to end his career at the end of his contract + g.tactics.at(b + 0xb) |= 0x20; + post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer)); + } + } + g.tactics.at(b + 0x11)++; + if (rand.range(0, 6) == 0) { + // the mood (+0x0d) drifts back towards 100 + const int d = std::abs(100 - g.tactics.at(b + 0xd)); + if (int16_t(d) != 0) { + int16_t step = int16_t(d) < 0xb ? 1 : 10; + if (g.tactics.at(b + 0xd) > 100) step = int16_t(-step); + g.tactics.at(b + 0xd) = uint8_t(std::clamp(step + g.tactics.at(b + 0xd), 0, 0xff)); + } + } + if (g.tactics.at(b + 0x43) != 0) { + g.tactics.at(b + 0x43)--; + if ((g.tactics.at(b + 0x43) & 0x3f) == 0) g.tactics.at(b + 0x43) = 0; + } + if (g.tactics.at(b + 0xc) != 0xFF) g.tactics.at(b + 0xc)--; // contract months (BalancePlan_BalanceFromGame_RuntimeField is 0) + if (g.tactics.at(b + 0xc) <= 1) { + if (g.tactics.at(b + 0xc) != 0) { + // "'s Vertrag läuft in einem Monat ab. ..." (string at ContractExpiryWarningText) + post_composed(g, m, g.player_name(player) + + kContractEndsSoonText); + } else if (!(g.tactics.at(b + 0xb) & 0x20)) { + // the contract has ended: "... Vertrag ist ausgelaufen" (Month_BoardMonth_TextPointer4) and the + // contracts screen; without a renewal the message is posted and he goes + const std::string text = g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer4); + const int renewed = g.contract_screen ? g.contract_screen(g, m, s) : -2; + if (renewed == -2) { + report.fail("month change: a contract ends (the contracts screen InstallDefaultHooks)"); + return; + } + if (renewed < 0) return; + if (renewed == 0) { + post_composed(g, m, text); + if (!game) { + report.fail("month change: a player goes (MonthChange) without the game generator"); + return; + } + if (!release_player(g, int(range.first) + s, *game, rand, report)) return; + s = 0; + goto next_player; + } + } else { + // he ends his career (flag 0x20, see above): Month_BoardMonth_TextPointer2, then his club gets + // a compensation, Month_BoardMonth_TextPointer3 + the amount (AddToSquad with W(15, 30) + // percent, 1 year, rounded down to 10000) + post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer2)); + const int percent = rand.range(0xf, 0x1e); + uint32_t fee = 0, salary = 0; + market_value(g, int(range.first) + s, 0, percent, fee, salary, 1, 0, rand); + fee = fee / 10000 * 10000; + post_composed(g, m, message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer3) + format_amount(g, int32_t(fee)) + "."); + add32(r, rec + 0x314, int32_t(fee)); // MonthRuntimeField9: the balance, not booked + if (!game) { + report.fail("month change: a player retires (MonthChange) without the game generator"); + return; + } + if (!release_player(g, int(range.first) + s, *game, rand, report)) return; + goto next_player; + } + } + // the value history of the month + uint32_t fee = 0, salary = 0; + market_value(g, int(range.first) + s, 0, 100, fee, salary, 0, 0, rand); + const size_t h = b + size_t(month); + g.tactics.at(h + 0x19) = uint8_t(std::min(fee / 8000, 0xff)); + const uint32_t w = g.players.at(size_t(player)).w35c; + g.tactics.at(h + 0x25) = uint8_t((((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) * 3 >> 1) * 0xff) / 300); + g.tactics.at(h + 0x31) = uint8_t(std::min(((w & 0x7F) * 0x8c) / 0x5a, 0xff)); + } + for (int s = 0; s < 24; s++) g.tactics.at(board(s) + 0xb) &= 0x7F; +} + +// MonthChange2: share prices grow by 2.5 %, dividends, loans between the managers. +void shares_and_loans(GameState& g) { + StaticMemory& mem = g.memory; + std::vector& r = g.manager_records; + static const int kShareFactor[6] = {15, 18, 21, 24, 27, 30}; // MonthRuntimeField10 + const int managers = int(g.manager_teams.size()); + for (int k = 0; k < 6; k++) { + const uint32_t at = ::bmh::layout::FundBlock + uint32_t(k) * 0x1c; + uint32_t price = mem.u32(at); + price += ((price / 10000) * 0x19 / 10) * 10; + mem.set32(at, price); + // (a bug of the original: only the last manager's dividend is kept and it is booked + // for the manager after the last one) + int32_t dividend = 0; + for (int m = 0; m < managers; m++) + dividend = int32_t(mem.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c) * + ((price * uint32_t(kShareFactor[k])) / 10000)); + book_money(g, managers, -dividend, true); + add32(r, size_t(managers) * kRecord + 0x870, dividend); + } + for (int m = 0; m < managers; m++) + for (int l = 0; l <= managers; l++) { + const uint32_t e = ::bmh::layout::Loans + uint32_t(l) * 0x18 + uint32_t(m) * 0x78; + const int32_t rate = int32_t(mem.u32(e + 8)); + if (rate == 0) continue; + book_money(g, m, rate, true); + add32(r, size_t(m) * kRecord + 0x89c, rate); + if (l != 0) { + add32(r, size_t(l - 1) * kRecord + 0x870, rate); + book_money(g, l - 1, -rate, true); + } + mem.set32(e + 0x14, mem.u32(e + 0x14) + uint32_t(rate)); + mem.set32(e + 0x10, mem.u32(e + 0x10) + 1); + if (int32_t(mem.u32(e + 0xc)) <= int32_t(mem.u32(e + 0x10))) + for (uint32_t i = 0; i < 0x18; i++) mem.set8(e + i, 0); + } +} + +} // namespace + +bool list_transfer_player(GameState& g, int slot, WatcomRandom& rand, MinuteReport& report) { + return list_player(g, slot, rand, report); +} + +void new_transfer_list_entries(GameState& g, WatcomRandom& rand, MinuteReport& report) { new_list_entries(g, rand, report); } + +void market_value(const GameState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years, + int extra, WatcomRandom& rand) { + if (years > 4) years = 4; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const Player& p = g.players.at(size_t(player)); + int age = int((p.w364 >> 21) & 0x1F) + 1; // local_24 + if (age > 0x14) age = 0x14; + const int position = int(p.w364 & 3); + uint16_t value[2] = {uint16_t((p.w35c >> 7) & 0x7F), uint16_t((p.w35c >> 14) & 0x7F)}; // technique, condition + uint8_t growth = 100; // local_14 + if (age > 10) growth = uint8_t(age * -10 - 0x38); + for (int k = 0; k < 2; k++) + for (int s = 0; s < years - 1; s++) + value[k] = uint16_t((uint32_t(growth) * kDevelopment[int16_t(value[k]) / 10]) / 100 + value[k]); + const int ad = std::abs(0xb - age) & 0xFF; + int points = ((int16_t(value[0]) + int16_t(value[1])) * 5) / 2 + 0x96 - ad * 2; // local_2c + points = std::clamp(points, 0xc, 0x26c); + if (points > 500) points += points < 600 ? kDevelopment[10 + (points - 500) / 10] : 100; + points = (((points >> 2) + 1) * points * ((points >> 3) + 100)) / 10; + int16_t factor = int16_t(((p.w364 >> 26) & 0x3F) >> 2); // experience + if (position == 0) { + factor = int16_t(factor + 0x6e); + } else { + const int16_t skill = int16_t((int((p.w364 >> 10) & 0x3F) * 3 + int((p.w368 >> 7) & 0x3F)) >> 1); + const int t = (position * skill) / 3; + factor = int16_t(factor + 100 + (int16_t(t) >> 1)); + } + fee = uint32_t((percent * ((factor * points) / 100)) / 100); + if (fee < 50000) fee = uint32_t(rand.range(50000, 80000)); + salary = fee / 0x28; + // (local_24 holds 11 - age by now, the variable of the age difference above: younger + // players ask for more per extra year, older ones for less) + salary = ((uint32_t(extra * (0xb - age) + 100) * salary) / 10000) * 100; + if (loan == 1) fee >>= 2; + // BMH_MARKET_TRACE=1: the factors of one valuation (diagnosis of #40; no state, no draws) + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[market_value player %d (%s) pos %d age_raw %d TE %d KO %d -> points %d factor %d percent %d years %d extra %d: fee %u salary %u]\n", + player, g.player_name(player).c_str(), position, age, int((p.w35c >> 7) & 0x7F), int((p.w35c >> 14) & 0x7F), + points, int(factor), percent, years, extra, fee, salary); +} + +std::array contract_demands(GameState& g, int manager, int row, bool from_desk, WatcomRandom& rand) { + const SquadRange range = squad_range(g.manager_teams.at(size_t(manager))); + const int slot = int(range.first) + row; + const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const int age = int((g.players.at(size_t(player)).w364 >> 21) & 0x1F) + 1; // local_24 + // Difficulty (Range3 always returns 1, so the level is used) + const int percent = g.level + 100; + std::array demand{}; + for (int k = 0; k < 4; k++) { + // per year beyond the current contract the salary changes by 11 - age percent + const int extra = int8_t(uint8_t(k - (g.tactics.at(b + 0xc) + 6) / 0xc + 1)); + uint32_t fee = 0, salary = 0; + market_value(g, slot, 0, percent, fee, salary, k + 1, extra, rand); + salary = (g.tactics.at(b + 0xd) * salary) / 100; // his mood + const bool refuses = age + k >= 0x24 || (g.tactics.at(b + 0xb) & 0x60); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[contract_demands player %d years %d: mood +0x0d %d, flags +0x0b %02x, refuses %d -> %u]\n", + player, k + 1, int(g.tactics.at(b + 0xd)), int(g.tactics.at(b + 0xb)), int(refuses), salary); + demand[size_t(k)] = refuses && from_desk ? 0xFFFFFFFFu : salary; + } + return demand; +} + +bool contract_offer(GameState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request, + bool screen_row, WatcomRandom& rand, const std::array* proposed_bonuses) { + const int team = g.manager_teams.at(size_t(manager)); + const SquadRange range = squad_range(team); + const int slot = int(range.first) + row; + const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const size_t bonus_at = b + 0x12; + std::array current_bonuses{}; + for (size_t i = 0; i < current_bonuses.size(); ++i) { + current_bonuses[i] = g.tactics.at(bonus_at + i); + if (proposed_bonuses && (*proposed_bonuses)[i] > (i < 3 ? 20 : 200)) return false; + } + // the longer he is at the club (+0x11, months), the less he insists + int loyalty = g.tactics.at(b + 0x11) / rand.range(8, 0xc); // local_3c + if (int16_t(loyalty) > 6) loyalty = 6; + // the offer counts with 80 % of the bonus he can expect (ContractOffer with the fitness + // correction on a copy of his board row whose salary is the offer: its +0x50 is the + // offer variable local_f0 that follows the copy on the stack) + std::array buf; + const int predicted = table_prediction(g, team, 4, buf); + const int rank = predicted == 0 ? 0xB : predicted + 1; + uint8_t saved[4]; + std::copy(g.tactics.begin() + long(b + 0x50), g.tactics.begin() + long(b + 0x54), saved); + for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i)); + if (proposed_bonuses) + std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at)); + const uint32_t bonus = expected_bonus(g, manager, rank, row, player, true); + std::copy(saved, saved + 4, g.tactics.begin() + long(b + 0x50)); + if (proposed_bonuses) + std::copy(current_bonuses.begin(), current_bonuses.end(), g.tactics.begin() + long(bonus_at)); + const uint32_t worth = offer + (bonus * 0x50) / 100; // uVar12 + if (std::getenv("BMH_TRACE")) + std::printf(" [offer %u: loyalty %d, rank %d, bonus %u, worth %u, demand %u]\n", offer, loyalty, rank, bonus, worth, + demand); + // what he wants: W(80, 100) - 2 x loyalty percent of his demand (a request of his own: + // the whole demand) + const uint32_t wanted = (request ? 100u : uint32_t(rand.range(0x50, 100) - 2 * int16_t(loyalty))) * demand; + if (std::getenv("BMH_TRACE")) std::printf(" [wanted %u / 100]\n", wanted); + if ((offer * 100u) / demand < 0x3d || worth < wanted / 100) { + // "Der Spieler lehnt ab" (CareerSession_Reject_TextPointer6, a message box): he is offended (+0x4f bit 7) + // and in a worse mood + g.tactics.at(b + 0x4f) |= 0x80; + if (g.tactics.at(b + 0xd) < 0xfb) g.tactics.at(b + 0xd) = uint8_t(g.tactics.at(b + 0xd) + 5); + if (screen_row) g.tactics.at(b + 0xb) |= 0x40; // he will not talk again + return false; + } + // accepted (CareerSession_Reject_TextPointer5): the new salary and term; his mood is what the offer is worth + // against his market salary for that term + for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i)); + g.tactics.at(b + 0xc) = uint8_t((column + 1) * 0xc); + uint32_t fee = 0, salary = 0; + market_value(g, slot, 0, 100, fee, salary, column, 0, rand); + g.tactics.at(b + 0xd) = uint8_t(std::clamp((worth * 100) / salary, 100, 0xff)); + if (proposed_bonuses) + std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at)); + return true; +} + +bool contract_bonuses(GameState& g, int manager, int row, const std::array& rates) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return false; + const int team = g.manager_teams[size_t(manager)]; + if (team == kNoTeam) return false; + const SquadRange range = squad_range(team); + if (row < -1 || (row >= 0 && size_t(row) >= range.count) || range.first + range.count > g.squad_slots.size()) + return false; + for (size_t i = 0; i < rates.size(); ++i) + if (rates[i] > (i < 3 ? 20 : 200)) return false; + const size_t board = size_t(manager) * 0x840; + if (board + size_t(range.count) * 0x58 > g.tactics.size()) return false; + bool changed = false; + const size_t first_row = row < 0 ? 0 : size_t(row); + const size_t end_row = row < 0 ? range.count : size_t(row) + 1; + // The original checks the whole selected scope before committing any of it. + for (size_t r = first_row; r < end_row; ++r) { + const int player = g.squad_slots.at(range.first + r) & 0x0fff; + if (player == 0x0fff) continue; + if (size_t(player) >= g.players.size()) return false; + const size_t b = board + r * 0x58; + for (size_t i = 0; i < rates.size(); ++i) { + const uint8_t old = g.tactics.at(b + 0x12 + i); + changed |= rates[i] > old; + } + } + for (size_t i = 0; i < rates.size(); ++i) { + bool found = false; + uint8_t minimum = 0xff; + for (size_t r = first_row; r < end_row; ++r) { + if ((g.squad_slots.at(range.first + r) & 0x0fff) == 0x0fff) continue; + found = true; + minimum = std::min(minimum, g.tactics.at(board + r * 0x58 + 0x12 + i)); + } + if (found && rates[i] < minimum) return false; + } + if (!changed) return false; + for (size_t r = first_row; r < end_row; ++r) { + const int player = g.squad_slots.at(range.first + r) & 0x0fff; + if (player == 0x0fff) continue; + const size_t b = board + r * 0x58; + for (size_t i = 0; i < rates.size(); ++i) + if (rates[i] > g.tactics.at(b + 0x12 + i)) g.tactics.at(b + 0x12 + i) = rates[i]; + } + return true; +} + +ContractInsuranceResult contract_insurance(GameState& g, int manager, int row, int insurance_type, + uint8_t months) { + ContractInsuranceResult out; + if (manager < 0 || size_t(manager) >= g.manager_teams.size() || insurance_type < 0 || insurance_type >= 4 || + months < 1 || months > 60) return out; + const int team = g.manager_teams[size_t(manager)]; + if (team == kNoTeam) return out; + const SquadRange range = squad_range(team); + if (row < 0 || size_t(row) >= range.count || range.first + size_t(row) >= g.squad_slots.size()) return out; + const int player = g.squad_slots.at(range.first + size_t(row)) & 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size()) return out; + const size_t b = size_t(manager) * 0x840 + size_t(row) * 0x58; + if (b + 0x54 > g.tactics.size() || (g.tactics.at(b + 0x0b) & 0x60) != 0 || + g.tactics.at(b + 0x43) != 0 || (g.players[size_t(player)].w35c >> 27) != 0) return out; + const uint32_t salary = uint32_t(g.tactics.at(b + 0x50)) | + (uint32_t(g.tactics.at(b + 0x51)) << 8) | (uint32_t(g.tactics.at(b + 0x52)) << 16) | + (uint32_t(g.tactics.at(b + 0x53)) << 24); + const uint32_t fee = (((uint32_t(insurance_type * 10 + 10) * salary) / 1000) * 10); + const uint16_t old_fee = uint16_t(g.tactics.at(b + 0x4e) | (uint16_t(g.tactics.at(b + 0x4f)) << 8)); + g.tactics.at(b + 0x43) = uint8_t(months | uint8_t(insurance_type << 6)); + // The original clears the old amount but preserves the high flag before adding the + // term's monthly premium into the 16-bit field. + const uint16_t base = uint16_t(old_fee & 0x8000); + const uint16_t stored = uint16_t(base + uint16_t(fee)); + g.tactics.at(b + 0x4e) = uint8_t(stored); + g.tactics.at(b + 0x4f) = uint8_t(stored >> 8); + out.accepted = true; + out.monthly_fee = uint16_t(fee); + return out; +} + +void search_profile_news(GameState& g, int manager, uint32_t list, int player) { + const StaticMemory& mem = g.memory; + const size_t rec = size_t(manager) * kRecord; + auto b = [&](size_t off) { return int(g.manager_records.at(rec + off)); }; + const int team = g.manager_teams.at(size_t(manager)); + player &= 0xFFF; + if (team == kNoTeam || (mem.u16(list + 8) & 0x7FFF) == team || (b(0x1f6) & 0x40)) return; + const uint32_t w364 = g.players.at(size_t(player)).w364, w35c = g.players.at(size_t(player)).w35c; + // position wanted (or none selected) and age within the range + if (b(0x1f6 + (w364 & 3)) == 0 && b(0x1f9) + b(0x1f8) + b(0x1f7) + b(0x1f6) != 0) return; + const int age = int((w364 >> 21) & 0x1F); + if (age < b(0x1fa) || age > b(0x1fb)) return; + // strength by the selected attributes (condition, technique, form; none = all three) + int8_t selected = int8_t(b(0x200) + b(0x1fe) + b(0x1ff)); + if (selected == 0) selected = 3; + int sum = 0, n = 0, form = 0; + if (b(0x1fe) != 0 || selected == 3) sum = int((w35c >> 14) & 0x7F), n = 1; + if (b(0x1ff) != 0 || selected == 3) sum = int16_t(sum) + int((w35c >> 7) & 0x7F), n++; + if (b(0x200) != 0 || selected == 3) form = int(w35c & 0x7F); + int16_t strength; + if (n == 0) { + strength = int16_t((form - 0x23) * 3 + 10); + } else { + strength = int16_t(uint32_t(sum) / uint32_t(n)); + if (form != 0) strength = int16_t(uint32_t(strength * int16_t((int16_t(form) >> 3) + 0x5e)) / 100); + } + if (strength < b(0x1fc) || strength > b(0x1fd)) return; + // left / right foot and wing preferences (w35c bits 21-23 and 24-26) + const int lane = int((w35c >> 21) & 7), foot = int((w35c >> 24) & 7); + bool low_foot = b(0x201) || b(0x203), high_foot = b(0x202) || b(0x204); + if (low_foot && high_foot) low_foot = high_foot = false; + bool low_lane = b(0x201) || b(0x202), high_lane = b(0x203) || b(0x204); + if (low_lane && high_lane) low_lane = high_lane = false; + if ((low_lane && lane >= 3) || (high_lane && lane <= 4) || (low_foot && foot >= 3) || (high_foot && foot <= 4)) return; + // the price class (asking price 70..130 %) against the classes wanted + int8_t price_class = int8_t((mem.u8(list + 0x54) - 0x46) / 0x14); + price_class = std::clamp(price_class, 0, 2); + const int8_t classes = int8_t(b(0x207) + b(0x205) + b(0x206)); + int highest = 2; + while (highest >= 0 && b(0x205 + size_t(highest)) == 0) highest--; + if (classes == 0 || price_class <= highest) + post_composed(g, manager, message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer2)); +} + +void month_change(GameState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + StaticMemory& mem = g.memory; + std::vector& r = g.manager_records; + const int managers = int(g.manager_teams.size()); + // 1. advertising contracts + turn_step = "month_change: advertising"; + if (mem.u8(::bmh::layout::GameMode) != 1 && mem.u8(::bmh::layout::CareerDuration) != 1) + for (int m = 0; m < managers; m++) + for (int k = 0; k < 0x12; k++) { + const size_t c = size_t(m) * kRecord + 0xa34 + size_t(k) * 0xc; + if (r.at(c + 5) == 0 && (r.at(c + 6) & 0x80)) { + wr32(r, c, 0); + r.at(c + 6) = 0; + } + if (r.at(c + 5) != 0 && --r.at(c + 5) == 0) { + if ((r.at(c + 6) & 0x7F) == 0) wr32(r, c, 0); + else turn_step = "month_change: advertising text", post_text(g, m, text_id(::bmh::layout::Month_MonthChange_TextPointer)); // the contract can be renewed + } + } + // 2. new players on the transfer list + turn_step = "month_change: new list entries"; + new_list_entries(g, rand, report); + if (report.unsupported) return; + // 3. loans + turn_step = "month_change: loans"; + return_loans(g, rand, game, report); + if (report.unsupported) return; + // 4. the human managers + turn_step = "month_change: managers"; + for (int m = 0; m < managers && !report.unsupported; m++) { + const size_t rec = size_t(m) * kRecord; + for (int k = 0; k < 3; k++) + rate_manager(g, m, uint8_t(int8_t(int32_t(mem.u32(::bmh::layout::Month_MonthChange_RuntimeField + uint32_t(k) * 4 + uint32_t(m) * 0x24)) / 0x96)), + k + 1); + const int32_t expenses = monthly_expenses(g, m); + const int32_t income = monthly_income(g, m); + book_money(g, m, expenses - income, true); + for (int k = 0; k < 2; k++) + rate_manager(g, m, uint8_t(int8_t(((rd32(r, rec + 0x854 + size_t(k) * 4) / 5000) * 200) / 7)), k + 4); + board_month(g, m, rand, report, game); + } + if (report.unsupported) return; + // 5. shares and loans + turn_step = "month_change: shares"; + shares_and_loans(g); +} + +} // namespace bmh diff --git a/src/game/month.hpp b/src/game/month.hpp new file mode 100644 index 0000000..1aaca35 --- /dev/null +++ b/src/game/month.hpp @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The month change (DayStepRest2), run by the day step (DayStepRest) of the first day of +// a month in the full game (CompetitionSelection bit 0), after the training / weekly processing: +// +// 1. advertising contracts of the human managers count down (record +0xa34, 18 x 0xC) +// 2. new players on the transfer list (CareerFirstSteps): free agents of the pool and players +// the computer clubs want to sell +// 3. loaned players whose time is up return to their clubs (table Career_RemoveJoinLoans_RuntimeField) +// 4. per human manager: the monthly ratings (ManagerMatchRecord2), expenses minus income, and the +// monthly bookkeeping of every squad player on the tactics board (contract months, +// mood, value history, retirement wishes) +// 5. share prices grow, dividends and loans between managers are booked (MonthChange2) +// +// Monthly bookkeeping uses Watcom draws; player moves also require the game RNG. +// Human decisions use caller-supplied contract/loan presenters. Missing context +// and invalid state report through MinuteReport, rather than guessing a decision. + +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// `game` is needed when a player leaves at the end of his contract (MonthChange). +void month_change(GameState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr); + +// CareerFirstSteps: new players on the transfer list (part of the month change; also at the +// start of a season). +void new_transfer_list_entries(GameState& g, WatcomRandom& rand, MinuteReport& report); + +// AddToSquad(slot, loan, percent, &fee, &salary, years, extra): market value (fee) and +// salary of the player in an absolute squad slot, from strength, age, position and +// experience; `percent` scales the fee, `years` - 1 steps of expected development raise +// it, `extra` * (11 - age) percent change the salary. A fee below 50000 is replaced by W(50000, +// 80000); a loan (1) costs a quarter. +void market_value(const GameState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years, + int extra, WatcomRandom& rand); + +// ContractBonuses, the salary page of the contract talks (contracts screen InstallDefaultHooks): the +// four demands for 1-4 years when the talks open, AddToSquad with the level + 100 percent +// and the salary rise for the years beyond the current contract, times the player's mood +// (+0xd) / 100. Opened from the desk (`from_desk`, param_5 0x80) a player of 36 or more +// at the end of the term, or one flagged 0x20 / 0x40, wants no contract (no-contract sentinel). +std::array contract_demands(GameState& g, int manager, int row, bool from_desk, WatcomRandom& rand); + +// ContractBonuses "OK" with an offer for `column` + 1 years against that column's demand: W(8, 12) +// (loyalty from the months at the club, +0x11) and - unless the player asked himself +// (`request`, param_5 0x40) - W(80, 100). The offer plus 80 % of the expected bonus +// (ContractOffer) must reach that percentage of the demand, and the offer itself 61 %. +// Accepted: salary, term and mood (+0x50, +0xc, +0xd) change, AddToSquad for the term. +// Rejected: the player is offended (+0x4f bit 7, mood + 5); for the row whose contract +// ended (`screen_row`) he will not talk again (+0xb bit 6). Returns whether he accepted. +bool contract_offer(GameState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request, + bool screen_row, WatcomRandom& rand, + const std::array* proposed_bonuses = nullptr); + +// ContractBonuses "Prämien" page. `row == -1` edits the squad's shared proposal; each +// stored row is raised to the requested value. A bonus-only submission is accepted only +// when it does not lower any player's current rate, and must change at least one rate. +bool contract_bonuses(GameState& g, int manager, int row, const std::array& rates); + +struct ContractInsuranceResult { + bool accepted = false; + uint16_t monthly_fee = 0; +}; + +// ContractBonuses insurance button: one-time per player, duration 1..60 months, and insurance +// category bound to the selected 1..4 year term. This action consumes no RNG. +ContractInsuranceResult contract_insurance(GameState& g, int manager, int row, int insurance_type, + uint8_t months); + +// SearchProfileNews(manager, list entry, player, 1): tells a human manager about a new player on +// the transfer list that matches his search profile (record +0x1f6 .. +0x207). +void search_profile_news(GameState& g, int manager, uint32_t list, int player); + +// Put an existing squad slot on the shared transfer list (human desk action). +bool list_transfer_player(GameState& g, int slot, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh diff --git a/src/game/national.cpp b/src/game/national.cpp new file mode 100644 index 0000000..77cf4f8 --- /dev/null +++ b/src/game/national.cpp @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/national.hpp" + +#include +#include + +#include "game/lineup.hpp" +#include "game/match_engine.hpp" +#include "game/month.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kManagerRecord = 0xb0c; +constexpr size_t kBoard = 0x840; // one manager's tactics board (24 x 0x58) +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kDesktops = ::bmh::layout::Desktops; // desktop layouts, 0x360 per manager slot +constexpr size_t kDesktop = 0x360; +constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField: the clubs' squads end here +constexpr uint8_t kNominated[4] = {3, 5, 7, 5}; // NationalRuntimeField: keepers, defence, midfield, attack + +// the manager's team (record +0x290) as the port caches it +void refresh_manager_teams(GameState& g) { + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const size_t at = m * kManagerRecord + 0x290; + g.manager_teams[m] = int16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + } +} + +// a byte of the original's static data, created on first use (not every one is saved) +uint8_t& static_byte(GameState& g, uint32_t address) { + if (!g.memory.has(address)) g.memory.add_block(address, 1); + return g.memory.at(address); +} + +} // namespace + +void swap_manager_slots(GameState& g, int a, int b) { + if (a == b) return; + std::swap_ranges(g.manager_records.begin() + long(size_t(a) * kManagerRecord), + g.manager_records.begin() + long(size_t(a + 1) * kManagerRecord), + g.manager_records.begin() + long(size_t(b) * kManagerRecord)); + std::swap_ranges(g.tactics.begin() + long(size_t(a) * kBoard), g.tactics.begin() + long(size_t(a + 1) * kBoard), + g.tactics.begin() + long(size_t(b) * kBoard)); + if (g.memory.has(kDesktops)) + for (size_t i = 0; i < kDesktop; i++) { + const uint32_t pa = kDesktops + uint32_t(size_t(a) * kDesktop + i); + const uint32_t pb = kDesktops + uint32_t(size_t(b) * kDesktop + i); + const uint8_t t = g.memory.u8(pa); + g.memory.set8(pa, g.memory.u8(pb)); + g.memory.set8(pb, t); + } + refresh_manager_teams(g); +} + +int add_to_squad(GameState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand) { + // FirstFreeSlotSquad(start, 0x18): the first free slot of the squad + int slot = -1; + for (int s = squad_start; s < squad_start + 24; s++) + if (g.squad_slots.at(size_t(s)) == kEmptySlot) { + slot = s; + break; + } + if (slot < 0) return -1; // (the original shows the message PendingOffer_FormatError_ExecutableField) + g.squad_slots.at(size_t(slot)) = g.squad_slots.at(size_t(from_slot)); + new_board_entry(g, manager, slot - squad_start, slot, rand); + return slot; +} + +void new_board_entry(GameState& g, int manager, int index, int slot, WatcomRandom& rand) { + uint8_t* e = &g.tactics.at(size_t(manager) * kBoard + size_t(index) * kBoardSlot); + std::memset(e + 7, 0, 3); + std::memset(e + 0x19, 0, 0x24); + e[10] = 2; + for (int k = 0; k < 4; k++) e[2 + k] = index < 2 ? 1 : uint8_t(rand.range(2, 0x27)); + e[0x3f] = 0xff; + e[0x46] = 0xff, e[0x47] = 0x0f; // u16 0xfff + e[0x44] = 0xff, e[0x45] = 0x0f; + e[0] = 10; + e[1] = 4; + e[0xe] = 0x59; + e[0xf] = uint8_t(rand.range(0x28, 0x3c)); + e[0x11] = 0; + e[0x43] = 0; + e[0x4e] = 0, e[0x4f] = 0; + e[0x3d] = index < 11 ? 0 : index <= 0x10 ? 1 : 2; + e[0xc] = 0x18; + // AddToSquad(slot, 0, W(95, 105), &fee, &salary (+0x50), 2 years, no extra) + const int percent = rand.range(0x5f, 0x69); + uint32_t fee = 0, salary = 0; + market_value(g, slot, 0, percent, fee, salary, 2, 0, rand); + for (int k = 0; k < 4; k++) e[0x50 + k] = uint8_t(salary >> (8 * k)); + std::memset(e + 0x12, 0, 7); +} + +bool national_team_day(GameState& g, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const SquadRange national = squad_range(kNoTeam); + // NationalSquadEmptied: the national squad is emptied + for (size_t s = national.first; s < national.first + national.count; s++) g.squad_slots.at(s) = kEmptySlot; + + // SwapManagerSlots2 (called whether or not a take-over is already in effect): a manager flagged + // as Bundestrainer takes the national team over in slot 0. ActiveManager is what the day + // step's manager loop (DayStepRest) leaves: the number of managers. + (void)mem; + (void)report; + national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(g.date - g.season_start)); + const uint8_t coach = static_byte(g, ::bmh::layout::CoachActive); // CoachActive + if (coach == 0) swap_manager_slots(g, 4, 0); // slot 0 becomes the spare slot 4 + + // the strongest available German players per position (NationalRuntimeField of each), kept in + // ascending order: a stronger one pushes the weakest out + int16_t best[4][7] = {}, slots[4][7] = {}; + for (size_t s = 0; s < kPoolSlots; s++) { + const int id = g.squad_slots.at(s) & 0xfff; + if (id == 0xfff) continue; + const Player& p = g.players.at(size_t(id)); + const bool fit = (p.w35c >> 27) == 0 || ((p.w364 >> 16) & 0x1f) == 0; + if (!fit || nationality(g, id) != 0) continue; + const int pos = int(p.w364 & 3); + int16_t strength = int16_t(p.strength(false)); // Strength(w35c, 0) + if (pos > 1) strength = int16_t(strength + ((p.w364 >> 2) & 0x3f) + (((p.w368 >> 18) & 0x3f) >> 1)); + if (s > 0x86f) strength = int16_t((strength * 0xb) / 10); // (the clubs from slot 0x870 on) + int i = 0; + // NationalTeamDay caps the insertion index at the positional quota. Guard + // before indexing: the full seven-player row has no C++ eighth element. + while (i < kNominated[pos] && strength > best[pos][i]) i++; + if (i == 0) continue; + const int j = i - 1; + // Int16T: entries 1..j move down one place, the new one takes place j + for (int k = 0; k < j; k++) best[pos][k] = best[pos][k + 1], slots[pos][k] = slots[pos][k + 1]; + best[pos][j] = strength; + slots[pos][j] = int16_t(s); + } + // PendingOfferAnswer for each, weakest first, into the board of slot 0 + for (int pos = 0; pos < 4; pos++) + for (int k = 0; k < kNominated[pos]; k++) add_to_squad(g, 0, slots[pos][k], int(national.first), rand); + // Int2(0x165, 0xe4) with manager 0's option byte (ManagerAutomation) at 1 + const uint8_t option = g.manager_options.at(0); + g.manager_options.at(0) = 1; + try { + auto_lineup(g, kNoTeam, 0xe4); + } catch (const std::exception& ex) { + report.fail(std::string("national team line-up: ") + ex.what()); + } + if (coach == 0) swap_manager_slots(g, 4, 0); + g.manager_options.at(0) = option; + return coach != 0; // (with a Bundestrainer his desk follows: AdvanceTurn's local_28 = 4) +} + + +// --------------------------------------------------------------------------------------- +// The Bundestrainer (national coach). A manager flagged in his record (+0x21c), every +// manager in the world game without leagues (CompetitionSelection == 2) and the only manager of a +// one-manager game coaches the national team on international days: SwapManagerSlots2 moves his +// slot 0 to the spare slot 4 and puts the national team's record (kept in slot 4 between the +// international periods) into slot 0; NationalCoachHandBack swaps them back. CoachActive tells +// whether the swap is in effect, OriginalManagerCount keeps the number of managers meanwhile. + +namespace { + +void set_manager_count(GameState& g, int managers) { + static_byte(g, ::bmh::layout::ManagerCount) = uint8_t(managers); // ManagerCount + g.manager_teams.assign(size_t(managers), 0); // (the typed copy, one entry per manager) +} + +} // namespace + +void national_coach_take_over(GameState& g, int active_manager, uint16_t source_season_day) { + StaticMemory& mem = g.memory; + int managers = int(g.manager_teams.size()); + static_byte(g, ::bmh::layout::OriginalManagerCount) = uint8_t(managers); // OriginalManagerCount = ManagerCount + static_byte(g, ::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3) = uint8_t(active_manager); // ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager + // DaysIntoSeason == 1 (the first day after the saved season origin): the national team's + // mood byte loses its top bit before coach eligibility is checked. + const bool first_day = source_season_day == 1; + if (first_day) g.team_morale.at(kNoTeam) &= 0x7f; + const bool world_only = mem.u32(::bmh::layout::CompetitionSelection) == 2; + // (the loop bound is ManagerCount itself, which a take-over sets to 1) + for (int m = 0; m < managers; m++) { + uint8_t* rec = &g.manager_records.at(size_t(m) * kManagerRecord); + if (rec[0x21c] == 0 && !world_only && managers != 1) continue; + // the national team's record (slot 4) gets the coach's portrait (+0x221) and name + // (+0xa8, StrcpySoHallReplacesItsCurrentTournament = strcpy) + uint8_t* spare = &g.manager_records.at(4 * kManagerRecord); + spare[0x221] = rec[0x221]; + for (size_t i = 0;; i++) { + spare[0xa8 + i] = rec[0xa8 + i]; + if (rec[0xa8 + i] == 0) break; + } + managers = 1; + set_manager_count(g, 1); + swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) + uint8_t* coach = &g.manager_records.at(0); + coach[0x290] = uint8_t(kNoTeam & 0xff), coach[0x291] = uint8_t(kNoTeam >> 8); // CupDraw_FormatError_RuntimeField2 = 0x165 + coach[0x218] = g.manager_records.at(4 * kManagerRecord + 0x218); // NationalRuntimeField2 = NationalRuntimeField3 + g.manager_teams.at(0) = kNoTeam; + auto_lineup(g, kNoTeam, 0xe4); // Int2(0x165, 0xe4) + static_byte(g, ::bmh::layout::CoachActive) = 1; + if (first_day) g.team_morale.at(kNoTeam) |= 0x80; + } +} + +void national_coach_hand_back(GameState& g) { + if (static_byte(g, ::bmh::layout::CoachActive) == 0) return; + const int managers = static_byte(g, ::bmh::layout::OriginalManagerCount); + set_manager_count(g, managers); // ManagerCount = OriginalManagerCount + swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) (refreshes the typed teams) + static_byte(g, ::bmh::layout::CoachActive) = 0; +} + +bool national_coach_active(const GameState& g) { return !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam; } + +void national_coach_after_load(GameState& g) { + // NationalCoachAfterLoad's end, loading as well as saving: the take-over is done again + if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0) + national_coach_take_over(g, g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0, + uint16_t(g.date - g.season_start)); +} + +GameState national_coach_save_form(const GameState& g) { + // NationalCoachAfterLoad's start: the slots swapped back, CoachActive kept at 1 + GameState s = g; + if (s.memory.has(::bmh::layout::CoachActive) && s.memory.u8(::bmh::layout::CoachActive) != 0) { + national_coach_hand_back(s); + s.memory.set8(::bmh::layout::CoachActive, 1); + } + return s; +} + +} // namespace bmh diff --git a/src/game/national.hpp b/src/game/national.hpp new file mode 100644 index 0000000..8431a66 --- /dev/null +++ b/src/game/national.hpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The national team (BMH.exe V2.24 + supported rule profile patch), team id 0x165 (kNoTeam), squad slots +// 0xc00-0xc17 (LargeSquadClubCount). +// +// With the world game on (CompetitionSelection bit 1) the calendar holds national team days (entry +// 0x4006, DayCompetitions -> national-only flag). On such a day AdvanceTurn calls NationalTeamDay, which +// nominates the squad: the manager slots are swapped so that slot 0 is a spare one +// (SwapManagerSlots(4, 0); a Bundestrainer instead takes slot 0 over with the national team, +// SwapManagerSlots2), the 3 goalkeepers, 5 defenders, 7 midfielders and 5 forwards +// (NationalRuntimeField) of the highest strength among the available German players of all clubs +// join the national squad with a fresh tactics board entry (PendingOfferAnswer), the national team +// gets its line-up (Int2(0x165, 0xe4)) and the slots are swapped back. Without a +// Bundestrainer the day then prepares an empty matchday (no desk, no match). + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +struct MinuteReport; + +// SwapManagerSlots(a, b): manager slots a and b change places - the manager records (0xb0c +// bytes), the tactics boards (0x840) and the desktop layouts (block Desktops, 0x360). +void swap_manager_slots(GameState& g, int a, int b); + +// PendingOfferAnswer(manager, from_slot, -1, squad_start): the player of the absolute squad slot +// `from_slot` gets the first free slot of the squad starting at `squad_start` (24 slots; +// the slot value is copied with its flags) and a fresh entry on the tactics board of +// manager slot `manager`: neutral settings, familiarity W(40, 60), the four attribute +// bytes W(2, 39) each (1 for the first two places) and the salary of a 2-year contract +// at W(95, 105) percent (AddToSquad). Returns the new absolute slot, -1 if the squad is full. +int add_to_squad(GameState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand); +// The board part of PendingOfferAnswer (also called with a given place `index`): the entry of +// the player in absolute squad slot `slot` on the tactics board of `manager`. +void new_board_entry(GameState& g, int manager, int index, int slot, WatcomRandom& rand); + +// NationalTeamDay: the national team day (see above). Returns whether a Bundestrainer manages +// the national team (CoachActive) - then his desk follows (AdvanceTurn: local_28 = 4). +bool national_team_day(GameState& g, WatcomRandom& rand, MinuteReport& report); + +// The Bundestrainer (national coach), see national.cpp. SwapManagerSlots2: notes the number of +// managers (OriginalManagerCount) and `active_manager` (ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager); a manager +// flagged in his record (+0x21c), every manager in the world game without leagues +// (CompetitionSelection == 2) and the only manager of a one-manager game takes the national team over: +// the national team's record (slot 4) gets his name and portrait, the number of managers +// becomes 1, slots 4 and 0 change places, slot 0 manages team 0x165 and copies +0x218 from +// slot 4, the national team gets its line-up (Int2(0x165, 0xe4)) and +// CoachActive = 1. +// `source_season_day` is the 16-bit value visible in DaysIntoSeason at this exact Source call +// site. It is not always `g.season_day()`: DailyInterest advances the counter before +// quiet-day rest but after rest on the completed-event path. +void national_coach_take_over(GameState& g, int active_manager, uint16_t source_season_day); +// NationalCoachHandBack: with CoachActive set the slots change places again, the number of managers +// is restored from OriginalManagerCount and CoachActive cleared. +void national_coach_hand_back(GameState& g); +// CupDraw_FormatError_RuntimeField2 == 0x165: slot 0 manages the national team. +bool national_coach_active(const GameState& g); +// NationalCoachAfterLoad (saving and loading): the savegame holds the slots swapped back with +// CoachActive still 1; afterwards (and so after loading) SwapManagerSlots2 takes over again. +void national_coach_after_load(GameState& g); +// The state as NationalCoachAfterLoad writes it (for the savegame writer and comparisons). +GameState national_coach_save_form(const GameState& g); + +} // namespace bmh diff --git a/src/game/other_games.cpp b/src/game/other_games.cpp new file mode 100644 index 0000000..ff97713 --- /dev/null +++ b/src/game/other_games.cpp @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/other_games.hpp" + +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "game/cup.hpp" +#include "game/schedule.hpp" + +namespace bmh { +namespace { + +constexpr uint32_t kActiveSelectors = ::bmh::layout::ActiveSelectors; +constexpr uint32_t kSelectorCount = 8; +constexpr size_t kTextCompetitionNames = (::bmh::layout::CupDraw_FormatError_ExecutableField6 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextCompetitionButtonNames = (::bmh::layout::OtherGames_Layout_ExecutableField - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextRoundHeadings = (::bmh::layout::CupDraw_FormatError_ExecutableField4 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextGroupRound = (::bmh::layout::Calendar_Information_TextPointer2 - ::bmh::layout::TextPointerTable) / 4; +constexpr size_t kTextGroupCaption = (::bmh::layout::CupDraw_FormatError_ExecutableField5 - ::bmh::layout::TextPointerTable) / 4; + +[[noreturn]] void invalid(const char* why) { throw FormatError(std::string("other games: ") + why); } + +std::string text(const TextDb& texts, size_t index) { + if (index >= texts.strings.size()) invalid("missing Source TEXTD entry"); + return texts.strings[index]; +} + +bool in_descriptor_table(int entry) { return entry >= 0 && entry < kCupEntries; } + +// Bounded port of FindCup's literal scan cursor. On a matching descriptor, its +0x17 link +// wins, else +0x16; a zero link falls back to entry0 in Source. The scan cursor itself advances +// only on a nonmatch and returns the just-followed pointer immediately when the cursor is0. +// Malformed/no-match paths fail closed instead of returning Source's invalid one-past-table ptr. +int resolve_linked_entry(const StaticMemory& memory, int competition, int ordinal) { + if (ordinal < 0 || ordinal >= kCupEntries) invalid("linked occurrence outside Source bounds"); + int cursor = 0, current = 0, remaining = ordinal; + std::vector seen(size_t(kCupEntries) * kCupEntries * kCupEntries, 0); + for (size_t step = 0; step < seen.size(); ++step) { + if (!in_descriptor_table(cursor) || !in_descriptor_table(current)) + invalid("Source linked resolver left descriptor table"); + const size_t key = (size_t(cursor) * kCupEntries + size_t(current)) * kCupEntries + size_t(remaining); + if (seen[key]) invalid("cycle in Source linked resolver"); + seen[key] = 1; + const uint32_t address = cup_entry_address(current); + if (!memory.has(address + 0x19)) invalid("truncated Source descriptor ID"); + if (int16_t(memory.u16(address + 0x18)) == competition) { + if (remaining == 0) return current; + const int parallel = int8_t(memory.u8(address + 0x17)); + const int next = int8_t(memory.u8(address + 0x16)); + if (parallel != 0) current = parallel; + else if (next != 0) current = next; + else invalid("Source linked occurrence reaches its no-link fallback"); + if (!in_descriptor_table(current)) invalid("invalid Source linked descriptor link"); + --remaining; + if (cursor == 0) return current; + } else { + ++cursor; + if (cursor >= kCupEntries) invalid("Source linked resolver cursor wrapped without a match"); + current = cursor; + } + } + invalid("Source linked resolver exceeded bounded traversal"); +} + +std::vector source_linked_pages(const StaticMemory& memory, int selected) { + std::vector pages; + int first = selected; + std::array seen{}; + while (in_descriptor_table(first)) { + if (seen[size_t(first)]) invalid("cycle while locating first Source group selector"); + seen[size_t(first)] = true; + const uint8_t group = memory.u8(cup_entry_address(first) + 0x1e); + if ((group >> 4) == 0) break; + if (first == 0) invalid("Source group selector would walk before descriptor table"); + --first; // InDescriptorTable moves one adjacent descriptor left until group index0. + } + while (true) { + if (!in_descriptor_table(first) || seen[size_t(first)]) { + // The first adjacent scan above marks visited entries; reset its cycle guard before + // following signed previous-stage links. + if (!in_descriptor_table(first)) invalid("invalid Source first group descriptor"); + } + seen[size_t(first)] = true; + const int previous = int8_t(memory.u8(cup_entry_address(first) + 0x15)); + if (previous == -1) break; + if (!in_descriptor_table(previous) || seen[size_t(previous)]) invalid("invalid Source previous-stage link"); + first = previous; + } + // InDescriptorTable suppresses the linked-page selector before enumerating groups when the first + // stage has no +0x16 continuation. + if (memory.u8(cup_entry_address(first) + 0x16) == 0) return pages; + int stage = first; + std::array stage_seen{}; + while (in_descriptor_table(stage)) { + if (stage_seen[size_t(stage)]) invalid("cycle in Source linked-stage selector"); + stage_seen[size_t(stage)] = true; + int group_entry = stage; + const uint8_t count = memory.u8(cup_entry_address(stage) + 0x1e) & 0x0f; + for (int group = 0; group < count; ++group) { + if (!in_descriptor_table(group_entry)) invalid("parallel group left descriptor table"); + const uint32_t address = cup_entry_address(group_entry); + pages.push_back({int(pages.size()), group_entry, int16_t(memory.u16(address + 0x18)), + int(memory.u8(address + 0x1e) >> 4), int(count)}); + const bool has_adjacent = memory.u8(address + 0x17) != 0; + if (group + 1 < count && !has_adjacent) + invalid("parallel group count lacks adjacent Source entry"); + // Source checks +0x17 after every emitted sibling, including the final one; when + // present it advances to the adjacent descriptor before reading its +0x16 stage. + if (has_adjacent) ++group_entry; + } + const int next = int8_t(memory.u8(cup_entry_address(group_entry) + 0x16)); + if (next == 0) break; + if (!in_descriptor_table(next)) invalid("invalid Source next-stage selector link"); + stage = next; + } + return pages; +} + +void validate_team(const GameState& game, uint16_t team) { + // CupGroupOverviewEffects indexes ClubIdentities directly; this screen has no empty-club fallback. + if (team == 0x0fff) invalid("Source row references the empty-club sentinel"); + if (team >= game.club_ids.size()) invalid("club id outside loaded name table"); +} + +OtherGamesRow make_row(const GameState& game, int home, int away, uint16_t result, int match) { + if (home < 0 || home > 0xffff || away < 0 || away > 0xffff) invalid("invalid team id"); + const uint16_t h = uint16_t(home), a = uint16_t(away); + validate_team(game, h); + validate_team(game, a); + OtherGamesRow row; + row.home_team = home; + row.away_team = away; + row.home_name = game.club_name(home); + row.away_name = game.club_name(away); + row.source_result = result; + row.played = result != 0xcccc; + if (row.played) { + row.home_goals = (result >> 5) & 0x1f; + row.away_goals = result & 0x1f; + } + row.source_match = match; + return row; +} + +OtherGamesClubMetadata source_metadata(const GameState& game, int team) { + OtherGamesClubMetadata out; + bool manager_owned = game.manager_of(team) >= 0; + constexpr size_t kNationalOriginalClub = 4 * 0xb0c + 0x290; + if (!manager_owned && !game.manager_teams.empty() && game.manager_teams[0] == kNoTeam && + game.manager_records.size() >= kNationalOriginalClub + 2) { + const int original_club = int(uint16_t(game.manager_records[kNationalOriginalClub] | + uint16_t(game.manager_records[kNationalOriginalClub + 1]) << 8)); + manager_owned = original_club == team; + } + if (team >= 168 && !manager_owned) { + const size_t at = size_t(team - 168); + if (at >= game.foreign_strength.size()) invalid("missing Source foreign-strength byte"); + out.foreign_strength = game.foreign_strength[at]; + return out; + } + if (team >= 168 && team != kNoTeam) + invalid("manager-controlled foreign-club row needs live TeamRating W-generator context"); + constexpr std::array kFlags{0x0f1, 0x0f2, 0x0f4, 0x0f8, 0x0ff}; + for (size_t i = 0; i < kFlags.size(); ++i) + out.averages[i] = team_average(game, team, kFlags[i]).value; + out.has_squad_values = true; + return out; +} + +void attach_source_values(const GameState& game, OtherGamesRow& row) { + row.home_metadata = source_metadata(game, row.home_team); + row.away_metadata = source_metadata(game, row.away_team); +} + +void add_second_leg_and_winner(OtherGamesRow& row, uint16_t second, bool present, + bool visible, uint8_t flags) { + row.source_second_leg = second; + row.second_leg_array_present = present; + row.second_leg_visible = visible; + if (present) { + // The second fixture is reversed relative to the primary row: its low field belongs + // to the first displayed club and its high field to the second displayed club. + row.second_leg_home_goals = second & 0x1f; + row.second_leg_away_goals = (second >> 5) & 0x1f; + } + if (row.source_result == 0xcccc) return; + int home = row.home_goals; + int away = row.away_goals; + // CupTie reads the second result whenever the descriptor has an array pointer, + // independently of whether its separate detail line is visible or contains 0xcccc. + const uint16_t winner_second = present ? second : 0; + const int home_total = home + (winner_second & 0x1f); + const int away_total = away + ((winner_second >> 5) & 0x1f); + home = home_total; + away = away_total; + if ((flags & 0x10) && home == away && (row.source_result >> 11) == 0) { + home += winner_second & 0x1f; + away += row.away_goals; + } + row.source_winner = home > away ? 0 : away > home ? 1 : 2; +} + +} // namespace + +OtherGamesProjection other_games_from_game(const GameState& game, const TextDb& texts, + int competition, int linked_page, int requested_round, + OtherGamesDisplayMode display_mode, int participant_offset, + bool source_new_selection) { + const StaticMemory& memory = game.memory; + if (competition < 0 || competition >= 0x14) invalid("unsupported competition selector"); + if (linked_page < 0 || linked_page >= kCupEntries) invalid("invalid linked-page index"); + if (!memory.has(kActiveSelectors) || !memory.has(kActiveSelectors + kSelectorCount - 1)) + invalid("missing live active-competition selector list"); + + OtherGamesProjection out; + for (uint32_t i = 0; i < kSelectorCount; ++i) { + const uint8_t id = memory.u8(kActiveSelectors + i); + if (id == 0x14) { + out.selectors.push_back({int(i), -1, {}, false}); + continue; + } + if (id > 0x14 || !in_descriptor_table(find_cup(memory, id))) + invalid("active selector has no supported competition descriptor"); + out.selectors.push_back({int(i), int(id), text(texts, kTextCompetitionButtonNames + id), true}); + } + int entry = resolve_linked_entry(memory, competition, linked_page); + if (source_new_selection) { + std::array advanced{}; + while (in_descriptor_table(entry)) { + if (advanced[size_t(entry)]) invalid("cycle while advancing completed Source stages"); + advanced[size_t(entry)] = true; + const uint32_t at = cup_entry_address(entry); + const uint8_t next = memory.u8(at + 0x16); + if (next == 0) break; + const int count = memory.u8(at + 0x1b); + if (cup_round(memory, entry) < count) break; + if (!in_descriptor_table(next)) invalid("completed stage points outside descriptor table"); + entry = next; + } + } + const uint32_t address = cup_entry_address(entry); + const uint8_t flags = memory.u8(address + 0x14); + const int team_count = memory.u8(address + 0x1a); + const int rounds = memory.u8(address + 0x1b); + const int live_round = cup_round(memory, entry); + if (team_count < 0 || team_count > 0x40 || rounds <= 0 || rounds > 0x40) + invalid("descriptor dimensions outside Source bounds"); + const int round = requested_round < 0 ? std::min(live_round, rounds - 1) : requested_round; + if (round < 0 || round >= rounds) invalid("requested round outside descriptor"); + + out.competition = competition; + out.descriptor_competition = int16_t(memory.u16(address + 0x18)); + out.linked_page = linked_page; + out.entry_index = entry; + out.entry_address = address; + out.flags = flags; + out.knockout = (flags & 4) != 0; + out.two_legs = (flags & 1) != 0; + out.current_round = live_round; + out.round = round; + out.rounds = rounds; + out.group_index = memory.u8(address + 0x1e) >> 4; + out.group_count = memory.u8(address + 0x1e) & 0xf; + out.title = text(texts, kTextCompetitionNames + size_t(competition)); + out.linked_pages = source_linked_pages(memory, entry); + + int round_text = ((flags & 4) ? round : 0) + 1 + memory.u8(address + 0x1c); + if (memory.u8(address + 0x1c) == 1 && round == 0) --round_text; + if (round_text < 0 || round_text >= 32) invalid("Source round-heading index outside table"); + out.round_heading = text(texts, kTextRoundHeadings + size_t(round_text)); + if (kTextRoundHeadings + size_t(round_text) == kTextGroupRound && out.round_heading.size() > 0x10) + out.round_heading[0x10] = char('1' + linked_page); + if (kTextRoundHeadings + size_t(round_text) == kTextGroupCaption && out.round_heading.size() > 0x19) + out.round_heading[0x19] = char('0' + (linked_page == 0 ? 1 : linked_page)); + + // Source +0x1a is participants in this round. The detail/compact toggle is gated on this + // value, and detail mode's ordinary window is 16 participant slots (eight matches). + out.source_participant_count = team_count >> (round & 31); + out.display_mode_toggle_available = out.source_participant_count > 0x10; + if (display_mode != OtherGamesDisplayMode::compact && display_mode != OtherGamesDisplayMode::detail) + invalid("unknown Source display mode"); + const OtherGamesDisplayMode effective_mode = out.source_participant_count <= 0x10 + ? OtherGamesDisplayMode::detail : display_mode; + out.display_mode = effective_mode; + if (participant_offset < 0 || participant_offset > 0x7f || participant_offset % 0x10 != 0) + invalid("participant window offset is not a Source 16-slot boundary"); + // Compact draws the whole round, but the caller separately retains local14. + // Detail redraw only ORs CareerSession_DispatchOtherGames_RuntimeField's high bit; it never resets a retained cursor, + // even when a Source ID-versus-slot selection quirk leaves it past this list. + if (effective_mode == OtherGamesDisplayMode::compact) participant_offset = 0; + out.participant_offset = participant_offset; + out.round_arrows_visible = effective_mode == OtherGamesDisplayMode::detail && rounds > 1; + + // CupGroupOverviewEffects selects the second-leg result array only for descriptors with the exact + // two-leg/knockout flags and when the displayed round has reached that leg. + const uint8_t played = memory.u8(address + 0x1d); + const bool second_leg = out.knockout && (played % 2 != 0 || round < played / 2) && (flags & 5) == 5; + + // CupGroupOverviewEffects gates the fixture panel if this knockout round is in the future, or any + // descriptor in its +0x15 predecessor chain has not completed all its source rounds. + int predecessor = int8_t(memory.u8(address + 0x15)); + std::array seen_predecessors{}; + while (predecessor != -1) { + if (!in_descriptor_table(predecessor) || seen_predecessors[size_t(predecessor)]) + invalid("invalid/cyclic predecessor descriptor chain"); + seen_predecessors[size_t(predecessor)] = true; + const uint32_t pred = cup_entry_address(predecessor); + if (cup_round(memory, predecessor) < memory.u8(pred + 0x1b)) out.unfinished_predecessor = true; + predecessor = int8_t(memory.u8(pred + 0x15)); + } + out.fixtures_available = !out.unfinished_predecessor && (!out.knockout || round <= live_round); + out.display_mode_toggle_available = out.fixtures_available && out.source_participant_count > 0x10; + + if (out.descriptor_competition == 12) out.scheduled_day_mode = true; + // Source paints TEXTD1186 and returns before touching team/result/schedule arrays for a + // blocked future or unfinished stage. Preserve that boundary for incomplete live records. + if (!out.fixtures_available) return out; + + const uint32_t team_list = memory.pointer(address); + const uint32_t first_results = memory.pointer(address + 0x0c); + const uint32_t second_results = memory.pointer(address + 0x10); + if (team_count != 0 && team_list == 0) invalid("missing Source team list"); + if (team_count != 0 && first_results == 0) invalid("missing Source result list"); + if (out.knockout && second_leg && second_results == 0) invalid("missing Source second-leg results"); + + int participant_base = 0; + std::vector group_fixtures; + if (out.knockout) { + participant_base = uint8_t(cup_round_offset(memory, entry, round)); + } else { + const int table_teams = cup_group_schedule_teams(memory, address); + if (table_teams <= 0) invalid("unsupported Source group-round schedule table"); + const int rounds_per_leg = rounds / ((flags & 1) + 1); + if (rounds_per_leg <= 0) invalid("invalid group schedule leg count"); + group_fixtures = generate_fixtures(table_teams, round + 1, rounds_per_leg, 0); + } + + int row_participants = out.knockout ? out.source_participant_count : team_count; + int visible_participants = row_participants; + if (out.knockout && effective_mode == OtherGamesDisplayMode::detail) + visible_participants = std::min(visible_participants, 0x10); + const int begin = participant_offset; + const int end = out.knockout ? std::min(row_participants, begin + visible_participants) : row_participants; + if (out.scheduled_day_mode && !memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) invalid("missing live Source date for scheduled competition"); + for (int p = out.knockout ? begin : 0; p + 1 < end; p += 2) { + int home = -1, away = -1, match = p / 2; + size_t result_slot = 0; + if (out.knockout) { + const int slot = participant_base + p; + if (!memory.has(team_list + uint32_t(slot) * 2 + 1)) invalid("truncated Source knockout team list"); + home = memory.u16(team_list + uint32_t(slot) * 2); + away = memory.u16(team_list + uint32_t(slot + 1) * 2); + result_slot = size_t(slot / 2); + } else { + const int fixture = p / 2; + if (size_t(fixture) >= group_fixtures.size()) invalid("group fixture count does not match descriptor"); + const Fixture& f = group_fixtures[size_t(fixture)]; + if (!memory.has(team_list + uint32_t(f.home) * 2 + 1) || + !memory.has(team_list + uint32_t(f.away) * 2 + 1)) invalid("truncated Source group team list"); + home = memory.u16(team_list + uint32_t(f.home) * 2); + away = memory.u16(team_list + uint32_t(f.away) * 2); + result_slot = size_t(round) * size_t(team_count / 2) + size_t(fixture); + } + const uint32_t result_address = first_results + uint32_t(result_slot * 2); + if (!memory.has(result_address + 1)) invalid("truncated Source result list"); + const uint16_t result = memory.u16(result_address); + OtherGamesRow row = make_row(game, home, away, result, match); + if (out.scheduled_day_mode) { + row.kind = OtherGamesRowKind::scheduled_competition; + row.played = false; + row.home_goals = row.away_goals = 0; + row.scheduled_source_day = uint32_t(memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)) + + uint32_t(int32_t(int16_t(result))); + } else if (out.knockout) { + uint16_t second = 0xcccc; + const bool second_present = second_results != 0; + if (second_results != 0) { + const uint32_t second_address = second_results + uint32_t(result_slot * 2); + if (!memory.has(second_address + 1)) invalid("truncated Source second-leg result list"); + second = memory.u16(second_address); + } + add_second_leg_and_winner(row, second, second_present, second_leg, flags); + } + attach_source_values(game, row); + out.rows.push_back(std::move(row)); + } + if (!out.knockout && team_count > 2) out.group_tables.push_back(cup_group_table(memory, address)); + return out; +} + +} // namespace bmh diff --git a/src/game/other_games.hpp b/src/game/other_games.hpp new file mode 100644 index 0000000..a42892b --- /dev/null +++ b/src/game/other_games.hpp @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "formats/textd.hpp" +#include "game/state.hpp" +#include "game/table.hpp" + +namespace bmh { + +enum class OtherGamesRowKind : uint8_t { match, scheduled_competition }; +// Source local20==0 (`compact`) draws the complete round in dense six-pixel rows; +// local20==1 (`detail`) draws a 16-participant window in the taller 16-pixel layout. +enum class OtherGamesDisplayMode : uint8_t { compact, detail }; + +struct OtherGamesClubMetadata { + bool has_squad_values = false; + std::array averages{}; + // -1 for squad-backed clubs, otherwise the raw ForeignClubStrength byte for foreign-club rendering. + int foreign_strength = -1; +}; + +// One Source row in the ordinary CupGroupOverviewEffects desk view. Names and text are kept in +// Original encoding so the presentation layer can pass them through the existing FNT3 path. +struct OtherGamesRow { + OtherGamesRowKind kind = OtherGamesRowKind::match; + int home_team = -1; + int away_team = -1; + std::string home_name; + std::string away_name; + uint16_t source_result = 0xcccc; // primary +0x0c result, always retained by Source + uint16_t source_second_leg = 0xcccc; // reversed +0x10 result, shown only in Source's local4c case + bool second_leg_array_present = false; + bool second_leg_visible = false; + bool played = false; + int home_goals = 0; + int away_goals = 0; + int second_leg_home_goals = 0; + int second_leg_away_goals = 0; + // CupTie result encoding: 0 home, 1 away, 2 tied; -1 when primary is 0xcccc. + int source_winner = -1; + // Competition id 12 stores signed day offsets, not scorewords. + uint32_t scheduled_source_day = 0; + // Void6 metadata is kept per side; foreign-club labels are formatted by the UI with the + // Original EXE strings, while these values remain source-faithful raw data. + OtherGamesClubMetadata home_metadata; + OtherGamesClubMetadata away_metadata; + // The zero-based match in the descriptor's current round. This is presentation metadata, + // not a writable result-array index supplied by the UI. + int source_match = -1; +}; + +struct OtherGamesSelector { + int slot = -1; + int competition = -1; + std::string title; + bool active = false; +}; + +struct OtherGamesLinkedPage { + int ordinal = -1; + int entry_index = -1; + int competition = -1; + int group_index = 0; + int group_count = 0; +}; + +struct OtherGamesProjection { + int competition = -1; + int descriptor_competition = -1; + int linked_page = 0; + int entry_index = -1; + uint32_t entry_address = 0; + uint8_t flags = 0; + bool knockout = false; + bool two_legs = false; + int current_round = 0; + int round = 0; + int rounds = 0; + int group_index = 0; + int group_count = 0; + std::string title; + std::string round_heading; + std::vector selectors; + // InDescriptorTable's flattened linked-stage/group selector. The ordinal is the value retained by + // Source CareerSession_FormatError_RuntimeField8 and consumed by FindCup on the next draw. + std::vector linked_pages; + // Source's toggle gate uses participants in the displayed round (>16), before rows are + // paired into matches. Detail mode shows a 16-participant window; compact mode shows all. + int source_participant_count = 0; + int participant_offset = 0; + bool display_mode_toggle_available = false; + OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail; + bool round_arrows_visible = false; + bool fixtures_available = true; + bool unfinished_predecessor = false; + bool scheduled_day_mode = false; + std::vector group_tables; + std::vector rows; +}; + +// Const projection of the ordinary menu-5 call to CupGroupOverviewEffects. This API intentionally models +// only the visible values: Original entry separately updates serialized CareerSession_FormatError_RuntimeField3/selector-12 state, +// while complete/compact and page navigation persist the active manager's CareerSession_DispatchOtherGames_RuntimeField byte. It is +// therefore not evidence that the entire Original menu interaction is Native-neutral. +// `linked_page` follows the descriptor's Source +0x17 parallel-group link, then +0x16 next-stage +// link. `round == -1` selects CupRound's live round; otherwise it is range-checked. +// `participant_offset` is Source's low-seven-bit display cursor (multiples of 16). The +// displayed-round group row list remains complete; the mode/offset applies to knockout rows. +OtherGamesProjection other_games_from_game(const GameState& game, const TextDb& texts, + int competition = 0, int linked_page = 0, + int round = -1, + OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail, + int participant_offset = 0, + bool source_new_selection = true); + +} // namespace bmh diff --git a/src/game/pending_offer.hpp b/src/game/pending_offer.hpp new file mode 100644 index 0000000..a0bc2b3 --- /dev/null +++ b/src/game/pending_offer.hpp @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include + +#include "game/club_player_detail.hpp" +#include "game/transfer_allocator.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +// Explicit manual DispatchClubPlayerPendingOffers answers; absence never means NEIN. +enum class PendingOfferAnswer { yes, no, unsupported }; +enum class PendingOfferQuestionKind { salary_demand, severance }; +struct PendingOfferQuestion { + PendingOfferQuestionKind kind = PendingOfferQuestionKind::salary_demand; + int manager = -1; + int raw_offer_slot = -1; + int offered_player = -1; + int clicked_player = -1; // original identity, never remapped to offered_player + int clicked_source_slot = -1; // fixed throughout this DispatchClubPlayerPendingOffers invocation + std::string current_clicked_name; // PlayerName reads this fixed slot at each question + uint32_t amount = 0; + uint16_t source_flags = 1; // PresentManagerDialog: salary1, severance0x305 + std::string original_message; // Original-encoded text, not UTF-8 +}; + +enum class PendingOfferTransferChoiceKind { bid, decline, unsupported }; +struct PendingOfferTransferChoice { + PendingOfferTransferChoiceKind kind = PendingOfferTransferChoiceKind::unsupported; + int raw_bid_slot = -1; +}; +struct PendingOfferNotice { + int manager = -1; + int raw_offer_slot = -1; + uint32_t text_address = 0; + std::string original_message; +}; +// PendingOfferAnswer reads the unsaved EXE byte MatchEventsDisabled. The caller must copy its observed +// value into this per-dispatch context; neither an absent save byte nor a +// default value is evidence that the allocator is enabled. +using PendingOfferAllocatorGate = TransferAllocatorContext; +struct PendingOfferHooks { + std::function answer; + std::function select_transfer; + // Read-only owned notices/ACKs; installing it changes neither bytes nor RNG. + std::function notice; + PendingOfferAllocatorGate human_buyer_allocator_gate = PendingOfferAllocatorGate::unsupported; + // PresentLoanReturn is a full-screen diagnostic, distinct from SystemIdentity notices. + // Returning acknowledges it; throwing leaves App retryable. + std::function program_error; +}; +struct PendingOfferResult { + bool completed = false; + int processed = 0; + int salary_accepted = 0; + int transferred = 0; + int buyer_funds_refused = 0; + int buyer_allocator_blocked = 0; + int buyer_no_room = 0; + bool forced_acceptance = false; // sticky local18 from DispatchClubPlayerPendingOffers +}; + +// AdvanceTurn's post-desk caller has transient state which is not saved in FBM. The +// App must own and explicitly identify the supported interactive mode; the +// default/unsupported value never means that missing transient bytes were zero. +enum class PendingOfferDeskRuntimeMode { unsupported, normal_interactive }; +struct PendingOfferDeskRequest { + PendingOfferDeskRuntimeMode runtime_mode = PendingOfferDeskRuntimeMode::unsupported; + int manager_count = -1; // caller's validated desk-loop count + int manager_position = -1; // current position in the saved NextDeskManager permutation +}; + +// ClubPlayerDetailFromGame's ordinary pending action -> DispatchClubPlayerPendingOffers, not the legacy answer_offers. +// Resolve the clicked slot/board once; execute every active-owner raw offer0..3. +// Intended for a staged GameState + both RNGs owned by the caller: an unsupported +// hook/path reports failure and may follow earlier batch effects, so discard the +// staged state/RNGs on report.unsupported. A distinct human buyer is supported only +// for ordinary sales and an explicitly supplied unsaved PendingOfferAnswer gate. Funds refusal, +// a gate-suppressed allocator and a full buyer squad are expected Source partial +// outcomes; their counters distinguish them from an actual transfer. Loans and +// unported error30/31/32 boundaries remain unsupported. No legacy weekly caller changes. +PendingOfferResult process_player_card_pending_offers(GameState&, const ClubPlayerDetailSelection&, + GameRandom&, WatcomRandom&, const PendingOfferHooks&, MinuteReport&); + +// AdvanceTurn post-desk adapter. It validates native manager +// count/order/cursor, restores ActiveManager from NextDeskManager, anchors the DispatchClubPlayerPendingOffers batch at +// the first raw owned offer whose player exists in an ordinary owned squad slot, +// and preserves offers for other managers. Missing offered players require the +// explicit PresentLoanReturn presenter, then scanning continues in raw order. A genuine +// national takeover uses its current national squad for owner0 and the retained +// raw club record for an ordered owner1..3; the active manager list stays reduced. +// DispatchClubPlayerPendingOffers keeps the first resolved anchor board for all salary questions. +// Verified old-club offers missing from the national squad retain M121's quiet +// cleanup improvement. A present national player follows Source's actual salary +// and transfer path, including its national-board quirk. On the last desk +// only, it performs Source's global four-entry pool/offer cleanup and sets DeskPosition +// to the completed manager count before the caller starts simulation. As with the +// manual batch API, callers must stage GameState and both RNGs and discard on +// unsupported; no weekly or replay wrapper behavior changes. +PendingOfferResult process_natural_pending_offers_after_desk(GameState&, + const PendingOfferDeskRequest&, GameRandom&, WatcomRandom&, + const PendingOfferHooks&, MinuteReport&); + +// AdvanceTurn's reduced-count national nomination desk has a distinct post-desk +// owner rule: it restores NextDeskManager[0] even though the active national runtime has +// one manager. Validate the precise 4006 calendar/competition identity, then +// reuse the post-desk AdvanceTurn/DispatchClubPlayerPendingOffers sequence above, including owned offers. +// The saved order prefix is preserved and bounded by the saved original count, +// rather than interpreted as a count-one permutation. Call on staged state and +// both RNGs; unavailable/declined presenters require complete caller rollback. +PendingOfferResult process_national_nomination_pending_after_desk(GameState&, + const PendingOfferDeskRequest&, GameRandom&, WatcomRandom&, + const PendingOfferHooks&, MinuteReport&); + +} // namespace bmh diff --git a/src/game/poach.cpp b/src/game/poach.cpp new file mode 100644 index 0000000..bdc2c73 --- /dev/null +++ b/src/game/poach.cpp @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/poach.hpp" + +#include + +#include "game/messages.hpp" +#include "game/month.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kAttempts = 0x8b6; // five player ids, 0xffff free +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 rows of 0x58 bytes +constexpr uint32_t kListRow = 0x58; +constexpr size_t kPoolFirst = 0xb70; // CareerRuntimeField: squad slot of list row 0 +constexpr uint32_t kOfferSlots = ::bmh::layout::OfferSlots; // OfferSlots: 4 words, -1 free +constexpr int kBigSquadClubs = 90; // TeamsWithSquads +// Attempt: how many players of each position a club wants (MonthRuntimeField4 / MonthRuntimeField5) +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; + +uint16_t attempt(const GameState& g, int m, int i) { + const size_t at = size_t(m) * kRecordSize + kAttempts + size_t(i) * 2; + return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); +} + +// PoachAttemptsLeft(player, club): the asking percentage of the club for the player, or -1 with +// the reason in `messages`. A club of a human manager asks 100 %. +int club_asking_percent(const GameState& g, int player, int club, std::vector& messages, WatcomRandom& rand) { + if (g.manager_of(club) >= 0) return 100; + const Player& p = g.players.at(size_t(player)); + const int position = int(p.w364 & 3); + const int strength = p.strength(true); // Strength(w35c, 1) + const int8_t* wanted = club < kBigSquadClubs ? kWantedBig : kWantedSmall; + // SquadCount(club, 0): the fit players + if (squad_count(g, club, 0) < (club < kBigSquadClubs ? 3 : 0) + 0xe) { + messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer) + g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer2)); + return -1; + } + int sum[4], count[4]; + for (int k = 0; k < 4; k++) { + // QuoteNationalFriendlyMatch with 0x607 + the position bit: sum of the fit players and their number + const TeamAverage a = team_average(g, club, uint16_t((1 << (k + 4)) + 0x607)); + sum[k] = int16_t(a.value); + count[k] = int8_t(a.players); + } + const int short_of = int16_t(wanted[position] - count[position]); // local_24 + if (short_of >= 3 || (short_of == 0 && position == 0)) { + // the club needs him (a club always keeps its second goalkeeper) + messages.push_back(g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer3)); + return -1; + } + int percent = short_of < 0 ? short_of * 0x18 + 0x8c : short_of * 16 + 0x82; // local_34 + if (percent < 0x5a) percent = 0x5a; + int averages = 0; + for (int k = 0; k < 4; k++) averages = int16_t(averages + sum[k] / count[k]); + const int team = averages / 4; + int relative = team != 0 ? int16_t(strength * 100 / team) : 100; // local_30 + if (relative < 0x65) { + percent -= std::clamp(100 - relative, 0, 0x14); // ClampInteger + } else { + const int over = int16_t(relative - 100) >> 1; + percent = int16_t(percent + int16_t(over * over)); + } + if (short_of != 0 && percent >= 0x100) { + messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer4)); // FINANCIAL FAIRPLAY + return -1; + } + if (percent > 0xbe) percent = 0xbe; + return uint8_t(rand.range(0xc, 0x14) + percent); +} + +} // namespace + +int poach_attempts_left(const GameState& g, int manager) { + int left = 0; + for (int i = 0; i < 5; i++) + if (attempt(g, manager, i) == 0xffff) left++; + return left; +} + +PoachStart start_poach(GameState& g, int manager, int squad_slot, WatcomRandom& rand) { + PoachStart out; + out.manager = manager; + out.squad_slot = squad_slot; + const size_t rec = size_t(manager) * kRecordSize; + if (attempt(g, manager, 4) != 0xffff) { + out.status = PoachStatus::attempts_used; + out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2)); + return out; + } + if (g.manager_records.at(rec + 0x220) >> 5 == 1) { // PushBack + out.status = PoachStatus::transfer_ban; + out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer)); + return out; + } + if (squad_slot < 0 || size_t(squad_slot) >= kPoolFirst || g.squad_slots.at(size_t(squad_slot)) == 0xfff) return out; + out.player = g.squad_slots.at(size_t(squad_slot)) & 0xfff; + out.club = slot_team(squad_slot); // SlotTeam + if (out.club < 0 || out.club == g.manager_teams.at(size_t(manager))) return out; + // BoughtEntry: a player on loan (table Career_RemoveJoinLoans_RuntimeField) + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xfff) == out.player) { + out.status = PoachStatus::on_loan; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer)); + return out; + } + } + for (int i = 0; i < 5; i++) + if (attempt(g, manager, i) == out.player) { + out.status = PoachStatus::tried_before; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer2)); + return out; + } + // PlayerOnTransferListFirstPoolSlots: the player is on the transfer list (first 44 pool slots) + for (size_t s = kPoolFirst; s < kPoolFirst + 0x2c; s++) + if ((g.squad_slots.at(s) & 0xfff) == out.player) { + out.status = PoachStatus::on_transfer_list; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer3)); + return out; + } + const int percent = club_asking_percent(g, out.player, out.club, out.messages, rand); + if (percent < 0) { + out.status = PoachStatus::club_refuses; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer5)); + return out; + } + out.asking_percent = percent; + // RowWhose: a special row whose OfferSlots word is free + int k = 0; + while (k < 4 && g.memory.u32(kOfferSlots + uint32_t(k) * 4) != 0xffffffffu) k++; + if (k == 4) { + out.status = PoachStatus::market_busy; + out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer4)); + finish_poach(g, out); + return out; + } + out.offer_row = k; + const int demand = rand.range(0x50, 100); + // Range2(slot, 0, percent, demand, 0, k): the row like a market row of the club. + // (Its salary floor for a club of a human manager searches the buyer's own squad for + // the player and so never applies; the 0x8000 flag of the club word is kept.) + const uint32_t row = kTransferList + uint32_t(0x28 + k) * kListRow; + uint16_t club_word = uint16_t(out.club); + if (g.manager_of(out.club) >= 0) club_word |= 0x8000; + g.memory.set16(row + 8, club_word); + for (int b = 0; b < 4; b++) g.memory.set16(row + uint32_t(b) * 2, 0xffff); + g.memory.set8(row + 0x54, uint8_t(percent)); + g.memory.set8(row + 0x55, uint8_t(demand)); + uint32_t fee = 0, salary = 0; + market_value(g, squad_slot, 0, uint8_t(percent), fee, salary, 1, 0, rand); + g.memory.set32(row + 0x2c, fee); + g.memory.set32(row + 0x30, salary); + g.squad_slots.at(kPoolFirst + 0x28 + size_t(k)) = uint16_t(out.player); + out.status = PoachStatus::ready; + return out; +} + +void finish_poach(GameState& g, const PoachStart& poach) { + if (poach.offer_row >= 0) { + g.squad_slots.at(kPoolFirst + 0x28 + size_t(poach.offer_row)) = 0xfff; + g.memory.set32(kOfferSlots + uint32_t(poach.offer_row) * 4, 0xffffffffu); + } + for (int i = 0; i < 5; i++) + if (attempt(g, poach.manager, i) == 0xffff) { + const size_t at = size_t(poach.manager) * kRecordSize + kAttempts + size_t(i) * 2; + g.manager_records.at(at) = uint8_t(poach.player); + g.manager_records.at(at + 1) = uint8_t(poach.player >> 8); + break; + } +} + +} // namespace bmh diff --git a/src/game/poach.hpp b/src/game/poach.hpp new file mode 100644 index 0000000..1184007 --- /dev/null +++ b/src/game/poach.hpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Poaching ("Abwerben", transfer screen menu 17, H2 p. 70; BMH.exe V2.24 + supported rule profile patch): +// the manager picks a player of another club in the league tables and makes him an offer +// that is decided at once. Button 4 of the transfer screen Reset: +// +// - at most five attempts per season: the players tried are kept in manager record +// +0x8b6 (5 words, 0xffff free; cleared at the season start, season.cpp) - CareerSession_DispatchPoachUi_TextPointer2 +// - not with a transfer ban (record +0x220 >> 5 == 1, PushBack, CareerSession_DispatchPoachUi_TextPointer) +// - not for a player on loan (BoughtEntry, Poach_StartPoach_TextPointer), not twice for the same player +// (Poach_StartPoach_TextPointer2), not for a player on the transfer list (PlayerOnTransferListFirstPoolSlots, Poach_StartPoach_TextPointer3) +// - the club must let him go (PoachAttemptsLeft): its squad must be big enough, the position +// must not be short (and a club keeps its second goalkeeper); the asking percentage +// follows how much the club needs him and how good he is compared with the team +// - the offer uses one of the special list rows 40..43 (RowWhose: a row whose +// OfferSlots word is free, else "Transfermarkt überlastet"), prepared like a market +// row by Range2: asking percentage, demand W(80, 100), market value and salary. +// +// The offer itself is the ordinary offer editor (desk_actions.hpp, OpenTransferEditor) on that +// row with `poach` set; its submit (SubmitTransferBidSourceHumanBuyer) decides at once. finish_poach frees the +// row again and counts the attempt, as the original does when the editor returns. + +#include +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +enum class PoachStatus : uint8_t { + ready, // the offer row is prepared: open the offer editor on it + attempts_used, // five attempts this season (CareerSession_DispatchPoachUi_TextPointer2) + transfer_ban, // the DFB has banned all transfers (CareerSession_DispatchPoachUi_TextPointer) + invalid, // no player, or a player of the own club + on_loan, // "Dieser Spieler ist nur ausgeliehen!" (Poach_StartPoach_TextPointer) + tried_before, // "Nur 1 Abwerbeversuch pro Spieler pro Saison!" (Poach_StartPoach_TextPointer2) + on_transfer_list, // Poach_StartPoach_TextPointer3 + club_refuses, // PoachAttemptsLeft refused (its reason, then Poach_StartPoach_TextPointer5) + market_busy, // no free special row (Poach_StartPoach_TextPointer4); the attempt counts +}; + +struct PoachStart { + PoachStatus status = PoachStatus::invalid; + std::vector messages; // the original's message boxes, in order + int manager = -1; + int squad_slot = -1; // absolute SquadSlots slot of the player at his club + int player = -1; + int club = -1; + int offer_row = -1; // k (0..3); the list row is 40 + k, its pool slot 0xb70 + 40 + k + int asking_percent = 0; +}; + +// Attempts left this season (record +0x8b6). +int poach_attempts_left(const GameState& g, int manager); + +// Button 4 after the player was picked (FriendlyMatchScreen returned `squad_slot`): the checks, +// PoachAttemptsLeft, RowWhose and Range2. Draws W(12, 20) (asking percentage), W(80, +// 100) (demand) and what the market value draws. `market_busy` counts the attempt itself. +PoachStart start_poach(GameState& g, int manager, int squad_slot, WatcomRandom& rand); + +// When the offer editor has returned: the pool slot of the row is emptied, its OfferSlots +// word freed and the attempt recorded in +0x8b6. +void finish_poach(GameState& g, const PoachStart& poach); + +} // namespace bmh diff --git a/src/game/prediction.cpp b/src/game/prediction.cpp new file mode 100644 index 0000000..17c3dfb --- /dev/null +++ b/src/game/prediction.cpp @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/prediction.hpp" + +#include +#include + +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; // one slot of the board + +// Static league tables of V2.24 (not part of the savegame): +// (European places per league, CareerSession_InstallLeagueSizes_RuntimeField, are kLeagueEurope of the loaded game; league 0 uses 4) +// (the relegation places per league, CareerSession_InstallLeagueSizes_RuntimeField2, are kLeagueRelegation of the loaded game) +constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField: clubs in the league system + +// Text of a pointer variable of the text table TextPointerTable. +} // namespace + +int table_prediction(GameState& g, int team, int mode, std::array& buf, int* size_word) { + buf.fill(1); + int league = team_league(team); // local_30 + if (league >= kLeagueCount) return 0; // reads CareerRuntimeField6[0] = 0 as the round count + const int rounds = int8_t(g.league_rounds.at(size_t(league))); // local_1c + const int matchdays = league_matchdays(league); // LeagueMatchdayCounts + if (rounds < 2 || matchdays <= rounds) return 0; + const int manager = g.manager_of(team); // local_18, 0xFF = none + // (Fill would refresh the desk warning flags PredictionRuntimeField.. here; they are + // run-time only and not needed by the game logic.) + const size_t rec = size_t(manager) * kRecord; + const int size = kLeagueSizes[league]; // local_2c + if (size_word) *size_word = size; // (stored as a word, see the header) + if (team >= kLeagueTeams) return 9; + const int pos = team - league_first_team(league); // local_24 + const int target[3] = {0, league == 0 ? 4 : kLeagueEurope[league], size - kLeagueRelegation[league]}; + + int from = 0; // local_10 + if (mode > 3) { + from = rounds - 5 * (mode >> 2); + if (from < 0) from = 0; + } + auto per_game = [&](const LeagueTable& t, int club) { + const int games = t.games(club); + return games ? t.points[club] * 500 / games : 0; // the original divides by zero here + }; + int own_rate = 1500; // local_34: three points per remaining game + if (mode != 1) own_rate = per_game(compute_league_table(g, league, from, rounds, 3, 0), pos); + const LeagueTable full = compute_league_table(g, league, 0, rounds, 7, 0); + int points[20] = {}, remaining[20] = {}; // acStack_60, acStack_4c + for (int c = 0; c < size; c++) { + points[c] = full.points[c]; + remaining[c] = int8_t(matchdays - full.games(c)); + } + // The scratch table the rates of the other clubs are read from: the recent form table + // for mode >= 4, otherwise still the full table. + const LeagueTable rates = mode > 3 ? compute_league_table(g, league, from, rounds, 3, 0) : full; + uint16_t own = uint16_t(points[pos] * 500 + remaining[pos] * own_rate); // local_28 (low word) + + int ahead = size; // local_20: ranks that are out of reach + if (mode == 1) { + ahead = 0; + for (int c = 0; c < size; c++) ahead += int(own) < points[c] * 500; + } + for (int r = 0; r < ahead; r++) buf.at(size_t(r)) = 0; + + int league_index = league; // local_30 is changed by the league name of message 1 + if (mode == 1) { + for (int k = 0; k < 3; k++) { + if (buf.at(size_t(target[k])) != 0) continue; + if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> k & 1)) continue; + // the goal can no longer be reached + if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << k); + std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer2); + if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer3); + if (k == 1) { + std::string tail; + if (league_index == 0) { + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer4); + } else if (league_index == 2 || league_index == 3) { + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer5); + } else { + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer6); + if (league_index > 2) league_index--; + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer + uint32_t(league_index) * 4); // league name + tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer7); + } + msg += tail; + } + if (k == 2) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer8); + if (manager >= 0) post_composed(g, manager, msg); + } + own = uint16_t(points[pos] * 500); + } + + int behind = 0; // local_14: clubs that can no longer catch up + for (int c = 0; c < size; c++) { + if (c == pos) continue; + int rate; + if (mode == 1) rate = 1500; + else if (mode == 2) rate = 0; + else rate = int16_t(per_game(rates, c)); + if (uint16_t(points[c] * 500 + remaining[c] * rate) < own) behind++; + } + int r = 0; + for (; r < behind; r++) buf.at(size_t(size - r - 1)) = 0xFF; + if (mode != 1) { + if (r == size) r++; // cannot happen: the club itself is never counted + buf.at(size_t(size - r - 1)) = 1; + } + if (mode == 1) { + for (int k = 0; k < 3; k++) { + if (buf.at(size_t(target[k])) != 0xFF) continue; + if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> (k + 3) & 1)) continue; + // the goal is secured (or relegation avoided / certain) + if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << (k + 3)); + std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer9); + if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer10); + else if (k == 1) + msg += message_text(g, league_index == 0 ? ::bmh::layout::Prediction_TablePrediction_TextPointer11 : (league_index == 2 || league_index == 3) ? ::bmh::layout::Prediction_TablePrediction_TextPointer12 : ::bmh::layout::Prediction_TablePrediction_TextPointer13); + else msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer14); + msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer15); + // without a manager the original posts to "manager" 0xFE; not needed here + if (manager >= 0) post_composed(g, manager, msg); + } + } + int first = 0; + while (first < 24 && buf[size_t(first)] == 0) first++; + return (first + 1) & 0xFF; +} + +static uint32_t season_bonus_impl(GameState& g, int manager, int team, int board_slot, int rank, bool pay) { + const int league = team_league(team); + uint32_t amount = 0; + if (league == 0 && rank == 0) amount = pay_bonus(g, manager, board_slot, 3, pay); + if (amount == 0 && rank < 5) amount = pay_bonus(g, manager, board_slot, 4, pay); + if (amount == 0 && rank < 10) amount = pay_bonus(g, manager, board_slot, 5, pay); + if (amount == 0 && league < kLeagueCount && rank < kLeagueSizes[league] - kLeagueRelegation[league]) + amount = pay_bonus(g, manager, board_slot, 6, pay); + return amount; +} + +uint32_t season_bonus(GameState& g, int manager, int board_slot, int rank, bool pay) { + return season_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),board_slot,rank,pay); +} + +static uint32_t expected_bonus_impl(GameState& g, int manager, int team, int rank, int board_slot, int player, bool fitness) { + static const uint8_t kPerSeason[3] = {0, 34, 25}; // PredictionRuntimeField2: -, points, appearances + static const uint8_t kGoals[4] = {0, 2, 4, 8}; // PredictionRuntimeField3: goals by position + const int position = int(g.players.at(size_t(player)).w364 & 3); + if (rank == 0xFF) { + std::array buf; + const int r = table_prediction(g, team, 4, buf); + rank = r == 0 ? 0xB : r + 1; + } + const size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + const uint32_t base = uint32_t(g.tactics.at(slot + 0x50) | g.tactics.at(slot + 0x51) << 8 | + g.tactics.at(slot + 0x52) << 16) | uint32_t(g.tactics.at(slot + 0x53)) << 24; + uint32_t sum = 0; + for (int k = 0; k < 3; k++) { + uint32_t times = k == 0 ? kGoals[position] : kPerSeason[k]; + if (fitness && k != 1) { + // the fitness correction: a player weaker than the team average (QuoteNationalFriendlyMatch + // flags 499) earns goal and appearance bonuses less often - PredictionRuntimeField4 per gap + static const uint8_t kPerGap[3] = {1, 0, 5}; // PredictionRuntimeField4 + const uint32_t w = g.players.at(size_t(player)).w35c; + int gap = int16_t(team_average(g, team, 499).value - + int((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) >> 1)); + if (gap < -1) gap = -1; + const int t = int(times) - kPerGap[k] * gap; + times = t < 0 ? 0 : uint32_t(t); + } + sum += g.tactics.at(slot + 0x12 + size_t(k)) * base / 100 * times / 12; + } + return season_bonus_impl(g, manager, team, board_slot, rank & 0xFF, false) / 12 + sum; +} + +uint32_t expected_bonus(GameState& g, int manager, int rank, int board_slot, int player, bool fitness) { + return expected_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),rank,board_slot,player,fitness); +} + +uint32_t expected_bonus_parked_club_source(GameState& g, int rank, int board_slot, int player, bool fitness) { + constexpr size_t team_at=4*kRecord+0x290; + if(g.manager_teams!=std::vector{kNoTeam} || !g.memory.has(::bmh::layout::CoachActive) || + g.memory.u8(::bmh::layout::CoachActive)==0 || !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 || + !g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + g.manager_records.size()<5*kRecord || + (int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=kNoTeam || + board_slot<0 || board_slot>=24 || g.tactics.size()<5*kBoard) + throw std::invalid_argument("expected_bonus: invalid FindManagerForClub parked club context"); + const int team=int(g.manager_records[team_at]) | int(g.manager_records[team_at+1])<<8; + if(team<0 || team>=kLeagueTeams) + throw std::invalid_argument("expected_bonus: parked record4 has no ordinary club"); + return expected_bonus_impl(g,4,team,rank,board_slot,player,fitness); +} + +} // namespace bmh diff --git a/src/game/prediction.hpp b/src/game/prediction.hpp new file mode 100644 index 0000000..493ec9e --- /dev/null +++ b/src/game/prediction.hpp @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Table prediction and bonus expectations of human managers (BMH.exe V2.24). +// +// table_prediction Void5 which final ranks a club can still reach / has secured +// expected_bonus ContractOffer bonus a player on the tactics board can expect +// season_bonus SeasonBonus the board's season bonus (title, Europe, staying up) +// +// team_rating (rating.cpp) uses them for the players of human managers: a player who can +// expect a large bonus relative to his base pay tries harder (+5 with some probability). +// As a side effect the prediction posts the "still possible" / "no longer possible" +// messages about the season goals (champion, Europe, relegation) to the manager, once per +// goal and season (bits 0-5 of manager record +0x28b). + +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +// Void5(team, mode, buf). Fills buf[0..23], one entry per final rank: +// 0 the rank can no longer be reached (at least that many clubs stay ahead) +// 1 the predicted rank (modes other than 1) +// 0xFF a rank the club cannot fall to any more +// and returns the first rank (1-based) that is not 0, i.e. the best reachable rank. +// mode 1: maximum points = points + 3 per remaining game for every club (and messages); +// mode 2: the club's own points per game projected, the others stay where they are; +// mode 3: every club projected with its own points per game; +// mode >= 4: as 3, but the points per game over the last 5 * (mode / 4) matchdays. +// `size_word` receives the league size, which the original stores as a word in its frame +// (local_2c) unless it returns early (before the second matchday etc.; then it stays +// untouched). The side ratings read that stack word as a stale value, see team_rating. +// Returns 0 before the second matchday and after the last one (and for leagues >= 9), +// 9 for clubs outside the league system (ids from 138 on). +int table_prediction(GameState& g, int team, int mode, std::array& buf, int* size_word = nullptr); + +// ContractOffer(manager, predicted rank, board slot, player, 0): goal, point and appearance +// bonus of the board slot, each weighted by how often it is earned (goals by position: +// PredictionRuntimeField3, points 34, appearances 25 per season), plus the season bonus for the +// predicted rank, all divided by 12. `rank` 0xFF means: predict it (table_prediction mode 4). +// Only the variant without the fitness correction (last argument 0) is ported. +uint32_t expected_bonus(GameState& g, int manager, int rank, int board_slot, int player, bool fitness = false); + +// Checked FindManagerForClub record4 variant for a club parked during national takeover. +// Read the actual club from record4 without adding it to the active manager list. +uint32_t expected_bonus_parked_club_source(GameState& g, int rank, int board_slot, int player, bool fitness = false); + +// SeasonBonus(manager, board slot, rank, 0): season bonus of the slot for a final rank: +// title (league 0 only, rank 0), top 5, top 10, staying up (bonus indices 3-6 of the slot, +// the first one that is set and applies). Not paid. +uint32_t season_bonus(GameState& g, int manager, int board_slot, int rank, bool pay = false); + +} // namespace bmh diff --git a/src/game/presentation.hpp b/src/game/presentation.hpp new file mode 100644 index 0000000..e9f7170 --- /dev/null +++ b/src/game/presentation.hpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// What the original shows during a matchday, as events for the UI (BMH.exe V2.24 + supported rule profile). +// +// The match engine reproduces the random numbers of the original's live desk, its message +// boxes and animations, but draws nothing. Where the original would show something it +// appends a ShowEvent (MatchEngine::show, when set) with the values the original computes +// for the picture - the UI renders from these and never draws random numbers itself, so +// rendering, hovering or replaying a frame cannot change the game. +// +// The event descriptions document the observed match activity; the +// screen coordinates are those of the 320x240 work screen PresentationRuntimeField unless noted. +// +// Booking EventImpl, layout field-layout field: the message box of a foul. Shown when +// MatchEngineRuntimeField12 is set and the offender's team (or, for flag 0x80, the +// opponent) is watched: team flag 0x80 (live desk; for a yellow card only +// without button MatchEngine_EventImpl_ExecutableField) or 0x40 (ticker; button MatchEngine_EventImpl_ExecutableField2 for a +// yellow, MatchEngine_EventImpl_ExecutableField3 otherwise switches it off). Text: LiveMatchday_FormatError_TextPointer2[kind] +// (0 yellow, 1 red, 2 injury, 3 second yellow) + the player's name, for a +// yellow card also his yellow cards of the season (Cstring); the side's +// colours (Button(side | 0x40)), the scoreboard of the match flashes +// (DcThat(6, group, match)), the text is drawn at (0x5f, 0x27) +// (DrawnFirstBy), a whistle (PauseMusic(0x11), not for injuries), a delay +// (AdvanceStep(3 + (kind != 0))) and the box waits for a click +// (PatternRect). `shown` tells whether the box appears; the event is +// appended for every foul so that a ticker can list it. +// Substitution Injure after a foul: `player` leaves, `other` comes on. +// Chance the live desk after a chance (layout field-layout field, EndPhase): kind 0 open +// play, 1 penalty / free kick, 2 follow-up, 3 corner; the shooter, the +// assistant, the distance shown (MatchEngineRuntimeField15, kind 1), the goal. The text +// is the shooter's name (+ LiveMatchday_FormatError_ExecutableField3), the distance (LiveMatchday_FormatError_TextPointer12 / +// LiveMatchday_FormatError_TextPointer13 "m"); halved indoors (MatchEngine_Minute_ExecutableField4). +// SetPiece LiveSetPieceFrames(kind, distance) with MatchEngineRuntimeField6 = `side` (1 = the picture +// is mirrored): the ball's spot (a, b = x, y in the scene's 1000-wide +// coordinates), the kicker's run-up timer (c) and, for kind 3, the flight +// time of the ball (d). +// ShotOnGoal SetPieceAnimation(miss, follow_up) + Range4: `side` (0 left / 1 right +// lane of MatchEngineRuntimeField4), a = height of the shot, b = lane (x), c = the ball's +// end height, d = the goalkeeper's first reaction frame and its delay +// (d >> 8); `flag` bit 0 = follow-up picture, bit 1 = mirrored. +// PenaltyKick PenaltyShootout live: ". Elfmeter" (LiveMatchday_FormatError_TextPointer4 / LiveMatchday_FormatError_TextPointer5) + the +// taker's name at (0x49, 0x5f), the kick animated (SetPiece kind 2 and +// ShotOnGoal follow-up), then the score of the shoot-out (a : b); +// c = the round (1-5, then sudden death). +// ShootoutEnd PenaltyShootout live: the text LiveMatchday_FormatError_TextPointer6 at (0x49, 0x5f). + +#include +#include + +namespace bmh { + +enum class Show : uint8_t { Booking, Substitution, Chance, SetPiece, ShotOnGoal, PenaltyKick, ShootoutEnd }; + +struct ShowEvent { + Show what; + int16_t minute = 0; // PresentationRuntimeField2 (0x79 = 121 for the shoot-out) + uint8_t group = 0; // match group (descriptor index) and match within it + uint8_t match = 0; + uint8_t side = 0; // 0 home, 1 away (of the acting team; SetPiece: MatchEngineRuntimeField6) + uint8_t kind = 0; // Booking: 0 yellow, 1 red, 2 injury, 3 second yellow; Chance / + // SetPiece: the chance kind + uint8_t flag = 0; // Booking: shown in a box; Chance / PenaltyKick: goal; ShotOnGoal: see above + int16_t team = -1; + int16_t player = 0xFFF; // offender, shooter, taker, player leaving + int16_t other = 0xFFF; // assistant, player coming on + int32_t a = 0, b = 0, c = 0, d = 0; // per kind, see above + std::string text; // the composed text as the original builds it (ISO 646-DE) +}; + +} // namespace bmh diff --git a/src/game/random.hpp b/src/game/random.hpp new file mode 100644 index 0000000..f672eba --- /dev/null +++ b/src/game/random.hpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Both random generators of the original (docs/RNG.md). Must stay bit-exact. +// +// Both classes count their draws; the match engine tests compare these counts with +// recordings of the original, minute by minute. +#include + +namespace bmh { + +// Debugging aid: called before every draw of a generator (0 the game generator, 1 Watcom). +inline void (*draw_hook)(int generator) = nullptr; + +// Watcom C runtime rand()/srand(); random(lo, hi) = WatcomRandom. +// Seeded from the clock at program start, so its sequence is not reproducible from a +// savegame; recordings capture its state (RandomRuntimeField) directly. +class WatcomRandom { +public: + explicit WatcomRandom(uint32_t seed = 1) : seed_(seed) {} + void srand(uint32_t seed) { seed_ = seed; } + uint32_t seed() const { return seed_; } + uint64_t calls() const { return calls_; } + int rand() { + calls_++; + if (draw_hook) draw_hook(1); + seed_ = seed_ * 0x41C64E6Du + 0x3039u; + return int(seed_ >> 16 & 0x7FFF); + } + int range(int lo, int hi) { + int n = hi - lo + 1; + if (n < 1) return lo; + int32_t prod = int32_t(uint32_t(rand()) * uint32_t(n)); + // arithmetic shift with rounding toward zero, as compiled by Watcom + return (prod < 0 ? -((-prod) >> 15) : prod >> 15) + lo; + } + +private: + uint32_t seed_; + uint64_t calls_ = 0; +}; + +// Game's own deterministic generator, GameRandom; seed CareerSession_Save_RuntimeField lives in the savegame. +// All arithmetic is signed 32 bit with wrap-around (shl/imul/idiv in the original). +class GameRandom { +public: + explicit GameRandom(int32_t seed = 0) : seed_(seed) {} + int32_t seed() const { return seed_; } + void set_seed(int32_t seed) { seed_ = seed; } + uint64_t calls() const { return calls_; } + int32_t range(int32_t lo, int32_t hi) { + calls_++; + if (draw_hook) draw_hook(0); + seed_ = int32_t(uint32_t(seed_) * 16u + 0xA7u) % 4000000; + int32_t prod = int32_t(uint32_t(seed_) * uint32_t(hi - lo + 1)); + return prod / 4000000 + lo; + } + +private: + int32_t seed_; + uint64_t calls_ = 0; +}; + +} // namespace bmh diff --git a/src/game/rating.cpp b/src/game/rating.cpp new file mode 100644 index 0000000..9e554d0 --- /dev/null +++ b/src/game/rating.cpp @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/rating.hpp" + +#include +#include +#include + +#include "game/prediction.hpp" + +namespace bmh { + +int player_value(const GameState& g, int player, uint16_t attrs, int scale, int team, const RatingContext& ctx, int x, int y) { + if (player == 0xFFF) return 0; + const Player& p = g.players.at(player); + const uint32_t w1 = p.w35c, w3 = p.w364; + + int sum = 0, weight = 0, form_term = 0; + // local_1c / local_20, only set when selected (see RatingContext::stale_condition) + int condition = ctx.stale_condition >= 0 ? ctx.stale_condition : 0; + int technique = ctx.stale_technique >= 0 ? ctx.stale_technique : 0; + int skill[7] = {-1, -1, -1, -1, -1, -1, -1}; // selected skills * 5 (local_38, local_2c, ...) + for (int bit = 0; bit < 16; bit++) { + if (!((int16_t(attrs) >> bit) & 1)) continue; + if (bit < 2) { + weight += 100; + int v = bit == 0 ? int(w1 >> 14 & 0x7F) : int(w1 >> 7 & 0x7F); + (bit == 0 ? condition : technique) = v; + sum += v; + } else if (bit == 2) { + form_term += int(w1 & 0x7F) / 8 - 6; + } else if (bit == 3 || bit == 4) { + int pos = int(w3 & 3); + sum += bit == 3 ? 9 - 3 * pos : 3 * pos; + weight += 9; + } else if (bit == 12) { + int v = int(w3 >> 2 & 0x3F) * 3; + sum += v > 20 ? 20 : v; + weight += 20; + } + if (bit > 4 && bit < 12) { // the seven skills, bit 5 = skill 0 + int v = int(p.w368 >> (bit * 2 - 10) & 3) * 5; + skill[bit - 5] = v; + sum += v; + weight += 15; + } + } + + int multiplier = 100; + if (attrs & 3) { + int bonus = g.player_bonus.at(player) & 0x7F; + if (bonus != 0) multiplier = (bonus > 50 ? 50 : bonus) / 2 + 100; + multiplier = multiplier + form_term - (6 - ((g.team_morale.at(team) & 0x3F) >> 2)); + // Imbalance between condition and technique costs extra in certain match situations. + if (condition < technique && (ctx.chance_rain > 2 || int8_t(ctx.chance_temperature) < 0)) multiplier -= ctx.chance_rain * 3; + if (technique < condition && int8_t(ctx.chance_temperature) > 25) multiplier -= int8_t(ctx.chance_temperature) - 25; + } + // Human managers from game level 4 on: the place on the tactics board counts. Field + // players get skill bonuses for fitting places and lose for the distance between the + // place and their preferred depth/lane (w35c bits 21-22 and 24-25), and for age. + if (g.level > 3 && x != 0xFF && (w3 & 3) != 0 && g.manager_of(team) >= 0) { + static const int kDepthBias[4] = {0, 4, 10, 16}; // RatingRuntimeField + if (x < 31) { + // tackling near the own goal, teamplay + passing in midfield, speed on the wings + if (skill[4] != -1 && x != 0 && x < 4 && y > 2 && y < 6) + multiplier = (technique < condition ? multiplier - 5 : multiplier - 10) + skill[4]; + if (skill[0] != -1 && skill[3] != -1 && x > 9 && x < 13 && y > 2 && y < 6) + multiplier = (condition < technique ? multiplier - 10 : multiplier - 20) + skill[0] + skill[3]; + if (skill[1] != -1 && x > 11 && (y < 2 || y > 6)) multiplier = multiplier - 7 + skill[1]; + } else { + x = ((x - 30) * 10) / 14; // between the grid lines + } + if (y > 30) { + y = 4 - ((12 - (y - 30)) * 10) / 25; + y = y < 0 ? 0 : y > 8 ? 8 : y; + } + int depth = std::abs(int(w1 >> 21 & 3) + kDepthBias[w3 & 3] - 3 - x); + int lane = std::abs(int((w1 >> 24 & 3) << 3) / 7 - y); + multiplier -= (depth >> 1) + (lane >> 1); + int age = int(w3 >> 21 & 0x1F); // age - 16 + if (age > 14) multiplier -= age - 14; + if (age < 6) multiplier -= 6 - age; + } + + if (w1 >> 27) weight += weight / 20; // players with bits 27-31 set count 5 % less + if (weight == 0) return 0; + return scale * (sum * multiplier / 100) / weight; +} + +namespace { + +// The corrections of TeamRating for a player of a human manager (layout field-layout field), +// applied to his player_value `v`: +// - from game level 5 on (not for the goalkeeper group): minus the distance between the +// slot's own place (bytes 0/1) and the place he is put on, times the group weight / 100, +// plus 3 +// - +5 if G(20, 100) < expected bonus * 100 / base pay: a good bonus motivates +// - levels 8 and 9: minus level - 6 +// - slot byte 0x0f above 70: minus (value - 50) / 4 +// - with the live scene, half of slot byte 5 (10 = neutral): minus W(0, 10 - value) +// below 10, minus W(0, value) above 10 +int human_correction(GameState& g, RatingContext& ctx, int manager, int rank, int board_slot, int player, int group, + int weight, int x, int y, int board_depth, int board_live, int v) { + const size_t board = size_t(manager) * 0x840 + size_t(board_slot) * 0x58; + if (group != 0 && g.level > 4) { + v = int16_t(v - std::abs(g.tactics.at(board) - x) * weight / 100); + v = v - std::abs(g.tactics.at(board + 1) - y) * weight / 100 + 3; + } + if (!ctx.game || !ctx.rand) throw std::invalid_argument("team_rating: a human team needs both generators"); + const uint32_t base = uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16) | uint32_t(g.tactics.at(board + 0x53)) << 24; + if (base == 0) throw std::invalid_argument("team_rating: board slot without base pay (the original divides by zero)"); + const uint32_t motivation = expected_bonus(g, manager, rank, board_slot, player) * 100u / base; + if (uint32_t(ctx.game->range(0x14, 100)) < motivation) v += 5; + if (g.level > 7) v -= g.level - 6; + if (board_depth > 0x46) v = int16_t(v) - (board_depth - 0x32) / 4; + if (board_live < 10) v -= ctx.rand->range(0, 10 - board_live); + if (board_live > 10) v -= ctx.rand->range(0, board_live); + return v; +} + +} // namespace + +int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper) { + if (team >= 168 && team != kNoTeam) { + // Clubs without squad: per group a random value around the level of the club + // (ForeignClubStrength bits 5-7 -> RatingRuntimeField2), +2 if the group's strength bit is set + // (bit 3, 3, 2, 1 for goal, defence, midfield, attack: RatingRuntimeField3) and a style + // offset (RatingRuntimeField4: bit 0 clear = +6 defence -6 attack, set = the opposite). + static const uint8_t kLevel[8] = {55, 61, 65, 67, 70, 73, 76, 80}; + static const uint8_t kStrongBit[4] = {3, 3, 2, 1}; + static const int8_t kStyle[8] = {0, 6, 0, -6, 0, -6, 0, 6}; + if (!ctx.rand) throw std::invalid_argument("team_rating: a team without squad needs the Watcom generator"); + const uint8_t s = g.foreign_strength.at(size_t(team - 168)); + int16_t total = 0; + for (int i = 0; i < 4; i++) { + const int level = kLevel[s >> 5]; + const int strong = ((s >> kStrongBit[i]) & 1) * 2; + const int v = strong + ctx.rand->range(level, level + 3) - 1 + kStyle[(s & 1) * 4 + i]; + total = int16_t(total + profile.weight[i] * int16_t(v) / 100); + } + return total; + } + // Human managers: the predicted final rank (Void5 in mode 1 before the tenth + // round of the manager's league, mode 2 after it) for the expected bonus. Mode 1 may + // post the season goal messages. + const int manager = team == kNoTeam ? -1 : g.manager_of(team); // local_5a + int rank = 0; // local_5e + if (manager >= 0) { + const size_t rec = size_t(manager) * 0xB0C; + const int league = g.manager_records.at(rec + 0x210); + const int mode = (league < int(g.league_rounds.size()) && g.league_rounds[size_t(league)] > 9) + 1; + std::array buf; + int size_word = -1; + const int r = table_prediction(g, g.manager_teams.at(size_t(manager)), mode, buf, &size_word); + rank = r == 0 ? 0xB : r + 1; + // Void5 (3 arguments) is called from the same frame as the player values + // (PlayerValue, 6 arguments): its league size word (local_2c, [ESP+0xfc]) lands in + // the slot of their technique (local_20). Profiles without the technique attribute + // (4, 5) compare the condition against it (see RatingContext::stale_technique); it + // matters only when the chance weather's rain byte exceeds 2. + if (size_word >= 0 && !(profile.attrs & attr::TECHNIQUE)) ctx.stale_technique = size_word; + } + int board_depth = 0x32; // local_76: slot byte 0x0f of the board + int board_live = 10; // local_62: half of slot byte 5, only with the live scene + + static const int8_t kGroupDepth[4] = {1, 8, 13, 22}; // RatingRuntimeField5: group if x < value + static const int8_t kNominal[4] = {1, 4, 4, 2}; // RatingRuntimeField6: nominal 1-4-4-2 + + int16_t bucket[12] = {}; // local_84: 4 groups x 3 lanes + uint8_t count[12] = {}; // local_6c + uint8_t in_group[4] = {}; // RatingRuntimeField7 + int8_t missing = 11; // local_18: 11 - line-up size + if (keeper) *keeper = 0xFFF; + + SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + uint16_t slot = g.squad_slots.at(s); + int player = slot & 0x0FFF; + if (player == 0xFFF) break; // the original stops at the first empty slot + if (!(slot & kSlotInLineup)) continue; + g.players.at(player).w364 |= 0x1000; // mark as having played + missing--; + + int x = 0, y = 0; + const int board_slot = int(s - range.first); + g.formation_position(team, board_slot, x, y); + const size_t board = size_t(manager) * 0x840 + size_t(board_slot) * 0x58; + if (manager >= 0) { + board_depth = g.tactics.at(board + 0xf); + if (ctx.live_scene) board_live = g.tactics.at(board + 5) / 2; + } + for (int group = 0; group < 4; group++) { + if (x >= kGroupDepth[group]) continue; + in_group[group]++; + int lane = (group == 1 || group == 2) ? y / 3 : 0; + if (profile.weight[group] != 0) { + int v = player_value(g, player, profile.attrs, 100, team, ctx, x, y); + // the next call finds this player's condition/technique on the stack + if (profile.attrs & attr::CONDITION) ctx.stale_condition = g.players[player].condition(); + if (profile.attrs & attr::TECHNIQUE) ctx.stale_technique = g.players[player].technique(); + if (manager >= 0) v = human_correction(g, ctx, manager, rank, board_slot, player, group, profile.weight[group], x, y, board_depth, board_live, v); + int16_t value = int16_t(v); + if (value < 0) value = 0; + bucket[group * 3 + lane] = int16_t(bucket[group * 3 + lane] + value); + count[group * 3 + lane]++; + if (group == 0) { + if (y == 4) { + if (keeper) *keeper = player; + } else { + bucket[lane] = 0; // a goalkeeper off the centre does not count + } + if (g.players[player].position() != 0) bucket[lane] = int16_t(bucket[lane] / 6); // not a keeper + } + } + break; + } + } + if (missing < 0) missing = 0; // the original reports an internal error (0x6f) here + + if (profile.weight[0] != 0 && bucket[0] == 0) + for (int i = 0; i < 9; i++) bucket[i] = 0; // no goalkeeper: goal, defence and 2 mid buckets are void + + int total = 0; // local_34, used as a short + for (int group = 0; group < 4; group++) { + int8_t diff = int8_t(in_group[group] - kNominal[group]); + for (int lane = 0; lane < 3; lane++) { + int i = group * 3 + lane; + if (profile.weight[group] == 0 || count[i] == 0) continue; + if (diff != 0) bucket[i] = int16_t(bucket[i] * (diff * 10 + 100) / 100); + bucket[i] = int16_t(profile.weight[group] * bucket[i] / 100); + if (group == 1 || group == 2) count[i] = uint8_t(count[i] * 3); + total = int16_t(total) + bucket[i] / count[i]; + } + } + if (missing != 0) total = int16_t(total) * 100 / (missing * 10 + 100); + if (int16_t(total) > 110) total = 110; + return total; +} + +} // namespace bmh diff --git a/src/game/rating.hpp b/src/game/rating.hpp new file mode 100644 index 0000000..948a0a1 --- /dev/null +++ b/src/game/rating.hpp @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Player and team ratings used by the match engine. +// +// Ported from BMH.exe V2.24: +// player_value PlayerValue weighted value of one player for a set of attributes +// team_rating TeamRating rating of a line-up for one of six rating profiles +// +// For the teams of human managers the players are placed by the tactics board (block +// TacticsBoards) and their values are corrected by the board settings, the expected bonus +// (prediction.hpp) and random motivation draws. + +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// Attribute bits of player_value (the "param_2" of PlayerValue). Each selected +// attribute adds value/weight to a weighted mean: +namespace attr { +constexpr uint16_t CONDITION = 1 << 0; // KO, weight 100 +constexpr uint16_t TECHNIQUE = 1 << 1; // TE, weight 100 +constexpr uint16_t FORM = 1 << 2; // not averaged: (form / 8 - 6) percent on the multiplier +constexpr uint16_t DEFENSIVE = 1 << 3; // 9 - 3 * position (goalkeeper 9 .. forward 0), weight 9 +constexpr uint16_t OFFENSIVE = 1 << 4; // 3 * position, weight 9 +constexpr uint16_t TEAMPLAY = 1 << 5; // skill * 5, weight 15 (bits 5-11 = the 7 skills) +constexpr uint16_t SPEED = 1 << 6; +constexpr uint16_t SHOOTING = 1 << 7; +constexpr uint16_t PASSING = 1 << 8; +constexpr uint16_t TACKLING = 1 << 9; +constexpr uint16_t FREE_KICK = 1 << 10; +constexpr uint16_t CORNER = 1 << 11; +constexpr uint16_t EXPERIENCE = 1 << 12; // min(3 * (w364 bits 2-7), 20), weight 20 +} // namespace attr + +// Match context globals the original reads while rating (ChanceRain, ChanceTemperature). +// They are per-match values of the running match; outside a match they keep whatever the +// last match left behind. Zero is the value after program start. +struct RatingContext { + int chance_rain = 0; + int chance_temperature = 0; + // local_1c of PlayerValue is only written when the condition attribute (bit 0) is + // selected; otherwise it holds whatever the previous call at the same stack depth left + // there. For the free kick taker (attributes 0x0802) that is the condition of the last + // candidate of the shooter pick just before. -1 = unknown, 0 is used. + int stale_condition = -1; + // local_20, the same for the technique (bit 1). Rating profiles 4 and 5 of the side + // record select the condition but not the technique, so the condition/technique + // comparison uses the technique of the player rated last with profile 3. + // (Now and then the original finds a larger value there: nothing in the program writes + // the slot in between, so a hardware interrupt on the stack must have - not modelled.) + int stale_technique = -1; + // Watcom generator for clubs without squad, whose ratings are drawn (TeamRating). + WatcomRandom* rand = nullptr; + // Game generator, needed for the players of human managers (the bonus motivation). + GameRandom* game = nullptr; + // LiveSceneVisible: the live scene is shown; then the board's slot byte 5 counts. + bool live_scene = false; +}; + +// PlayerValue for computer teams: +// player player id (0xFFF gives 0) +// attrs attribute bits (namespace attr) +// scale result scale, normally 100 +// team team the player plays for (its morale counts) +// Result: scale * (sum * multiplier / 100) / weight, where multiplier = +// 100 + bonus/2 + form term - (6 - morale/4), with extra rules for KO/TE imbalance. +// x, y place on the tactics board (FormationPosition), 0xFF = none; only used for +// human managers from game level 4 on +int player_value(const GameState& g, int player, uint16_t attrs, int scale, int team, const RatingContext& ctx = {}, + int x = 0xFF, int y = 0); + +// The six rating profiles of the side record (table at layout field): weights for the +// goalkeeper, defence, midfield and attack groups plus the player_value attributes. +struct RatingProfile { + int16_t weight[4]; + uint16_t attrs; +}; +constexpr RatingProfile kRatingProfiles[6] = { + {{80, 10, 10, 0}, 0x0007}, // 0 goalkeeping: KO TE form + {{25, 55, 10, 10}, 0x0267}, // 1 defence: + teamplay speed tackling + {{20, 15, 45, 20}, 0x0367}, // 2 midfield: + passing + {{10, 10, 30, 50}, 0x0067}, // 3 attack: KO TE form teamplay speed + {{0, 33, 33, 34}, 0x0481}, // 4 KO shooting free kick + {{0, 33, 33, 34}, 0x0A01}, // 5 KO tackling corner +}; + +// TeamRating for computer teams. Walks the line-up (squad slots flagged in-line-up, +// stopping at the first empty slot), puts every player into a group by formation depth +// (x < 1 goalkeeper, < 8 defence, < 13 midfield, < 22 attack) and a lane (defence and +// midfield: left/centre/right = y / 3), sums player_value per bucket, corrects each group +// by 10 % per player above/below the nominal 1-4-4-2, weights and averages the buckets, +// scales down for fewer than 11 players and caps the result at 110. +// +// Side effects like the original: sets bit 12 of w364 for every line-up player and +// returns the goalkeeper's player id in *keeper (0xFFF if none) (RatingRuntimeField8). +// `ctx` carries the stale locals from call to call (see RatingContext) and is updated. +int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper = nullptr); +inline int team_rating(GameState& g, int team, const RatingProfile& profile) { + RatingContext ctx; + return team_rating(g, team, profile, ctx); +} + +} // namespace bmh diff --git a/src/game/reality_ball.cpp b/src/game/reality_ball.cpp new file mode 100644 index 0000000..1505606 --- /dev/null +++ b/src/game/reality_ball.cpp @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/reality_ball.hpp" +#include "game/reality_duel.hpp" + +#include +#include + +namespace bmh { +namespace { +int source_char(int v) { return int(int8_t(v)); } +int source_short(int v) { return int(int16_t(v)); } +int value(const GameState& state,const RealitySetup& scene,int figure,uint16_t attrs,int scale, + int team,int x,int y,const RatingContext& context) { + return player_value(state,scene.players.at(size_t(figure)).player,attrs,scale,team,context,x+30,y+30); +} +void validate(const GameState& state,const RealitySetup& scene,int actor) { + if (actor<0 || actor>=22 || scene.attacking_side<0 || scene.attacking_side>1 || + actor/11!=scene.attacking_side || !scene.motion.figures[size_t(actor)].active) + throw FormatError("Reality ball: invalid actor/side"); + for (int id=0;id<22;++id) if (scene.motion.figures[size_t(id)].active) { + const int player=scene.players[size_t(id)].player; + if (player<0 || size_t(player)>=state.players.size() || size_t(player)>=state.player_bonus.size()) + throw FormatError("Reality ball: missing player attributes/bonus"); + } + for (int team:scene.teams) if (team<0 || size_t(team)>=state.team_morale.size()) + throw FormatError("Reality ball: missing team morale"); +} +int blockers(const RealitySetup& scene,const RealityPath& path,int side,bool select,WatcomRandom& rand,RealityBallDecision& result) { + const auto line=reality_line_occupants(scene,path,side,select,rand); + result.line_selected[size_t(side)]=line.selected;return line.count; +} +} // namespace + +RealityBallDecision decide_reality_ball(const GameState& state,const RealitySetup& scene,int actor, + const RealityBallHistory& history,const RatingContext& rating,WatcomRandom& rand) { + validate(state,scene,actor);RealityBallDecision result;result.actor=actor;result.side=scene.attacking_side; + const int side=result.side,team=scene.teams[size_t(side)];const auto start=scene.grid.position(actor); + const auto ball=scene.grid.ball();const auto goal=reality_goal_path(ball.first,ball.second,side ? 0 : 42); + result.original_x=start.first;result.original_y=start.second; + const auto goal_target=goal.points[goal.count-1];const auto& tactics=scene.tactics[size_t(side)]; + result.previous_actor=actor!=history.current_actor ? history.current_actor : history.previous_actor; + result.target_x=ball.first;result.target_y=ball.second; + const int distance=42-std::abs(side*42-start.first);result.goal_distance=distance; + const int own_blocked=blockers(scene,goal,side,true,rand,result); + const int other_blocked=blockers(scene,goal,1-side,true,rand,result); + const int blocked=own_blocked+other_blocked; + result.goal_blockers=blocked; + result.opponent_nearby=uint8_t(reality_nearby(scene,start.first,start.second,1-side,3,true)); + result.teamplay=source_char(value(state,scene,actor,0x20,30,team,start.first,start.second,rating)); + result.shooting=source_char(value(state,scene,actor,0x80,30,team,start.first,start.second,rating)); + result.passing=source_char(value(state,scene,actor,0x100,15,team,start.first,start.second,rating)); + result.opponent_at_actor=scene.grid.occupant(start.first,start.second,1-side); + int best=source_short(-2*(distance/(tactics[2]+1))+60+rand.range(10,20)); + const auto& player=state.players[size_t(scene.players[size_t(actor)].player)]; + result.speed_ability=source_char(int((player.w35c>>14)&127)+int((player.w368>>3)&3)*10); + best+=25-int((player.w368>>4)&3)*3-blocked*10; + if (!result.opponent_nearby && rand.range(7,9)36 || actor%11==0) best=100; + if (result.opponent_at_actor) best-=5; + if (!distance && start.second!=12) best=0; + if (distance>int(tactics[2])*3+10) best=0; + result.airborne=uint8_t(rand.range(0,1)!=0); + if (result.shooting+32 || rand.range(0,int(result.airborne)+1)==0) && + (!result.opponent_at_actor || rand.range(0,3)==0)) { + result.blocked_attempt=true; + result.scatter_x=rand.range(0,4)-2;result.scatter_y=rand.range(0,4)-2; + } + if (source_short(best)>0) { + const auto target=goal.points[goal.count>20 ? 20 : goal.count-1]; + result.target_x=uint8_t(target.first+result.scatter_x);result.target_y=uint8_t(target.second+result.scatter_y); + } + if (result.opponent_at_actor && result.shooting+20distance) continue; + if (distance>12) score=source_short(score)+center/2; + if (distance<9) score-=center; + const int low=result.passing/2+3,high=result.passing/2+15; + const int separation=std::abs(distance-target_distance); + if (separation>rand.range(low,high) || std::abs(start.second-target.second)>rand.range(low,high)) continue; + const bool offside=reality_offside(scene,target.first); + if (offside && rand.range(0,3)!=0) continue; + const auto line=reality_path(start.first,start.second,target.first,target.second); + const int obstructions=blockers(scene,line,1-side,true,rand,result); + const int nearby=reality_nearby(scene,target.first,target.second,1-side,2,true); + score+=33-obstructions*2-nearby*15; + if (target_distance<8 && target_distance-3=source_short(score)) continue; + result.receiver=id;result.receiver_player=scene.players[size_t(id)].player; + const int loft_bias=source_char((3-int(tactics[4]))*2); + result.airborne=uint8_t(rand.range(separation>loft_bias+6,separation>loft_bias+3)); + const int accuracy_draw=rand.range(0,2); + if (((((result.airborne!=0 || accuracy_draw==0) && (result.airborne==0 || accuracy_draw!=0)) || !obstructions)) && + rand.range(0,40)6 && result.passing+rand.range(0,1)*8>5) { + for (int step=0;step<2;++step) { + result.receiver_nearby=reality_nearby(scene,target.first+step,target.second,1-side,2,true); + if (result.receiver_nearby<=nearby+1 && + (!step || (target_x+direction>=0 && target_x+direction<=42 && + !scene.grid.occupant(target_x+direction,target.second,1-side)))) { + target_x+=direction;result.leading_run=true;score+=10; + } + } + } + result.target_x=uint8_t(target_x+result.scatter_x);result.target_y=uint8_t(target.second+result.scatter_y);best=score; + } + int dribble; + if (result.opponent_nearby==1 && blocked<=1) dribble=35; + else dribble=40-int(result.opponent_nearby)*(result.opponent_nearby<2 ? 25 : 20); + dribble+=center+distance-blocked*5+22; + if (distance<6) dribble-=10; + if (result.opponent_at_actor) { + bool behind=false; + for (int id=side*11+1;id2) dribble-=rand.range(0,8)+15; + const int own=uint8_t(value(state,scene,actor,0x20e,100,team,start.first,start.second,rating)); + const int opponent=uint8_t(source_char(value(state,scene,result.opponent_at_actor-1,0x20e,100, + scene.teams[size_t(1-side)],start.first,start.second,rating))+scene.tactics[size_t(1-side)][6]*10); + result.actor_duel=uint8_t(own);result.opponent_duel=uint8_t(opponent); + dribble+=(own-opponent)/2; + } + if (actor%11==0 && (distance<34 || result.opponent_nearby)) dribble=0; + result.score=source_short(best);result.dribble_score=source_short(dribble); + if (result.dribble_score>result.score) result.boundary=RealityBallBoundary::dribble_or_duel; + return result; +} + +namespace { +RealityBallOutcome apply_ball_tail(const GameState& state,RealitySetup& scene,const RealityBallDecision& decision, + RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game, + const RealityDribbleDecision* dribble) { + if (!dribble && decision.boundary!=RealityBallBoundary::direct_move) + throw FormatError("Reality ball: dribble/duel continuation is not implemented"); + validate(state,scene,decision.actor); + if (decision.side!=scene.attacking_side || decision.action<0 || decision.action>(dribble ? 2 : 1)) + throw FormatError("Reality ball: invalid direct decision"); + const int actor=decision.actor,side=decision.side; + const auto start=dribble ? std::pair{decision.original_x,decision.original_y} : scene.grid.position(actor); + const auto old_ball=scene.grid.ball(); + auto target=std::pair{decision.target_x,decision.target_y};RealityBallOutcome outcome;outcome.action=decision.action; + auto actor_target=dribble ? std::pair{dribble->actor_target_x,dribble->actor_target_y} : start; + if (dribble) { + outcome.scene_status=dribble->scene_status;outcome.restart=dribble->restart; + outcome.event_stops_scene=dribble->event_stops_scene;outcome.lost_duel=dribble->lost_duel; + } + uint8_t airborne=decision.airborne; + if (history.airborne) { + const int control=source_short(value(state,scene,actor,6,100,scene.teams[size_t(side)],start.first,start.second,rating)); + if (controlsteps : 2),path.count-1)]; + if (outcome.action==2 && !outcome.lost_duel) target=point; + if (!scene.grid.place(actor,point.first,point.second,side) && !scene.grid.place(actor,start.first,start.second,side)) { + outcome.scene_status=3;outcome.needs_reporter=false;return outcome; // Source returns before reporter + } + const auto accepted=scene.grid.position(actor);scene.motion.figures[size_t(actor)].next_x=accepted.first; + scene.motion.figures[size_t(actor)].next_y=accepted.second; + history.previous_actor=outcome.action==1 ? actor : decision.previous_actor;history.current_actor=actor; + if (outcome.action==0) outcome.shot_ready=true; + if (target.first>42) { + outcome.scene_status=1;target.first=std::clamp(source_char(target.first),0,42); + target.second=game.range(0,1) ? 14 : 10; + if (decision.blocked_attempt) outcome.restart=3; + } + if (target.second>24) { outcome.scene_status=2;target.second=std::clamp(source_char(target.second),0,24); } + if (outcome.action==0 && decision.goal_distance<37) { + outcome.shooter_row=actor;outcome.assistant_row=history.previous_actor; + outcome.shooter=scene.players[size_t(actor)].player; + if (history.previous_actor>=0 && history.previous_actor<22 && history.previous_actor/11==side) + outcome.assistant=scene.players[size_t(history.previous_actor)].player; + } + if (decision.receiver_offside && rand.range(0,(referee&3)*2+2)!=0) outcome.scene_status=3; + if (!scene.grid.place(22,target.first,target.second,2)) throw FormatError("Reality ball: invalid Source final ball"); + auto& shadow=scene.motion.figures[22];shadow={true,old_ball.first,old_ball.second,target.first,target.second,shadow.phase}; + auto& ball=scene.motion.figures[23];ball.active=true;ball.old_x=old_ball.first;ball.old_y=old_ball.second; + ball.next_x=target.first;ball.next_y=target.second;scene.motion.ball_airborne=airborne!=0;history.airborne=airborne; + return outcome; // explicit InitializeRealityReporter / reporter-RNG boundary +} +} // namespace + +RealityBallOutcome apply_reality_ball(const GameState& state,RealitySetup& scene,const RealityBallDecision& decision, + RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game) { + return apply_ball_tail(state,scene,decision,history,rating,referee,rand,game,nullptr); +} + +RealityBallOutcome apply_reality_dribble(const GameState& state,RealitySetup& scene,const RealityDribbleDecision& decision, + RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game) { + if (decision.ball.boundary!=RealityBallBoundary::dribble_or_duel || decision.ball.action!=2 || + decision.steps<1 || decision.steps>2) + throw FormatError("Reality dribble: invalid prepared decision"); + return apply_ball_tail(state,scene,decision.ball,history,rating,referee,rand,game,&decision); +} + +} // namespace bmh diff --git a/src/game/reality_ball.hpp b/src/game/reality_ball.hpp new file mode 100644 index 0000000..0adab03 --- /dev/null +++ b/src/game/reality_ball.hpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/rating.hpp" +#include "game/reality_space.hpp" + +namespace bmh { + +struct RealityBallHistory { + int current_actor = 0xfff, previous_actor = 0xfff; // afb08/afb06 + uint8_t airborne = 0; // afb72 +}; +enum class RealityBallBoundary { direct_move, dribble_or_duel }; +struct RealityBallDecision { + RealityBallBoundary boundary = RealityBallBoundary::direct_move; + int actor = 0, side = 0, previous_actor = 0xfff; + int action = 0, score = 0, dribble_score = 0; // afb7a:0 shot,1 pass; source shorts + int goal_distance = 0, shooting = 0, passing = 0, teamplay = 0; + int original_x = 0, original_y = 0, goal_blockers = 0, speed_ability = 0; + uint8_t actor_duel = 0, opponent_duel = 0; + int receiver = -1, receiver_player = 0xfff, target_x = 0, target_y = 0; + uint8_t airborne = 0, opponent_at_actor = 0, opponent_nearby = 0; + std::array line_selected{}; // afaec, one-based occupancy IDs + int scatter_x = 0, scatter_y = 0, receiver_nearby = 0; + bool intercepted = false, inaccurate = false, blocked_attempt = false; + bool receiver_offside = false, leading_run = false; +}; +// ApplyRealityBall prefix through the shot/pass-vs-dribble decision. Caller must clear +// the actor's old occupancy, as DecideRealityBall does. Uses Source rating context/RNG; +// no fabricated foul/dribble outcome and no reporter text draws. +RealityBallDecision decide_reality_ball(const GameState&, const RealitySetup&, int actor, + const RealityBallHistory&, const RatingContext&, WatcomRandom&); +struct RealityBallOutcome { + int action = 0, scene_status = 0, restart = 0, shooter = 0xfff, assistant = 0xfff; + int shooter_row = 0xfff, assistant_row = 0xfff; + bool received = false, shot_ready = false, needs_reporter = true; + bool event_stops_scene = false, lost_duel = false; +}; +// ApplyRealityBall's common tail for a selected shot/pass. Source Game/Watcom calls +// for airborne reception, boundary handling and pass offside are preserved. +// A dribble/duel decision is rejected before any mutation or additional draws. +RealityBallOutcome apply_reality_ball(const GameState&, RealitySetup&, const RealityBallDecision&, + RealityBallHistory&, const RatingContext&, uint8_t referee, + WatcomRandom&, GameRandom&); + +} // namespace bmh diff --git a/src/game/reality_duel.cpp b/src/game/reality_duel.cpp new file mode 100644 index 0000000..c8f9ce9 --- /dev/null +++ b/src/game/reality_duel.cpp @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/reality_duel.hpp" + +#include +#include + +namespace bmh { +namespace { +int source_manager(const GameState& state,int team) { + const int m=state.manager_of(team);if (m>=0) return m; + if (!state.manager_teams.empty() && state.manager_teams[0]==kNoTeam && + state.manager_records.size()>=4*0xb0c+0x292 && le16(state.manager_records,4*0xb0c+0x290)==team) return 4; + return -1; +} +} + +RealityFoulResult reality_foul(const GameState& state,const RealitySetup& scene,int offender,bool defending, + int ball_actor,uint8_t referee,bool muted,WatcomRandom& rand,const RealityForcedEvent& forced_event, const RealitySound& sound) { + if (offender<0 || offender>=22 || ball_actor<0 || ball_actor>=22) + throw FormatError("Reality foul: invalid figure"); + const auto& placement=scene.players[size_t(offender)];const int slot=placement.squad_slot; + if (slot<0 || size_t(slot)>=state.squad_slots.size()) throw FormatError("Reality foul: missing Source squad slot"); + const int player=state.squad_slots[size_t(slot)]&0xfff; + if (player==0xfff || size_t(player)>=state.players.size()) throw FormatError("Reality foul: missing Source player"); + const int team=scene.teams[size_t(offender/11)],manager=source_manager(state,team); + const auto& p=state.players[size_t(player)]; + int chance=std::clamp((int((p.w35c>>14)&127)-int((p.w35c>>7)&127))*4+100,0,200); + // Literal RealityFoul indexes by player ID minus squad start, not roster row. + const int board_row=std::clamp(player-int(squad_range(team).first),0,24); + if (manager>=0) { + const size_t at=size_t(manager)*0x840+size_t(board_row)*0x58+5; + if (at>=state.tactics.size()) throw FormatError("Reality foul: Source board row outside supplied memory"); + chance=(int(state.tactics[at])+chance)*100/239; + } + RealityFoulResult result;if (rand.range(0,100)>=chance) return result; + result.cues.push_back({ball_actor,defending ? 19 : 18}); + result.whistle=rand.range(0,1)==0 && !muted; + if (result.whistle && sound) sound(21); // RealityFoul, before the forced event. + result.result=2; + if (rand.range(0,(referee&3)+1)==0) return result; + result.cues.push_back({-1,20}); // RealityFoul does not assign MatchEngine_Minute_ExecutableField2 for this cue. + if (!forced_event) throw FormatError("Reality foul: real forced card/injury engine callback required"); + result.event_result=forced_event(slot,offender>10); + result.event_kind=result.event_result&0x7f; + result.result=3; + if (result.event_result) { + result.cues.push_back({defending ? offender : ball_actor,21});result.event_stops_scene=true; + } + if (!defending) result.scene_status=4; + else { + const auto ball=scene.grid.ball();const int distance=42-std::abs(scene.attacking_side*42-ball.first); + result.restart=distance<7 && ball.second>3 && ball.second<21 ? 2 : 1; + } + return result; +} + +RealityDribbleDecision continue_reality_dribble(const GameState& state,RealitySetup& scene,const LeImage& exe,const RealityBallDecision& decision, + uint8_t referee,bool muted,WatcomRandom& rand,const RealityForcedEvent& forced_event, const RealitySound& sound) { + if (decision.boundary!=RealityBallBoundary::dribble_or_duel || decision.actor<0 || decision.actor>=22 || + decision.side!=scene.attacking_side) throw FormatError("Reality dribble: invalid continuation"); + RealityDribbleDecision result;result.ball=decision;result.ball.action=2;result.ball.airborne=0; + result.ball.receiver_offside=false; + if (decision.speed_ability +#include +#include "game/reality_ball.hpp" + +namespace bmh { +// EventImpl(absolute squad slot,1,figure>10). Must execute the real forced +// card/injury routine and return its byte. No default substitute is supplied. +using RealityForcedEvent = std::function; +using RealitySound = std::function; +struct RealityFoulCue { int actor = -1, code = 0; }; // -1: Source leaves that actor slot unchanged +struct RealityFoulResult { + uint8_t result = 0, event_result = 0; + uint8_t event_kind = 0; // MatchEngine_Minute_ExecutableField, return byte with bit7 stripped + int scene_status = 0, restart = 0; + bool whistle = false, event_stops_scene = false; + std::vector cues; +}; +// RealityFoul up to/through the caller-owned forced-event boundary. +RealityFoulResult reality_foul(const GameState&,const RealitySetup&,int offender,bool defending, + int ball_actor,uint8_t referee,bool muted,WatcomRandom&, + const RealityForcedEvent&, const RealitySound& sound = {}); +struct RealityDribbleDecision { + RealityBallDecision ball; + int actor_target_x = 0, actor_target_y = 0, steps = 2; + bool lost_duel = false; + int scene_status = 0, restart = 0; + bool event_stops_scene = false; + std::vector cues; + std::optional card_kind; // MatchEngine_Minute_ExecutableField changes only on a nonzero forced return +}; +// ApplyRealityBall dribble/duel continuation; never reruns the earlier selection draws. +RealityDribbleDecision continue_reality_dribble(const GameState&,RealitySetup&,const LeImage&,const RealityBallDecision&, + uint8_t referee,bool muted,WatcomRandom&, + const RealityForcedEvent& forced_event = {}, const RealitySound& sound = {}); +RealityBallOutcome apply_reality_dribble(const GameState&,RealitySetup&,const RealityDribbleDecision&, + RealityBallHistory&,const RatingContext&,uint8_t referee, + WatcomRandom&,GameRandom&); + +} // namespace bmh diff --git a/src/game/reality_match.cpp b/src/game/reality_match.cpp new file mode 100644 index 0000000..c58ccdc --- /dev/null +++ b/src/game/reality_match.cpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_match.hpp" + +#include +#include "game/lineup.hpp" + +namespace bmh { +namespace { +void validate_owner(const MatchEngine& engine,const RealityMatchScene& owner) { + if(owner.state_owner!=&engine.state||owner.rand_owner!=&engine.rand||owner.game_owner!=&engine.game|| + owner.date!=engine.state.date||owner.group>=engine.groups.size()||owner.match<0|| + owner.group_count!=engine.groups.size()||owner.fixture_owner!=&engine.groups[owner.group]) + throw FormatError("Reality match: stale engine/fixture owner"); + const auto& group=engine.groups[owner.group]; + if(owner.match>=group.matches()||group.fixtures.at(size_t(owner.match)*2)!=owner.teams[0]|| + group.fixtures.at(size_t(owner.match)*2+1)!=owner.teams[1]) + throw FormatError("Reality match: fixture changed during scene"); +} +} +void initialize_reality_match_scene(MatchEngine& engine,size_t group,int match,int side,int minute, + const LeImage& exe,RealitySceneContext context,RealityMatchScene& owner) { + if(group>=engine.groups.size()||match<0||match>=engine.groups[group].matches()||side<0||side>1||minute<1) + throw FormatError("Reality match: invalid Source fixture/minute"); + if(owner.state_owner&&(!owner.scene.finished||!owner.settled)) + throw FormatError("Reality match: previous scene/change has not completed"); + const auto& fixture=engine.groups[group]; + context.referee_index=fixture.desc.at(0x10+size_t(match)); + context.referee_profile=engine.referees.at(context.referee_index); + context.numbers=engine.button(::bmh::layout::RealityMatch_FormatError_ExecutableField)==0; + const std::array teams{fixture.fixtures[size_t(match)*2],fixture.fixtures[size_t(match)*2+1]}; + owner.pending.reset();owner.settled=owner.settling=false; + owner.group=group;owner.group_count=engine.groups.size();owner.fixture_owner=&fixture;owner.match=match;owner.minute=minute;owner.teams=teams; + owner.date=engine.state.date;owner.state_owner=&engine.state; + owner.rand_owner=&engine.rand;owner.game_owner=&engine.game; + initialize_reality_scene(engine.state,teams,side,reality_formations(engine.state,teams),exe, + context,engine.rand,engine.game,owner.scene); +} +RealitySceneTick advance_reality_match_scene(MatchEngine& engine,RealityMatchScene& owner,const LeImage& exe, + MinuteReport& report,bool user_exit) { + validate_owner(engine,owner); + if(owner.scene.finished||owner.settled||owner.settling||report.unsupported) + throw FormatError("Reality match: round outside active Source scene"); + // RealityReporterPanel resets bdb14 before each DecideRealityBall, not after scene completion. + owner.pending.reset(); + const auto forced=[&](int slot,int side) { + auto& group=engine.groups[owner.group]; + const int player=engine.state.squad_slots.at(size_t(slot))&0xfff; + const auto event=engine.forced_event(group,owner.match,side,owner.minute,slot,report); + if(report.unsupported)throw FormatError(report.reason); + if(event.change) { + const int kind=(event.code&0x7f)==4?2:(event.code&0x7f)==1?0:1; + const int team=owner.teams.at(size_t(side)),other=owner.teams.at(size_t(1-side)); + owner.pending=RealityDeferredRequest{*event.change, + LiveMatchEvent{owner.group,owner.match,side,team,other,player,kind,owner.minute, + event.change->human?event.change->mode:engine.state.manager_of(team)},slot}; + } + return event.code; + }; + return advance_reality_scene(engine.state,owner.scene,exe,engine.rand,engine.game,forced,user_exit); +} +bool settle_reality_match_scene(MatchEngine& engine,RealityMatchScene& owner,MinuteReport& report) { + validate_owner(engine,owner); + if(!owner.scene.finished||owner.settling) + throw FormatError("Reality match: change before scene end or reentrant completion"); + if(owner.settled||report.unsupported)return false; + if(!owner.pending){owner.settled=true;return false;} + const auto request=*owner.pending;const auto& event=request.event;const auto& change=request.source; + if(event.group_index!=owner.group||event.match_index!=owner.match||event.minute!=owner.minute|| + event.side<0||event.side>1||event.team!=owner.teams[size_t(event.side)]|| + event.opponent!=owner.teams[size_t(1-event.side)]) + throw FormatError("Reality match: deferred request belongs to another fixture"); + const auto range=squad_range(event.team); + if(request.offender_slot=int(range.first+range.count)|| + (engine.state.squad_slots.at(size_t(request.offender_slot))&0xfff)!=event.player) + throw FormatError("Reality match: deferred offender slot changed"); + if(change.human) { + if(change.team!=event.opponent||change.slot!=0xff||change.mode!=event.manager_slot|| + change.mode<0||engine.state.manager_of(event.team)!=change.mode|| + (event.kind!=1&&event.kind!=2)) + throw FormatError("Reality match: invalid Source human request"); + if(!engine.live_event&&!engine.leave_screens) { + report.fail("deferred Reality substitution screen of a human manager (PitchScreen)");return false; + } + } else if(change.team!=event.team||change.slot!=request.offender_slot|| + change.mode!=engine.state.players.at(size_t(event.player)).position()+20) { + throw FormatError("Reality match: invalid Source automatic request"); + } + owner.settling=true; + try { + if(change.human) { + if(engine.state.memory.has(::bmh::layout::ActiveManager))engine.state.memory.set8(::bmh::layout::ActiveManager,uint8_t(change.mode)); + if(engine.live_event)engine.live_event(event); + } else { + // Exact Injure(team,absoluteSlot,position+20). This tail does not + // call BuildSideRecords3 again: the actual card routine already did so. + (void)substitute(engine.state,change.team,change.slot,change.mode,engine.rand); + } + validate_owner(engine,owner); // callbacks retain stable fixture identity + } catch(...) {owner.settling=false;throw;} + owner.settling=false;owner.pending.reset();owner.settled=true;return true; +} +} // namespace bmh diff --git a/src/game/reality_match.hpp b/src/game/reality_match.hpp new file mode 100644 index 0000000..6b13189 --- /dev/null +++ b/src/game/reality_match.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/match_engine.hpp" +#include "game/reality_scene.hpp" + +namespace bmh { +struct RealityDeferredRequest { + DeferredRealityChange source; // literal bdb14/16/18 + LiveMatchEvent event; // actual fixed offender, fixture, manager and minute + int offender_slot = -1; +}; +// Owned bridge between one actual fixture and the independent Source scene. +// Requests survive scene end, but do not execute while its figures still move. +struct RealityMatchScene { + RealityScene scene; + size_t group = 0; + int match = -1, minute = 0; + std::array teams{}; + uint32_t date = 0; + const MatchGroup* fixture_owner = nullptr; + size_t group_count = 0; + const GameState* state_owner = nullptr; + const WatcomRandom* rand_owner = nullptr; + const GameRandom* game_owner = nullptr; + std::optional pending; + bool settled = false, settling = false; +}; +void initialize_reality_match_scene(MatchEngine&,size_t group,int match,int side,int minute, + const LeImage&,RealitySceneContext,RealityMatchScene&); +RealitySceneTick advance_reality_match_scene(MatchEngine&,RealityMatchScene&,const LeImage&, + MinuteReport&,bool user_exit = false); +// RealityReporterPanel tail. Returns true for an executed request (even a legal automatic +// no-change). Empty/repeated completion is drawless. Missing human presenter +// preserves the request and reports the existing unsupported boundary; only +// explicit leave_screens allows the legacy headless skip. +bool settle_reality_match_scene(MatchEngine&,RealityMatchScene&,MinuteReport&); +} // namespace bmh diff --git a/src/game/reality_motion.cpp b/src/game/reality_motion.cpp new file mode 100644 index 0000000..e3e9fed --- /dev/null +++ b/src/game/reality_motion.cpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_motion.hpp" + +#include +#include +#include + +namespace bmh { + +int reality_direction(int x, int y) { + if (x < -42 || x > 42 || y < -24 || y > 24) + throw FormatError("Reality: direction outside the Source grid"); + int ax = std::abs(x), ay = std::abs(y); + if (!(ay > 1 && ax > 1 && ax != ay)) { + if (ay < ax) ay *= 2; + else ax *= 2; + } + int direction = y == 0 ? 3 : std::abs(ax / ay); + if (direction > 2) direction = 3; + if (direction > 1) --direction; + if (y > 0 && direction == 0) direction = 4; + if (x < 0 && direction > 0 && direction != 4) direction += 4; + if (y > 0 && (direction == 1 || direction == 5)) direction += 2; + return direction; +} + +std::pair reality_project(const LeImage& exe, int x, int y) { + if (x < 0 || x > 42 || y < 0 || y > 24) + throw FormatError("Reality: position outside the Source grid"); + // Int7: signed division truncates towards zero, including the horizon. + const int distance = (int(int16_t(exe.u16(::bmh::layout::RealityMotion_FormatError_RuntimeField4Unsigned + uint32_t(y * 2)))) - 2) * std::abs(21 - x) / 21; + return {153 + (x > 21 ? distance : -distance), exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField5Unsigned + uint32_t(y))}; +} + +RealityMotionResult reality_motion(const RealityMotionInput& input, const LeImage& exe) { + RealityMotionResult result; + auto figures = input.figures; + // RealityFieldScreen copies the ground trajectory (22) to the elevated ball (23). + // Only its animation phase remains independent. + const auto ball_phase = figures[23].phase; + figures[23] = figures[22]; figures[23].phase = ball_phase; + std::array x{}, y{}, dx{}, dy{}, next_x{}, next_y{}, pose{}, phase{}, order{}; + std::iota(order.begin(), order.end(), 0); + for (int i = 0; i < 24; ++i) { + const auto& figure = figures[size_t(i)]; + // Source iterates all slots, but absent figures are not projected/drawn. + if (!figure.active) { result.phases_after[size_t(i)] = figure.phase; continue; } + const auto old = reality_project(exe, figure.old_x, figure.old_y); + const auto next = reality_project(exe, figure.next_x, figure.next_y); + x[size_t(i)] = old.first * 128; y[size_t(i)] = old.second * 128; + next_x[size_t(i)] = next.first; next_y[size_t(i)] = next.second; + dx[size_t(i)] = (next.first - old.first) * 128 / 10; + dy[size_t(i)] = (next.second - old.second) * 128 / 10; + pose[size_t(i)] = i < 22 ? exe.u8(::bmh::layout::RealityMotion_RealityMotion_RuntimeFieldUnsigned + uint32_t(reality_direction( + figure.next_x - figure.old_x, figure.next_y - figure.old_y) + (i > 10 ? 8 : 0))) : i - 14; + phase[size_t(i)] = figure.phase; + const int poses = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned + uint32_t(pose[size_t(i)])); + if (!poses || phase[size_t(i)] >= poses) + throw FormatError("Reality: animation phase outside the Source pose"); + } + for (int tick = 0; tick < 11; ++tick) { + // Source's insertion sort uses final depth; equal depths keep slot order. + for (int group = 0; group < 8; ++group) { + const int start = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeFieldUnsigned + uint32_t(group)); + const int end = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField2Unsigned + uint32_t(group)); + if (start > end || end > 24) throw FormatError("Reality: invalid Source depth-sort interval"); + for (int index = start; index < end; ++index) { + int at = index; + while (at > 0 && next_y[size_t(order[size_t(at)])] < next_y[size_t(order[size_t(at - 1)])]) { + std::swap(order[size_t(at)], order[size_t(at - 1)]); --at; + } + } + } + auto& frame = result.frames[size_t(tick)]; + for (int i : order) { + if (!figures[size_t(i)].active) continue; + const bool player = i < 22, away = i > 10; + int px = tick < 9 ? x[size_t(i)] / 128 : next_x[size_t(i)]; + int py = tick < 9 ? y[size_t(i)] / 128 : next_y[size_t(i)]; + int code = pose[size_t(i)], animation = phase[size_t(i)]; + if (player) px += away ? 1 : -1; + if (!dx[size_t(i)] && !dy[size_t(i)]) { + animation = 0; + if (player) code = away ? 11 : 10; + } else if (i == 23 && input.ball_airborne) py -= exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField3Unsigned + uint32_t(tick)); + const int count = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned + uint32_t(code)); + const int cell = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField6Unsigned + uint32_t(code)) + animation; + if (!count || cell < 0 || cell > 30) throw FormatError("Reality: invalid Source sprite cell"); + frame.sprites[frame.count++] = {i, px, py, cell, + input.numbers && player ? i % 11 + 1 : 0, player && away}; + if (tick < 9) phase[size_t(i)] = (animation + 1) % count; + x[size_t(i)] += dx[size_t(i)]; y[size_t(i)] += dy[size_t(i)]; + } + } + for (int i = 0; i < 24; ++i) if (figures[size_t(i)].active) + result.phases_after[size_t(i)] = uint8_t(phase[size_t(i)]); + return result; +} + +RealityPath reality_path(int x, int y, int target_x, int target_y) { + const auto valid = [](int xx, int yy) { return xx >= 0 && xx <= 42 && yy >= 0 && yy <= 24; }; + if (!valid(x,y) || !valid(target_x,target_y)) throw FormatError("Reality: invalid path endpoint"); + RealityPath path; + const int distance_x = std::abs(target_x-x), distance_y = std::abs(target_y-y); + const int length = std::max(distance_x,distance_y); + const int step_x = length ? distance_x*100/length : 0; + const int step_y = length ? distance_y*100/length : 0; + const int direction_x = target_x < x ? -1 : 1, direction_y = target_y < y ? -1 : 1; + int error_x = 0, error_y = 0; + while (x != target_x || y != target_y) { + path.points[path.count++] = {x,y}; + // Preserve Source's finite array guard and duplicate terminal write. + if (path.count > 49) break; + if (x != target_x && (error_x += step_x) >= 100-step_x) { error_x -= 100;x += direction_x; } + if (y != target_y && (error_y += step_y) >= 100-step_y) { error_y -= 100;y += direction_y; } + } + path.points[path.count++] = {x,y}; + return path; +} + +RealityPath reality_goal_path(int x, int y, int goal_x) { + return reality_path(x,y,goal_x,y < 8 ? 11 : y > 16 ? 13 : 12); +} + +bool RealityGrid::place(int figure, int x, int y, int side) { + if (figure < 0 || figure >= 24 || side < 0 || side > 2) + throw FormatError("Reality: invalid figure/occupancy side"); + if (x < 0 || x > 42 || y < 0 || y > 24) return false; + if (side < 2) { + auto& cell = occupied_[size_t(side)][size_t(x*26+y)]; + if (cell) return false; + cell = uint8_t(figure+1); + } else { + previous_ball_ = ball_; ball_ = {x,y}; + } + positions_[size_t(figure)] = {x,y}; + return true; +} + +uint8_t RealityGrid::occupant(int x, int y, int side) const { + if (x < 0 || x > 42 || y < 0 || y > 24 || side < 0 || side > 1) + throw FormatError("Reality: invalid occupancy lookup"); + return occupied_[size_t(side)][size_t(x*26+y)]; +} + +void RealityGrid::clear(int x, int y, int side) { + if (x < 0 || x > 42 || y < 0 || y > 24 || side < 0 || side > 1) + throw FormatError("Reality: invalid occupancy clear"); + occupied_[size_t(side)][size_t(x*26+y)] = 0; +} + +void RealityGrid::reset_occupancy() { + for (auto& side : occupied_) side.fill(0); +} + +void RealityGrid::stage_position(int figure, int x, int y) { + if (figure < 0 || figure >= 24 || x < 0 || x > 42 || y < 0 || y > 24) + throw FormatError("Reality: invalid staged position"); + positions_[size_t(figure)] = {x,y}; +} + +std::pair RealityGrid::position(int figure) const { + if (figure < 0 || figure >= 24) throw FormatError("Reality: invalid figure lookup"); + return positions_[size_t(figure)]; +} + +} // namespace bmh diff --git a/src/game/reality_motion.hpp b/src/game/reality_motion.hpp new file mode 100644 index 0000000..19f2eb3 --- /dev/null +++ b/src/game/reality_motion.hpp @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include + +#include "formats/le.hpp" + +namespace bmh { + +// RealityFieldScreen consumes positions chosen by the Reality simulation. This owned +// input is deliberately independent of GameState and both random generators. +struct RealityFigureMotion { + bool active = false; + int old_x = 0, old_y = 0, next_x = 0, next_y = 0; + uint8_t phase = 0; + bool operator==(const RealityFigureMotion&) const = default; +}; +struct RealityMotionInput { + std::array figures{}; // 22 players, shadow, ball + bool ball_airborne = false; + bool numbers = true; // Source RealityMatch_FormatError_ExecutableField == 0 + bool operator==(const RealityMotionInput&) const = default; +}; +struct RealityMotionSprite { + int figure = 0, x = 0, y = 0, cell = 0, number = 0; + bool away_palette = false; + bool operator==(const RealityMotionSprite&) const = default; +}; +struct RealityMotionFrame { + std::array sprites{}; + size_t count = 0; + bool operator==(const RealityMotionFrame&) const = default; +}; +struct RealityMotionResult { + std::array frames{}; + std::array phases_after{}; + bool operator==(const RealityMotionResult&) const = default; +}; + +// RealityDirection / Int7. Coordinates use the original 43 by 25 Reality grid. +int reality_direction(int x, int y); +std::pair reality_project(const LeImage&, int x, int y); +RealityMotionResult reality_motion(const RealityMotionInput&, const LeImage&); + +struct RealityPath { + std::array, 51> points{}; + size_t count = 0; + bool operator==(const RealityPath&) const = default; +}; +// RealityPath's integer line, including both endpoints. The goal helper uses the +// Source's three goal-mouth target rows (11, 12, 13). +RealityPath reality_path(int x, int y, int target_x, int target_y); +RealityPath reality_goal_path(int x, int y, int goal_x); + +// Place. Each side has its own occupancy plane: opponents may share a cell, +// teammates may not. Ball placement records the previous cell without occupying +// either player plane. This is runtime scene state, not a Native save extension. +class RealityGrid { +public: + bool place(int figure, int x, int y, int side); + void clear(int x, int y, int side); // caller clears old occupancy before a move + void reset_occupancy(); // Source initialization preserves old figure/ball data + bool operator==(const RealityGrid&) const = default; + void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed + uint8_t occupant(int x, int y, int side) const; + std::pair position(int figure) const; + std::pair ball() const { return ball_; } + std::pair previous_ball() const { return previous_ball_; } +private: + std::array, 2> occupied_{}; + std::array, 24> positions_{}; + std::pair ball_{}, previous_ball_{}; +}; + +// Source scene globals persist across matchdays, but are not Native FBM data. +struct RealityResidue { + bool initialized = false, deflected = false; + uint8_t card_kind = 0; + int distance = 0; + std::array cue_actors{}; + RealityGrid grid; + bool operator==(const RealityResidue&) const = default; +}; + +} // namespace bmh diff --git a/src/game/reality_movement.cpp b/src/game/reality_movement.cpp new file mode 100644 index 0000000..da89bfb --- /dev/null +++ b/src/game/reality_movement.cpp @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/reality_movement.hpp" + +#include +#include + +namespace bmh { +namespace { +int source_short(int value) { return int(int16_t(value)); } +void validate(const GameState& state,const RealitySetup& scene,int figure,const RealityMoveContext& context) { + if (scene.attacking_side<0 || scene.attacking_side>1 || figure<0 || figure>=22 || + !scene.motion.figures[size_t(figure)].active || context.goal_path.count<1 || + context.goal_path.count>context.goal_path.points.size()) + throw FormatError("Reality movement: invalid scene/player/path"); + const int player=scene.players[size_t(figure)].player; + if (player<0 || size_t(player)>=state.players.size()) + throw FormatError("Reality movement: missing Source player attributes"); +} +int speed(const GameState& state,const RealitySetup& scene,int figure,WatcomRandom& rand) { + const auto& player=state.players[size_t(scene.players[size_t(figure)].player)]; + const int ability=int((player.w35c>>14)&127)+int((player.w368>>3)&3)*10; + return ability space(RealitySetup& scene,const LeImage& exe,int figure,int side,uint8_t flags,uint8_t mode, + const RealityMoveContext& context) { + const auto target=reality_seek_space(scene,exe,figure,side,flags,mode,context.goal_path); + if (target.found) scene.grid.stage_position(figure,target.x,target.y); + return scene.grid.position(figure); +} +void finish_move(RealitySetup& scene,int figure,int side,std::pair start,std::pair target, + int padding,RealityMoveResult& result,GameRandom& game) { + const auto path=reality_path(start.first,start.second,target.first,target.second); + const auto candidate=path.points[std::min(size_t(result.steps),path.count-1)]; + // Source updates afb0c/afb23 BEFORE the movement-box/occupancy checks. + // A failed commit returns home from this candidate, not from the old cell. + scene.grid.stage_position(figure,candidate.first,candidate.second); + const auto& box=scene.players[size_t(figure)]; + const bool within=candidate.first>=box.min_x-padding && candidate.first<=box.max_x+padding && + candidate.second>=box.min_y-padding && candidate.second<=box.max_y+padding; + if ((result.score>=100 || within) && scene.grid.place(figure,candidate.first,candidate.second,side)) { + auto& motion=scene.motion.figures[size_t(figure)];motion.next_x=candidate.first;motion.next_y=candidate.second; + } else { + result.returned_to_box=true; + reality_return_to_box(scene,figure,side,uint8_t(result.steps),game); + } +} +} // namespace + +RealityMoveContext reality_move_context(const RealitySetup& scene,const LeImage& exe) { + if (scene.attacking_side<0 || scene.attacking_side>1) throw FormatError("Reality movement: invalid attacking side"); + const int side=scene.attacking_side;const auto [x,y]=scene.grid.ball();RealityMoveContext context; + context.goal_path=reality_goal_path(x,y,side ? 0 : 42); + context.attacking_nearby4=uint16_t(reality_nearby(scene,x,y,side,4,false)); + context.attacking_area=uint8_t(reality_penalty_area(scene,exe,side)); + context.attacking_nearby2=uint8_t(reality_nearby(scene,x,y,side,2,false)); + context.defending_nearby3=uint16_t(reality_nearby(scene,x,y,1-side,3,false)); + context.defending_nearby2_forward=uint8_t(reality_nearby(scene,x,y,1-side,2,true)); + return context; +} + +void reality_defensive_push(const RealitySetup& scene,RealityMoveContext& context,WatcomRandom& rand) { + if (scene.attacking_side<0 || scene.attacking_side>1) throw FormatError("Reality movement: invalid attacking side"); + const auto count=context.goal_path.count; + const bool pushed=count<20 && count>6 && rand.range(0,8-int(context.defensive_push))==0 && + scene.tactics[size_t(1-scene.attacking_side)][5]!=0; + context.defensive_push=pushed ? 10 : 0; +} + +RealityMoveResult reality_move_attacker(const GameState& state,RealitySetup& scene,const LeImage& exe,int figure, + RealityMoveContext& context,WatcomRandom& rand,GameRandom& game) { + validate(state,scene,figure,context);const int side=figure/11; + if (side!=scene.attacking_side) throw FormatError("Reality movement: attacker on defending side"); + const auto start=scene.grid.position(figure),ball=scene.grid.ball();RealityMoveResult result;std::pair target; + if (figure%11==0) { + target={side*40+1,12}; + if (std::abs(ball.first-start.first)<4 && std::abs(ball.second-start.second)<4) target=ball; + } else { + const int depth=42-std::abs(side*42-start.first); + const int distance=std::max(std::abs(ball.first-start.first),std::abs(ball.second-start.second)); + const bool offside=reality_offside(scene,start.first); + result.steps=speed(state,scene,figure,rand); + result.score=!scene.grid.occupant(ball.first,ball.second,side) && + (distance<3 || (distance<15 && !context.attacking_nearby2)) ? + 100 : source_short(9-int(context.attacking_nearby4)*9); + target=ball; + if (!offside) { + int next_score=depth-int(context.attacking_area)*10+50; + if (depth<6) next_score=0; + if (source_short(result.score)8 && p.second<16) ++advanced; + } + next_score=int(context.attacking_nearby4)*4+(scene.tactics[size_t(side)][1]+4)*advanced; + if (context.goal_path.count>8 && source_short(result.score)2 && std::abs(end.second-ball.second)>2) result.reporter_code=17; + return result; +} + +RealityMoveResult reality_move_defender(const GameState& state,RealitySetup& scene,const LeImage& exe,int figure, + RealityMoveContext& context,WatcomRandom& rand,GameRandom& game) { + validate(state,scene,figure,context);const int side=figure/11; + if (side==scene.attacking_side) throw FormatError("Reality movement: defender on attacking side"); + const auto start=scene.grid.position(figure),ball=scene.grid.ball();RealityMoveResult result; + if (context.blocked_figure && context.blocked_figure-1==figure) { + if (!scene.grid.place(figure,start.first,start.second,side)) throw FormatError("Reality movement: uncleared blocked figure"); + return result; + } + int distance=std::max(std::abs(ball.first-start.first),std::abs(ball.second-start.second)),padding=0; + std::pair target=ball; + if (figure%11==0) { + const auto nearby=reality_nearby(scene,ball.first,ball.second,side,3,true); + if (!(distance<3 || (distance17) || occupied || + (distance>2 && (context.defending_nearby2_forward || distance>3) && + (distance>8 || context.defending_nearby3))) + result.score=source_short(18-(9-int(pressure)*6)*int(context.defending_nearby3)); + else result.score=200; + if (result.score!=200) { + result.score=source_short(result.score+6-(2-int(pressure))*distance); + int next_score=depth+20; + if (depth40) && start.second>9 && start.second<15 ? + scene.players[size_t(figure)].player : 0xfff; + return result; +} + +} // namespace bmh diff --git a/src/game/reality_movement.hpp b/src/game/reality_movement.hpp new file mode 100644 index 0000000..381b6c5 --- /dev/null +++ b/src/game/reality_movement.hpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/reality_space.hpp" + +namespace bmh { + +// DecideRealityBall's per-iteration observations; no ball action is synthesized here. +struct RealityMoveContext { + RealityPath goal_path; + uint16_t attacking_nearby4 = 0, defending_nearby3 = 0; + uint8_t attacking_nearby2 = 0, attacking_area = 0, defending_nearby2_forward = 0; + uint8_t blocked_figure = 0, defensive_push = 0; // afb7c (one-based), afb87 + int keeper_player = 0xfff; // RatingRuntimeField8, retained across non-keeper moves +}; +RealityMoveContext reality_move_context(const RealitySetup&, const LeImage&); +// DecideRealityBall's first-defender branch, including its short-circuit draw order. +void reality_defensive_push(const RealitySetup&, RealityMoveContext&, WatcomRandom&); +struct RealityMoveResult { + int steps = 2, score = -100; + bool returned_to_box = false; + int reporter_code = 0; // InitializeRealityReporter code17 boundary; reporter RNG is NOT consumed here +}; +// RealityMoveAttacker and RealityMoveAttacker2. Caller clears old occupancy as DecideRealityBall does. +// Positions/occupancy/next rendering coordinates and real movement RNG change. +// GameState is read-only. These are not yet called from MatchEngine/Main. +RealityMoveResult reality_move_attacker(const GameState&, RealitySetup&, const LeImage&, int figure, + RealityMoveContext&, WatcomRandom&, GameRandom&); +RealityMoveResult reality_move_defender(const GameState&, RealitySetup&, const LeImage&, int figure, + RealityMoveContext&, WatcomRandom&, GameRandom&); + +} // namespace bmh diff --git a/src/game/reality_reporter.cpp b/src/game/reality_reporter.cpp new file mode 100644 index 0000000..11373fc --- /dev/null +++ b/src/game/reality_reporter.cpp @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_reporter.hpp" + +#include +#include +#include "game/messages.hpp" + +namespace bmh { +namespace { +struct Node { + char token = 0; + int selector = 0, variants = 0; + std::string literal; + std::vector> branches; +}; +// Parse before evaluation: structural traversal cannot draw random numbers. +// The Source cursor skips entire unselected nested %x...#x expressions. +std::vector parse(std::string_view text,size_t& at,int depth) { + if(depth>32)throw FormatError("Reality reporter: template nesting too deep"); + std::vector nodes; + while(at=text.size())throw FormatError("Reality reporter: truncated token"); + n.token=text[at++]; + if(n.token=='x') { + if(at+2>text.size()||text[at]<'0'||text[at]>'9'||text[at+1]<'0'||text[at+1]>'9') + throw FormatError("Reality reporter: invalid selector digits"); + n.selector=text[at]-'0';n.variants=text[at+1]-'0';at+=2; + for(;;) { + n.branches.push_back(parse(text,at,depth+1)); + if(at>=text.size()||text[at++]!='#')throw FormatError("Reality reporter: missing branch terminator"); + if(at=pool.size())throw FormatError("Reality reporter: missing referee name"); + std::string out;for(;offset22)throw FormatError("Reality reporter: missing selected figure"); + return scene.players[size_t(one_based-1)].player; +} +std::string evaluate(const std::vector& nodes,const GameState& game,const RealitySetup& scene, + const LeImage& exe,const RealityReporterFrame& frame,const RealityReporterState& state,WatcomRandom& rand) { + std::string out; + for(const auto& node:nodes) { + if(!node.token)out+=node.literal; + else if(node.token=='x') { + const int index=node.selector+10*node.variants; + if(node.selector && index>=int(state.selectors.size()))throw FormatError("Reality reporter: selector outside Source context"); + const int choice=node.selector?state.selectors[size_t(index)]:rand.range(1,node.variants); + const size_t branch=size_t(choice<2?0:choice-1); + // Source walks to #x without output when the selector exceeds the branches. + if(branch20)value=uint8_t((value/5)*5); + out+=format_number(game,value,1); + } + // All other Source percent tokens are consumed without output. + if(out.size()>=500)throw FormatError("Reality reporter: expanded text exceeds Source buffer"); + } + return out; +} +} // namespace + +RealityReporterState initialize_reality_reporter(const LeImage& exe) { + RealityReporterState state; + for(size_t i=0;i1) + throw FormatError("Reality reporter: template needs its actual Source player side"); + size_t at=0;const auto nodes=parse(text,at,0); + return evaluate(nodes,game,scene,exe,frame,state,rand); +} +RealityReporterResult report_reality(const GameState& game,const RealitySetup& scene,const LeImage& exe, + RealityReporterFrame& frame,RealityReporterState& state,int figure,int side,uint8_t code,WatcomRandom& rand) { + RealityReporterResult out; + if(figure==100){state.last_side=state.last_owner=state.last_player=state.last_action=-1;return out;} + if(figure<0||figure>=22||side<0||side>1||frame.player_side>1||code>21) + throw FormatError("Reality reporter: invalid figure/side/cue"); + state.current_player=scene.players[size_t(figure)].player; + state.selectors[12]=frame.card_kind; + auto cue=[&](int value){out.codes.push_back(uint8_t(value));}; + if(code)cue(code); + else { + const int area=reality_penalty_area(scene,exe,1-side,scene.grid.ball().first,scene.grid.ball().second); + const auto ball=scene.grid.ball(),old=scene.grid.previous_ball(); + // InitializeRealityReporter uses signed chars for both differences; preserve byte wrapping. + const int dx=int8_t(std::abs(ball.first-old.first)),dy=int8_t(std::abs(ball.second-old.second)); + if(dy<=dx&&!frame.incoming_bh)throw FormatError("Reality reporter: missing Source incoming BH"); + const int high=dy>dx?dy:int(int8_t(*frame.incoming_bh)); + // BL stays dx even when dy is smaller (verified at 69210..6926d). + const int low=dx; + state.selectors[2]=uint8_t(2-frame.airborne); + state.selectors[3]=uint8_t((high>2)+1+(high>9)*2); + state.selectors[4]=uint8_t(3-2*(low>=10&&dy<=4)+(dy>16)); + state.selectors[5]=uint8_t(2-area); + state.selectors[6]=uint8_t(side==state.last_side?2-(frame.distance_before6)+1); + state.selectors[8]=uint8_t((ball.first>42)+1+(ball.second<11||ball.second>13)); + state.selectors[9]=frame.scene_status; + state.selectors[11]=uint8_t(2-int(frame.received)); + if(low>7&&state.selectors[4]==3)state.selectors[4]=2; + if(frame.action==2&&frame.opponent)frame.action=uint8_t(frame.lost_duel?9:10); + if(frame.action==0&&frame.received&&frame.distance_before<6&&rand.range(0,1)!=0)frame.action=16; + if(!(frame.action!=0&&frame.action==state.last_action&&state.current_player==state.last_player)) { + if(state.last_owner!=-1&&state.current_player!=state.last_owner){cue(7);state.selectors[1]=2;state.last_player=state.current_player;} + state.selectors[1]=uint8_t(state.current_player==state.last_player&&state.selectors[1]!=1?1:2); + if(frame.action==0&&frame.distance_before>34)frame.action=8; + cue(frame.action);state.last_owner=state.current_player; + if(frame.action==0&&frame.intercepted)cue(13); + if(frame.action==1) { + state.last_owner=frame.receiver_player; + if(frame.blocked_attempt) { + if(!frame.inaccurate&&frame.line_selected[size_t(1-frame.player_side)])cue(6); + else if(frame.inaccurate&&rand.range(0,2)==0)cue(4); + } + if(!frame.inaccurate&&!frame.line_selected[size_t(1-frame.player_side)]&&frame.offside&&int(frame.distance_after)=22)throw FormatError("Reality reporter: missing pass target figure"); + const auto target=scene.grid.position(frame.receiver); + const int enemy=scene.grid.occupant(target.first,target.second,1-side); + if(enemy){frame.opponent=uint8_t(enemy);cue(14);} + } + } + if(frame.scene_status)cue((frame.scene_status==3)+11); + } + } + if(code&&state.last_action==9){out.suppressed=true;return out;} + // %a/%b are fixed home/away afaf2/afaf4, independent of possession side. + for(uint8_t id:out.codes)out.text.push_back(reality_reporter_text(game,scene,exe,frame,state,exe.string_at_pointer(::bmh::layout::RealityReporter_FormatError_TextPointer+uint32_t(id)*4),rand)); + state.last_action=frame.action;state.last_player=state.current_player; + if(frame.action==9){state.last_owner=player(scene,frame.opponent);state.last_player=state.last_owner;} + state.last_side=side; + return out; +} +} // namespace bmh diff --git a/src/game/reality_reporter.hpp b/src/game/reality_reporter.hpp new file mode 100644 index 0000000..2730115 --- /dev/null +++ b/src/game/reality_reporter.hpp @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include "game/reality_space.hpp" + +namespace bmh { +// Runtime locals/globals of InitializeRealityReporter. The scene owner supplies their actual +// values; this module neither advances the ball nor constructs a match result. +struct RealityReporterFrame { + uint8_t action = 3, opponent = 0, airborne = 0, scene_status = 0; + uint8_t distance_before = 0, distance_after = 0, referee = 0, player_side = 0; + bool lost_duel = false, received = false, inaccurate = false; + bool blocked_attempt = false, intercepted = false, offside = false, leading_run = false; + int receiver = -1, receiver_player = 0xfff; + std::array line_selected{}; + uint8_t card_kind = 0; + // InitializeRealityReporter leaves BH unchanged when dx>=dy. This is the caller's + // incoming register byte, not max(dx,dy); absence is an explicit boundary. + std::optional incoming_bh; +}; +struct RealityReporterState { + int last_side = -1, last_owner = -1, last_player = -1, last_action = -1; + int current_player = -1; // afaee, assigned even if the explicit cue is suppressed + std::array selectors{}; // RealityReporter_InitializeRealityReporter_RuntimeField..MatchEngine_Minute_ExecutableField; reset keeps these unchanged +}; +struct RealityReporterResult { + std::vector codes; + std::vector text; // Original single-byte text, ready for later layout + bool suppressed = false; +}; +RealityReporterState initialize_reality_reporter(const LeImage&); +// RealityReporterText2/RealityReporterText: nested Original %xDD alternatives and entity tokens. +// Only chosen branches consume Watcom draws. No Game draw or Native write. +std::string reality_reporter_text(const GameState&,const RealitySetup&,const LeImage&, + const RealityReporterFrame&,const RealityReporterState&,std::string_view,WatcomRandom&); +// InitializeRealityReporter; figure100 resets the four history words only. code0 derives the +// normal cue sequence; codes1..21 request an explicit Source cue. May update +// action/opponent in the owned frame. Rendering must use the returned text. +RealityReporterResult report_reality(const GameState&,const RealitySetup&,const LeImage&, + RealityReporterFrame&,RealityReporterState&,int figure,int side,uint8_t code,WatcomRandom&); +} // namespace bmh diff --git a/src/game/reality_scene.cpp b/src/game/reality_scene.cpp new file mode 100644 index 0000000..c7e5dac --- /dev/null +++ b/src/game/reality_scene.cpp @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_scene.hpp" + +#include +#include +#include "game/messages.hpp" + +namespace bmh { +namespace { +bool goal_mouth(const RealityScene& scene,const LeImage& exe) { + const auto [x,y]=scene.setup.grid.ball(); + return x==exe.u8(::bmh::layout::RealityScene_GoalMouth_RuntimeFieldUnsigned+uint32_t(scene.setup.attacking_side))&&y>=11&&y<=13; +} +void finish(RealityScene& scene,RealitySceneStop stop) { + scene.finished=true; + auto& out=scene.result;out.stop=stop;out.side=scene.setup.attacking_side; + out.return_flags=scene.return_flags; + if(stop!=RealitySceneStop::possession_ended&&!out.scene_status&&out.shooter_row!=0xfff) + out.return_flags|=1; + // RealityReporterPanel converts only a same-side assist; missing/cross-side stays fff. + if(out.shooter_row==0xfff||out.assistant_row==0xfff||out.shooter_row/11!=out.assistant_row/11) + out.assistant=out.assistant_row=0xfff; + else { + out.assistant=scene.setup.players.at(size_t(out.assistant_row)).player; + out.assistant_row%=11; + } + if(out.shooter_row!=0xfff) { + out.shooter=scene.setup.players.at(size_t(out.shooter_row)).player; + out.shooter_row%=11; + } +} +void prepare_report(RealityScene& scene,const RealityBallDecision& decision,const RealityBallOutcome& outcome) { + auto& frame=scene.reporter_frame; + frame.action=uint8_t(outcome.action);frame.opponent=decision.opponent_at_actor; + frame.airborne=scene.ball_history.airborne;frame.scene_status=uint8_t(outcome.scene_status); + frame.distance_before=uint8_t(decision.goal_distance); + frame.distance_after=uint8_t(42-std::abs(decision.side*42-scene.setup.grid.ball().first)); + frame.player_side=uint8_t(decision.side);frame.lost_duel=outcome.lost_duel; + frame.received=outcome.received;frame.inaccurate=decision.inaccurate; + frame.blocked_attempt=decision.blocked_attempt;frame.intercepted=decision.intercepted; + frame.offside=decision.receiver_offside;frame.leading_run=decision.leading_run; + frame.receiver=decision.receiver;frame.receiver_player=decision.receiver_player;frame.line_selected=decision.line_selected; + // Verified 63e96: MOVZX EBX,byte(side), preserved by45bb5 and64d4d. + // Thus the normal ApplyRealityBall -> InitializeRealityReporter call enters with BH=0. + frame.incoming_bh=0; +} +} + +void initialize_reality_scene(GameState& state,const std::array& teams,int side, + const RealityFormations& positions,const LeImage& exe,const RealitySceneContext& context, + WatcomRandom& rand,GameRandom& game,RealityScene& scene) { + for(auto actor:context.retained_cue_actors) + if(actor>=22)throw FormatError("Reality scene: retained Source cue actor outside figures"); + auto retained_setup=std::move(scene.setup); + scene={};scene.setup=std::move(retained_setup);scene.context=context; + initialize_reality(state,teams,side,positions,exe,rand,game,scene.setup); + scene.setup.motion.numbers=context.numbers;scene.setup.motion.ball_airborne=false; + scene.reporter=initialize_reality_reporter(exe); + scene.reporter_frame.referee=context.referee_index;scene.reporter_frame.card_kind=context.retained_card_kind; + scene.result.side=side;scene.result.deflected=context.retained_deflection; + scene.result.distance=context.retained_distance; + if(!scene.setup.ready){scene.result.scene_status=3;finish(scene,RealitySceneStop::unavailable);} +} + +void exit_reality_scene_after_animation(RealityScene& scene) { + if (scene.finished || !scene.rounds) throw FormatError("Reality scene: exit outside post-animation boundary"); + finish(scene,RealitySceneStop::user_exit); +} + +RealitySceneTick advance_reality_scene(GameState& state,RealityScene& scene,const LeImage& exe, + WatcomRandom& rand,GameRandom& game,const RealityForcedEvent& forced_event,bool user_exit) { + if(scene.finished||!scene.setup.ready)throw FormatError("Reality scene: round requested after scene end"); + RealitySceneTick tick;tick.round=scene.rounds;tick.side=scene.setup.attacking_side; + const auto done=[&](){tick.result=scene.result;tick.finished=scene.finished;return tick;}; + if(goal_mouth(scene,exe)){finish(scene,RealitySceneStop::goal_mouth);return done();} + if(scene.result.restart){finish(scene,RealitySceneStop::boundary);return done();} + const int previous_side=scene.setup.attacking_side; + const auto [bx,by]=scene.setup.grid.ball(); + for(int side=0;side<2;++side) + if(scene.setup.grid.occupant(bx,by,side)&&!scene.setup.grid.occupant(bx,by,1-side)) + scene.setup.attacking_side=side; + const int side=scene.setup.attacking_side;tick.side=side; + if(scene.stagnation>3||previous_side!=side) { + if(scene.stagnation<4&&rand.range(0,1)) { + scene.return_flags^=0x80; + const int shift=int8_t(exe.u8(::bmh::layout::RealityScene_AdvanceRealityScene_RuntimeFieldUnsigned+uint32_t(side))); + for(auto& player:scene.setup.players) { + player.min_x=int16_t(player.min_x+shift);player.max_x=int16_t(player.max_x+shift); + } + scene.shot=false;scene.result.shot_attempted=false; + } else { + RealityReporterResult ended; + ended.text={message_text(state,::bmh::layout::RealityScene_AdvanceRealityScene_TextPointer)};tick.reports.push_back(std::move(ended)); + finish(scene,RealitySceneStop::possession_ended);return done(); + } + } + scene.reporter_frame.action=3;scene.reporter_frame.player_side=uint8_t(side); + uint8_t blocked=0; + int actor=-1; + if(!scene.first_round) { + // Source scans coordinate arrays0..21, not occupancy lookup/figure order. + for(int id=side*11;id=0) { + tick.ball_actor=actor; + const auto start=scene.setup.grid.position(actor);scene.setup.grid.clear(start.first,start.second,side); + const auto decision=decide_reality_ball(state,scene.setup,actor,scene.ball_history,scene.context.rating,rand); + std::vector cues;RealityBallOutcome outcome;auto effective=decision; + if(decision.boundary==RealityBallBoundary::dribble_or_duel) { + const auto dribble=continue_reality_dribble(state,scene.setup,exe,decision,scene.context.referee_profile, + scene.context.muted,rand,forced_event,scene.context.sound); + blocked=decision.opponent_at_actor;cues=dribble.cues;effective=dribble.ball; + if(dribble.card_kind)scene.context.retained_card_kind=scene.reporter_frame.card_kind=*dribble.card_kind; + outcome=apply_reality_dribble(state,scene.setup,dribble,scene.ball_history,scene.context.rating, + scene.context.referee_profile,rand,game); + } else outcome=apply_reality_ball(state,scene.setup,decision,scene.ball_history,scene.context.rating, + scene.context.referee_profile,rand,game); + scene.result.scene_status=uint8_t(outcome.scene_status);scene.result.restart=uint8_t(outcome.restart); + scene.result.shooter_row=outcome.shooter_row;scene.result.assistant_row=outcome.assistant_row; + scene.result.distance=decision.goal_distance;scene.result.deflected=decision.blocked_attempt; + scene.result.shot_attempted=scene.result.shot_attempted||outcome.shot_ready;scene.shot=outcome.shot_ready;scene.event_stop=outcome.event_stops_scene; + prepare_report(scene,effective,outcome); + if(outcome.needs_reporter) { + if(cues.empty())tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame, + scene.reporter,actor,side,0,rand)); + else { + if(cues.size()>scene.context.retained_cue_actors.size())throw FormatError("Reality scene: too many Source foul cues"); + for(size_t i=0;i=0)scene.context.retained_cue_actors[i]=uint8_t(cues[i].actor); + tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame,scene.reporter, + scene.context.retained_cue_actors[i],side,uint8_t(cues[i].code),rand)); + } + } + } + scene.stagnation=0; + } + } + if(actor<0)++scene.stagnation; + if(!scene.result.scene_status&&!goal_mouth(scene,exe)) { + auto context=reality_move_context(scene.setup,exe); + context.defensive_push=scene.defensive_push;context.blocked_figure=blocked;context.keeper_player=scene.result.keeper; + bool first_defender=true; + for(int id=side?21:0;id!=(side?-1:22);id+=side?-1:1) { + if(!scene.setup.motion.figures[size_t(id)].active)continue; + const int figure_side=id/11; + if(figure_side==side) { + if(scene.first_round||id==actor)continue; + const auto start=scene.setup.grid.position(id);scene.setup.grid.clear(start.first,start.second,figure_side); + const auto movement=reality_move_attacker(state,scene.setup,exe,id,context,rand,game); + tick.moved_figures.push_back(id); + if(movement.reporter_code)tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame, + scene.reporter,id,figure_side,uint8_t(movement.reporter_code),rand)); + } else { + if(first_defender){reality_defensive_push(scene.setup,context,rand);first_defender=false;} + const auto start=scene.setup.grid.position(id);scene.setup.grid.clear(start.first,start.second,figure_side); + reality_move_defender(state,scene.setup,exe,id,context,rand,game);tick.moved_figures.push_back(id); + } + } + scene.defensive_push=context.defensive_push;scene.result.keeper=context.keeper_player; + } + scene.first_round=false;++scene.rounds; + if(!scene.event_stop) { + if (scene.return_flags < 2 && scene.context.sound) scene.context.sound(16); // RealityFieldScreen. + tick.motion=reality_motion(scene.setup.motion,exe); + const auto ball_phase=scene.setup.motion.figures[23].phase; + scene.setup.motion.figures[23]=scene.setup.motion.figures[22];scene.setup.motion.figures[23].phase=ball_phase; + for(size_t i=0;i<24;++i) { + auto& figure=scene.setup.motion.figures[i];figure.phase=tick.motion->phases_after[i]; + if(i<23){figure.old_x=figure.next_x;figure.old_y=figure.next_y;} + } + } + if(scene.event_stop)finish(scene,RealitySceneStop::forced_event); + else if(user_exit)finish(scene,RealitySceneStop::user_exit); + else if(scene.shot)finish(scene,RealitySceneStop::shot); + else if(scene.result.scene_status||scene.result.restart)finish(scene,RealitySceneStop::boundary); + return done(); +} +} // namespace bmh diff --git a/src/game/reality_scene.hpp b/src/game/reality_scene.hpp new file mode 100644 index 0000000..77ad669 --- /dev/null +++ b/src/game/reality_scene.hpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/reality_duel.hpp" +#include "game/reality_movement.hpp" +#include "game/reality_reporter.hpp" + +namespace bmh { +// Caller-owned persistent Source context. MatchEngine_Minute_ExecutableField2 is not cleared by ApplyRealityBall: +// code20 leaves its actor slot unchanged. Supply the retained five slots; +// carrying these between scenes is the eventual MatchEngine owner's job. +struct RealitySceneContext { + RatingContext rating; + uint8_t referee_index = 0, referee_profile = 0; // afb73 vs RefereeProperties[index] + bool muted = true, numbers = true; + std::array retained_cue_actors{}; + uint8_t retained_card_kind = 0; + bool retained_deflection = false; // MatchEngine_Minute_ExecutableField3 survives until the next ball actor + int retained_distance = 0; // MatchEngine_Minute_ExecutableField4 is also assigned only by a ball actor + RealitySound sound; // presentation observer, never serialized +}; +enum class RealitySceneStop { none, unavailable, goal_mouth, possession_ended, shot, boundary, forced_event, user_exit }; +struct RealitySceneResult { + RealitySceneStop stop = RealitySceneStop::none; + uint8_t return_flags = 0, scene_status = 0, restart = 0; + int side = 0, shooter = 0xfff, assistant = 0xfff; + int shooter_row = 0xfff, assistant_row = 0xfff, distance = 0, keeper = 0xfff; + bool deflected = false, shot_attempted = false; // MatchEngine_Minute_ExecutableField3 and bdb7b +}; +struct RealityScene { + RealitySetup setup; + RealitySceneContext context; + RealityBallHistory ball_history; + RealityReporterState reporter; + RealityReporterFrame reporter_frame; + RealitySceneResult result; + uint8_t stagnation = 0, defensive_push = 0, return_flags = 0; + bool first_round = true, finished = false, shot = false, event_stop = false; + size_t rounds = 0; +}; +struct RealitySceneTick { + size_t round = 0; + int side = 0, ball_actor = -1; + std::vector moved_figures; // actual Source order, not a sorted view + std::vector reports; // one layout flush per call + std::optional motion; // omitted after a forced stop + RealitySceneResult result; + bool finished = false; +}; +// RealityReporterPanel initialization and DecideRealityBall/RealityReporterPanel control flow. The real forced +// card callback runs at the existing Source boundary; any deferred change must +// be retained by that caller and settled after the returned scene finishes. +// MatchEngine calls this through the fixture-owned Reality adapter. +void initialize_reality_scene(GameState&,const std::array&,int side,const RealityFormations&, + const LeImage&,const RealitySceneContext&,WatcomRandom&,GameRandom&,RealityScene&); +void exit_reality_scene_after_animation(RealityScene&); +RealitySceneTick advance_reality_scene(GameState&,RealityScene&,const LeImage&,WatcomRandom&,GameRandom&, + const RealityForcedEvent& forced_event = {},bool user_exit = false); +} // namespace bmh diff --git a/src/game/reality_setup.cpp b/src/game/reality_setup.cpp new file mode 100644 index 0000000..32349d7 --- /dev/null +++ b/src/game/reality_setup.cpp @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_setup.hpp" + +#include +#include + +namespace bmh { +namespace { +int manager(const GameState& state, int team) { + const int found = state.manager_of(team); + if (found >= 0) return found; + // FindManagerForClub's separate national-manager record is not in manager_teams. + if (!state.manager_teams.empty() && state.manager_teams[0] == kNoTeam && + state.manager_records.size() >= 4*0xb0c+0x292 && + le16(state.manager_records,4*0xb0c+0x290) == team) return 4; + return -1; +} + +std::optional> marked_position(const GameState& state, const RealitySetup& setup, int figure) { + const int side = figure > 10, other = 1-side; + const int own_manager = manager(state,setup.teams[size_t(side)]); + const int other_manager = manager(state,setup.teams[size_t(other)]); + int target = 0xfff; + if (own_manager >= 0) { + target = le16(state.tactics,size_t(own_manager)*0x840+size_t(figure-side*11)*0x58+0x44); + for (int row = other*11; row < other*11+11; ++row) + if (setup.players[size_t(row)].player == target) { target = row;break; } + } else if (other_manager >= 0) { + for (int row = 0; row < 11; ++row) + if (le16(state.tactics,size_t(other_manager)*0x840+size_t(row)*0x58+0x46) == + setup.players[size_t(figure)].player) { target = other*11+row;break; } + } + // RealityMarkedPosition also tests the unchanged low numeric target after a failed lookup. + if (target < 24 && setup.motion.figures[size_t(target)].active) { + if (target == 23) return std::pair{setup.motion.figures[23].next_x,setup.motion.figures[23].next_y}; + return setup.grid.position(target); + } + if (target >= 24 && target < 34) + throw FormatError("Reality setup: legacy marker addresses an untracked Source figure"); + return std::nullopt; +} + +void validate(const GameState& state, const std::array& teams, int side, const RealityFormations& positions) { + if (side < 0 || side > 1 || teams[0] == teams[1]) throw FormatError("Reality setup: invalid fixture"); + for (int s = 0; s < 2; ++s) { + const int team = teams[size_t(s)]; + if (team < 0) throw FormatError("Reality setup: invalid team"); + const auto range = squad_range(team); + if (range.first+range.count > state.squad_slots.size() || range.count < 11) + throw FormatError("Reality setup: truncated squad"); + const int m = manager(state,team); + if (m >= 0 && (state.manager_records.size() < size_t(m)*0xb0c+0xd9 || + state.tactics.size() < size_t(m+1)*0x840)) + throw FormatError("Reality setup: truncated manager/board"); + for (const auto& p : positions[size_t(s)]) + if (p.first < 0 || p.first > 30 || p.second < 0 || p.second > 8) + throw FormatError("Reality setup: prepared formation outside supported Source grid"); + for (size_t row = 0; row < 11; ++row) { + const auto slot = state.squad_slots[range.first+row]; + if (!(slot & kSlotInLineup)) continue; + const size_t player = slot & 0xfff; + if (player == 0xfff || player >= state.players.size() || player >= state.player_cards.size()) + throw FormatError("Reality setup: invalid starting player"); + if (m >= 0) { + const size_t board = size_t(m)*0x840+row*0x58; + if (state.tactics[board+2] > 38 || state.tactics[board+3] > 99 || state.tactics[board+4] > 99) + throw FormatError("Reality setup: unsupported player movement limits"); + } + } + } +} +} // namespace + +std::optional> reality_marked_position(const GameState& state, const RealitySetup& setup, int figure) { + if (figure < 0 || figure >= 22) throw FormatError("Reality: invalid marked player"); + for (int side=0;side<2;++side) { + const int m=manager(state,setup.teams[size_t(side)]); + if (m>=0 && state.tactics.size()& teams) { + RealityFormations result{}; + for (int side = 0; side < 2; ++side) for (int row = 0; row < 11; ++row) { + const int m = manager(state,teams[size_t(side)]); + if (m >= 0) { + const size_t at = size_t(m)*0x840+size_t(row)*0x58; + result[size_t(side)][size_t(row)] = {int(int8_t(state.tactics.at(at+0x41))),int(int8_t(state.tactics.at(at+0x42)))}; + } else { + int x = 0,y = 0;state.formation_position(teams[size_t(side)],row,x,y); + result[size_t(side)][size_t(row)] = {x,y}; + } + } + return result; +} + +void initialize_reality(GameState& state, const std::array& teams, int attacking_side, + const RealityFormations& positions, const LeImage& exe, WatcomRandom& rand, GameRandom& game, RealitySetup& setup) { + validate(state,teams,attacking_side,positions); + setup.ready = false;setup.teams = teams;setup.attacking_side = attacking_side; + for (int side = 0; side < 2; ++side) { + const int m = manager(state,teams[size_t(side)]); + for (int option = 0; option < 7; ++option) + setup.tactics[size_t(side)][size_t(option)] = uint8_t(m < 0 ? + rand.range(0,exe.u8(::bmh::layout::RealitySetup_InitializeReality_RuntimeFieldUnsigned+uint32_t(option))) : + state.manager_records.at(size_t(m)*0xb0c+0xd2+size_t(option))); + } + setup.grid.reset_occupancy(); // SizeT2 clears only the two occupancy planes. + for (int pass = 0; pass < 2; ++pass) { + const int side = pass ^ attacking_side, team = teams[size_t(side)], m = manager(state,team); + const auto range = squad_range(team); + std::array,5> candidates{};size_t candidates_count = 0, formation_cursor = 0; + for (int row = 0; row < 11; ++row) { + const int figure = side*11+row;auto& info = setup.players[size_t(figure)]; + auto& motion = setup.motion.figures[size_t(figure)]; + motion.active = false;info.player = 0; + const uint16_t slot = state.squad_slots.at(range.first+size_t(row)); + if (!(slot & kSlotInLineup)) continue; + // Source advances the prepared-formation cursor only for active rows. + const auto formation = positions[size_t(side)].at(formation_cursor++); + int x = int(int8_t(formation.first*14/10)), y = int(uint8_t(12-(4-formation.second)*25/10)); + if (x) x = std::max(1,int(int8_t(x+(side == attacking_side ? setup.tactics[size_t(side)][0]*2+4 : setup.tactics[size_t(side)][0]-2)))); + x = std::min(x,27); + if (side) { x = 42-x;y = 24-y; } + info.center_x = x;info.center_y = y; + const size_t board = m >= 0 ? size_t(m)*0x840+size_t(row)*0x58 : 0; + if (m < 0) { + info.min_x = x-4;info.max_x = x+4;info.min_y = y-2;info.max_y = y+2; + } else { + const int bias = state.tactics[board+2]; + const int left = side ? bias : 38-bias, right = side ? 38-bias : bias; + info.min_x = x-(int(state.tactics[board+3])+19+left)*42/235; + info.max_x = x+(int(state.tactics[board+3])+19+right)*42/235; + const int vertical = (int(state.tactics[board+4])*2/3+5)*25/117; + info.min_y = y-vertical;info.max_y = y+vertical; + } + if (row && (info.max_x < 2 || info.min_x > 40 || info.max_y < 1 || info.min_y > 23)) + throw FormatError("Reality setup: movement box cannot reach the Source pitch"); + for (int tries = 0; tries < 30; ++tries) { + if (row) { + do { x = int(int8_t(rand.range(info.min_x,info.max_x))); } while (x < 2 || x > 40); + do { y = int(int8_t(rand.range(info.min_y,info.max_y))); } while (y < 1 || y > 23); + } + if (!setup.grid.occupant(x,y,side)) break; + } + if (m >= 0) { + int increment = setup.tactics[size_t(attacking_side)][6] != 0; + const int distance = int(int8_t(std::abs(x-info.center_x)+std::abs(y-info.center_y))); + if (distance > 6 && rand.range(0,distance) > 6) ++increment; + if (increment) state.tactics[board+0xf] = uint8_t(std::clamp(int(int8_t(state.tactics[board+0xf]))+increment,0,99)); + } + if (side == attacking_side && x > 10 && x < 30 && candidates_count < candidates.size()) + candidates[candidates_count++] = {x,y}; + info.player = slot & 0xfff;info.squad_slot = int(range.first)+row; + info.card_value = state.player_cards.at(size_t(info.player)) & 31; + if (pass) if (const auto marker = marked_position(state,setup,figure)) { x = marker->first;y = marker->second; } + while (!setup.grid.place(figure,x,y,side)) { + const int next_x = int(int8_t(rand.range(x-1,x+1))); + const int next_y = int(int8_t(rand.range(y-1,y+1))); + x = std::clamp(next_x,0,42); + y = std::max(next_y,0); + // FormatError4's y>24 branch writes the packed x byte, leaving y + // outside the playable grid. Do not silently normalize this + // legacy spare-row/memory case into a different simulation. + if (y > 24) + throw FormatError("Reality setup: legacy collision enters an unsupported spare row"); + } + motion.active = true;motion.old_x = motion.next_x = x;motion.old_y = motion.next_y = y; + } + if (candidates_count) { + const auto ball = candidates[size_t(rand.range(1,int(candidates_count))-1)]; + setup.grid.place(22,ball.first,ball.second,2); + setup.motion.figures[22] = {true,ball.first,ball.second,ball.first,ball.second,0}; + } else if (side == attacking_side) return; + } + // RealityReporterPanel draws all 24 initial phases only after a successful FormatError4. + for (int figure = 0; figure < 24; ++figure) { + const int pose = figure < 22 ? (figure > 10 ? 7 : 0) : figure-14; + setup.motion.figures[size_t(figure)].phase = uint8_t(game.range(0,exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned+uint32_t(pose))-1)); + } + setup.motion.figures[23].active = setup.motion.figures[22].active; + setup.motion.ball_airborne = false; + setup.motion.numbers = (state.memory.has(::bmh::layout::RealityMatch_FormatError_ExecutableField) ? state.memory.u8(::bmh::layout::RealityMatch_FormatError_ExecutableField) : exe.u8(::bmh::layout::RealityMatch_FormatError_ExecutableField)) == 0; + setup.ready = true; +} + +} // namespace bmh diff --git a/src/game/reality_setup.hpp b/src/game/reality_setup.hpp new file mode 100644 index 0000000..39aae44 --- /dev/null +++ b/src/game/reality_setup.hpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/reality_motion.hpp" +#include "game/state.hpp" +#include + +namespace bmh { + +using RealityFormations = std::array,11>,2>; +struct RealityPlacement { + int player = 0, squad_slot = -1, card_value = 0; + int center_x = 0, center_y = 0; + int min_x = 0, max_x = 0, min_y = 0, max_y = 0; +}; +struct RealitySetup { + RealityGrid grid; + RealityMotionInput motion; + std::array players{}; + std::array,2> tactics{}; + std::array teams{}; + int attacking_side = 0; + bool ready = false; +}; + +// RealityMarkedPosition, shared by initialization and subsequent defensive movement. +std::optional> reality_marked_position(const GameState&, const RealitySetup&, int figure); + +// Int2's interleaved prepared positions, supplied separately to the scene. +RealityFormations reality_formations(const GameState&, const std::array& teams); +// RealityReporterPanel profile preparation + FormatError4 + initial sprite phases. This is a +// simulation operation: it consumes the real RNGs and can update board fatigue. +// It is not called by a renderer and is not yet connected to MatchEngine::side. +void initialize_reality(GameState&, const std::array& teams, int attacking_side, + const RealityFormations&, const LeImage&, WatcomRandom&, GameRandom&, RealitySetup&); + +} // namespace bmh diff --git a/src/game/reality_space.cpp b/src/game/reality_space.cpp new file mode 100644 index 0000000..9fc7400 --- /dev/null +++ b/src/game/reality_space.cpp @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reality_space.hpp" + +#include +#include + +namespace bmh { +namespace { +void side_ok(int side) { + if (side < 0 || side > 1) throw FormatError("Reality space: invalid side"); +} +void path_ok(const RealityPath& path) { + if (path.count > path.points.size()) throw FormatError("Reality space: truncated path"); + for (size_t i = 0; i < path.count; ++i) { + const auto [x,y] = path.points[i]; + if (x < 0 || x > 42 || y < 0 || y > 24) + throw FormatError("Reality space: path outside playable grid"); + } +} +bool playable(int x,int y) { return x >= 0 && x <= 42 && y >= 0 && y <= 24; } + +// RealityPath also receives movement-box centers outside the pitch. Unlike +// occupancy/projection, its signed-byte line does not clip those endpoints. +RealityPath box_path(int x,int y,int target_x,int target_y) { + const int ax=std::abs(target_x-x),ay=std::abs(target_y-y),length=std::max(ax,ay); + if (target_x < -128 || target_x > 127 || target_y < -128 || target_y > 127 || length > 127) + throw FormatError("Reality space: unsupported signed-byte box center"); + RealityPath path;const int sx=length ? ax*100/length : 0,sy=length ? ay*100/length : 0; + const int dx=target_x49) break; + if (x!=target_x && (ex+=sx)>=100-sx) { ex-=100;x+=dx; } + if (y!=target_y && (ey+=sy)>=100-sy) { ey-=100;y+=dy; } + } + path.points[path.count++]={x,y};return path; +} +} // namespace + +bool reality_on_path(const RealityPath& path,int x,int y) { + path_ok(path); + return std::find(path.points.begin(),path.points.begin()+path.count,std::pair{x,y})!=path.points.begin()+path.count; +} + +bool reality_offside(const RealitySetup& scene,int x) { + const int side=scene.attacking_side;side_ok(side); + const int ball_x=scene.grid.ball().first; + if ((side==1 && (x>20 || x>ball_x)) || (side==0 && (x<20 || x255) throw FormatError("Reality space: invalid neighborhood radius"); + const int left=forward && side==1 ? 0 : radius,right=forward && side==0 ? 0 : radius; + int count=0; + // RealityPenaltyArea deliberately counts all eleven coordinate slots, including + // inactive/stale ones; neither occupancy nor active flags are consulted. + for (int id=side*11;id=-left && px-x<=right) ++count; + } + return count; +} + +int reality_penalty_area(const RealitySetup& scene,const LeImage& exe,int side,int x,int y) { + side_ok(side); + const int min_x=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField),max_x=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField2),min_y=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField3),max_y=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField4); + if (x!=-1) return min_x<=x && x<=max_x && min_y<=y && y<=max_y; + // Source only offsets the scan; the point-membership branch above uses + // the unmirrored literal bounds even for side1. + const int offset=side ? 30 : 0; + if (!playable(min_x+offset,min_y) || !playable(max_x+offset,max_y)) + throw FormatError("Reality space: invalid Source penalty-area table"); + int count=0; + for (int px=min_x+offset;px<=max_x+offset;++px) + for (int py=min_y;py<=max_y;++py) if (scene.grid.occupant(px,py,side)) ++count; + return count; +} + +RealityLineOccupants reality_line_occupants(const RealitySetup& scene,const RealityPath& path,int side,bool select,WatcomRandom& rand) { + side_ok(side);path_ok(path);RealityLineOccupants result; + for (size_t i=0;i+1=22) throw FormatError("Reality space: invalid player"); + const auto [x,y]=scene.grid.position(figure); + int left=2,right=3; + RealityPath player_goal; + if (flags&0x10) { + if (!goal_path.count) throw FormatError("Reality space: missing Source goal path"); + const auto target=goal_path.points[goal_path.count-1]; + player_goal=reality_path(x,y,target.first,target.second); + if (!(flags&8)) { if (side==0) left=0;else right=1; } + } + RealitySpaceTarget result;int best=-100; + for (int px=x-left;px=5 && py<=19); + if (py==y) score+=2; + if (flags) { + if ((flags&8) && reality_offside(scene,px)) continue; + if (!(flags&0x20)) { + if (scene.grid.occupant(px,py,1-side)) continue; + score+=10-3*reality_nearby(scene,px,py,1-side,2,false); + } + score+=20-4*reality_nearby(scene,px,py,side,3,false); + if ((flags&0x10) && px!=x && mode<4) + score+=10*reality_on_path(player_goal,px,py)+15*reality_penalty_area(scene,exe,1-side,px,py); + } + if (flags&2) score+=std::abs(12-py)*(scene.tactics[size_t(side)][1]+4); + if (flags&0x20) score+=20*reality_on_path(goal_path,px,py); + const int source_score=int(int16_t(score)); + if (source_score>best) { best=source_score;result={true,px,py,source_score,-1}; } + } + return result; +} + +RealitySpaceTarget reality_support(const RealitySetup& scene,int x,int y,int side,int16_t minimum_score,uint8_t pressure) { + side_ok(side);RealitySpaceTarget result;int best=minimum_score; + for (int px=x-4;px25) depth+=10; + int score=depth+40; + if (!pressure) score+=depth;else if (depth>38) score=depth+120; + score-=2*std::max(std::abs(x-px),std::abs(y-py)); + if (scene.grid.ball()==std::pair{px,py}) score+=32; + if (score>best) { best=score;result={true,px,py,score,occupant-1}; } + } + return result; +} + +void reality_return_to_box(RealitySetup& scene,int figure,int side,uint8_t steps,GameRandom& game) { + side_ok(side); + if (figure<0 || figure>=22) throw FormatError("Reality space: invalid player"); + const auto& box=scene.players[size_t(figure)];const auto old=scene.grid.position(figure); + const int cx=int(int8_t((box.min_x+box.max_x)/2)),cy=int(int8_t((box.min_y+box.max_y)/2)); + const auto path=box_path(old.first,old.second,cx,cy); + auto [x,y]=path.points[std::min(size_t(steps),path.count-1)]; + while (!scene.grid.place(figure,x,y,side)) { + const int next_x=int(int8_t(x+game.range(0,2)-1)); + const int next_y=int(int8_t(y+game.range(0,2)-1)); + x=std::clamp(next_x,0,42);y=std::clamp(next_y,0,24); + } + auto& motion=scene.motion.figures[size_t(figure)];motion.next_x=x;motion.next_y=y; +} + +} // namespace bmh diff --git a/src/game/reality_space.hpp b/src/game/reality_space.hpp new file mode 100644 index 0000000..b911df9 --- /dev/null +++ b/src/game/reality_space.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/reality_setup.hpp" + +namespace bmh { + +// Source spatial decisions, still independent of the unfinished Reality loop. +bool reality_on_path(const RealityPath&, int x, int y); // RealityOffside +bool reality_offside(const RealitySetup&, int x); // RealityNearby, current attacking side +int reality_nearby(const RealitySetup&, int x, int y, int side, int radius, bool forward); // RealityPenaltyArea +int reality_penalty_area(const RealitySetup&, const LeImage&, int side, int x = -1, int y = -1); // RealityLineOccupants2 +struct RealityLineOccupants { int count = 0; uint8_t selected = 0; }; +// RealityLineOccupants excludes the terminal cell; sampling uses Watcom, not GameRandom. +RealityLineOccupants reality_line_occupants(const RealitySetup&, const RealityPath&, int side, + bool select, WatcomRandom&); +struct RealitySpaceTarget { + bool found = false; + int x = 0, y = 0, score = 0, figure = -1; +}; +// RealitySeekSpace: caller supplies the existing ball-to-goal path, flags and mode. +RealitySpaceTarget reality_seek_space(const RealitySetup&, const LeImage&, int figure, int side, + uint8_t flags, uint8_t mode, const RealityPath& goal_path); +// RealitySupport: best unopposed occupied support cell within the Source 9x9 scan. +RealitySpaceTarget reality_support(const RealitySetup&, int x, int y, int side, + int16_t minimum_score, uint8_t pressure); +// RealityReturnToBox. The Source caller must clear the figure's old occupancy first. +// Updates runtime placement/next position and consumes Game RNG only on collision. +void reality_return_to_box(RealitySetup&, int figure, int side, uint8_t steps, GameRandom&); + +} // namespace bmh diff --git a/src/game/reschedule.cpp b/src/game/reschedule.cpp new file mode 100644 index 0000000..ca8fd12 --- /dev/null +++ b/src/game/reschedule.cpp @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/reschedule.hpp" + +#include + +#include "game/matchday_setup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" + +namespace bmh { + +namespace { + +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day +constexpr int kCalendarDays = 0x16e; // CalendarCell copies 0x16e words +constexpr uint32_t kPostponed = ::bmh::layout::Postponed; // 40 entries: u16 day, round, league, match +constexpr int kPostponedEntries = 0x28; +constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; // friendly plan: team pairs +constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; // friendly plan: days, 30 entries +constexpr int kFriendlyEntries = 30; +// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break. +constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8; +// RescheduleLeagueMatch accepts replay days up to 0x11e; the draw loop wants the day after the +// target inside 0x15 .. 0x11e. +constexpr int kLastReplayDay = 0x11e, kFirstDayAfter = 0x15; +constexpr uint8_t kRescheduledMark = 0xce; // param_5 = -0x32 +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kFloodlights = 0x0e; // manager record byte (RescheduleRuntimeField) +// LeagueCalendarBits: calendar bit of a league (the two leagues 2 and 3 share bit 2, the four +// leagues of 12 clubs bit 4; compare kGroupLeague in matchday_setup.cpp). +// (kLeagueBit: schedule.hpp, set from the groups of the loaded game; 0xff = not played) + +size_t result_at(int league, int round, int match) { return size_t(match) + size_t(round) * 10 + size_t(league) * 0x17c; } + +bool memory_ok(const GameState& g) { + return g.memory.has(kCalendar + kCalendarDays * 2 - 1) && + g.memory.has(kPostponed + kPostponedEntries * 6 - 1) && g.memory.has(kFriendlyDays + kFriendlyEntries * 2 - 1) && + g.memory.has(kFriendlyTeams + kFriendlyEntries * 4 - 1); +} + +// The club of a human manager in league play, or -1. +int manager_team(const GameState& g, int manager) { + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return -1; + const int team = g.manager_teams[size_t(manager)]; + if (team < 0 || team_league(team) >= kLeagueCount) return -1; + return team; +} + +std::vector round_fixtures(int league, int round) { + return generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league)); +} + +// DayConflict(team, other, word, day): 1 when `day` (calendar word `word` of the screen's +// copy) cannot take a match of `team`/`other`: the word is taken (anything but 0, 0x4001 or +// a word marked eligible with bit 15) or the friendly plan already has a match of one of the +// teams - or of the national team - on that day. +bool day_conflict(const GameState& g, int team, int other, uint16_t word, int day) { + if (word != 0 && word != 0x4001 && (word & 0x8000) == 0) return true; + for (int i = 0; i < kFriendlyEntries; i++) { + if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(day)) continue; + for (int side = 0; side < 2; side++) { + const int t = int16_t(g.memory.u16(kFriendlyTeams + uint32_t(i) * 4 + uint32_t(side) * 2)); + if (t == kNoTeam || t == team || t == other) return true; + } + } + return false; +} + +// RescheduleTargetDays(day, team, league): entry + 1 of a replay of `team` in `league` on `day`, or 0 +// (the last such entry, as the original keeps looking). +int team_replay_on(const GameState& g, int day, int team, int league) { + int found = 0; + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day) || g.memory.u8(at + 3) != league) continue; + const Fixture f = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4)); + if (f.home == team || f.away == team) found = e + 1; + } + return found; +} + +// The draw loop of CalendarCell in mode 2 on a copy of the calendar: a future day is marked +// (bit 15) when it is free (0, 0x4001 or a calendar event 0x1c0), neither it nor its two +// neighbours conflict for the club (the neighbours before it may already be marked), the +// day after it lies in 0x15 .. 0x11e and it is not in the winter break. The national team +// (manager 0 coaching team 0x165) also checks the club of the Bundestrainer, CupDraw_FormatError_RuntimeField3. +std::vector marked_calendar(const GameState& g, int team) { + std::vector cal(kCalendarDays); + for (int d = 0; d < kCalendarDays; d++) cal[size_t(d)] = g.memory.u16(kCalendar + uint32_t(d) * 2); + // DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day + const int today = g.season_day(); + const bool national = !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam && g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField); + for (int d = today + 1; d < kCalendarDays; d++) { + const uint16_t word = cal[size_t(d)]; + if (word != 0 && word != 0x4001 && (word & 0x1c0) == 0) continue; + bool ok = true; + for (int i = std::max(0, d - 1); i <= std::min(kCalendarDays - 1, d + 1); i++) { + if (day_conflict(g, team, -1, cal[size_t(i)], i)) ok = false; + if (national && day_conflict(g, int16_t(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)), -1, cal[size_t(i)], i)) ok = false; + } + if (d + 1 > kLastReplayDay || d + 1 < kFirstDayAfter) ok = false; + if (d >= kWinterBreakFirst && d <= kWinterBreakLast) ok = false; + if (team == kNoTeam && (word & 0x1c0) != 0) ok = false; + if (ok) cal[size_t(d)] |= 0x8000; + } + return cal; +} + +} // namespace + +std::vector reschedulable_matches(const GameState& g, int manager) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const int league = team_league(team); + // The screen only reacts to the calendar bit of the club's league for bits 0-3 + // (local_34 == bit); CalendarCell derives local_34 as league - (league > 2). + const int screen_bit = league > 2 ? league - 1 : league; + if (screen_bit > 3 || kLeagueBit[league] != screen_bit) return out; + // DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day + const int today = g.season_day(); + const int matchdays = league_matchdays(league); + int round = -1; + for (int day = 0; day < kCalendarDays; day++) { + const uint32_t comps = day_competitions(g, g.memory.u16(kCalendar + uint32_t(day) * 2)); + if (kLeagueBit[league] > 7 || !((comps >> kLeagueBit[league]) & 1)) continue; + ++round; // local_58 - 1: the league days up to this one + if (day <= today || round == 0 || round + 2 >= matchdays) continue; + const std::vector fixtures = round_fixtures(league, round); + for (size_t m = 0; m < fixtures.size(); m++) { + const Fixture& f = fixtures[m]; + if (f.home != team && f.away != team) continue; + // the screen picks the club's match of the day; only a home match can be moved + if (f.home == team && g.results.at(result_at(league, round, int(m))) == kNotPlayed) + out.push_back({day, round, league, int(m), f.home, f.away}); + break; + } + } + return out; +} + +std::vector reschedule_target_days(const GameState& g, int manager, const LeagueMatchRef& match) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const std::vector movable = reschedulable_matches(g, manager); + if (std::none_of(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) { + return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match; + })) + return out; + std::vector cal = marked_calendar(g, team); + // floodlights: the day before the matchday (the Friday) is offered as well + if ((size_t(manager) + 1) * kRecordSize <= g.manager_records.size() && + g.manager_records[size_t(manager) * kRecordSize + kFloodlights] != 0 && match.day > 0) + cal[size_t(match.day - 1)] |= 0x8000; + for (int d = 0; d < kCalendarDays; d++) + if ((cal[size_t(d)] & 0x8000) && d != match.day && d <= kLastReplayDay && team_replay_on(g, d, team, match.league) == 0) + out.push_back(d); + return out; +} + +RescheduleStatus reschedule_league_match(GameState& g, int manager, const LeagueMatchRef& match, int day) { + if (manager_team(g, manager) < 0 || !memory_ok(g)) return RescheduleStatus::invalid_manager; + const std::vector movable = reschedulable_matches(g, manager); + const auto it = std::find_if(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) { + return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match; + }); + if (it == movable.end()) return RescheduleStatus::invalid_match; + const std::vector days = reschedule_target_days(g, manager, *it); + if (std::find(days.begin(), days.end(), day) == days.end()) return RescheduleStatus::invalid_day; + // the first free entry of the postponed list + int slot = -1; + for (int e = 0; e < kPostponedEntries && slot < 0; e++) + if (g.memory.u16(kPostponed + uint32_t(e) * 6) == 0) slot = e; + if (slot < 0) return RescheduleStatus::no_free_slot; + // RescheduleLeagueMatch(day, league, match, slot, -0x32, round): eight replays on the day or a + // team clash with one of them refuse the move. Like the winter mode the original builds + // the other replay's fixtures with the parameters of this league and compares the low + // bytes of the team ids only. + const int league = it->league; + const Fixture own = round_fixtures(league, it->round).at(size_t(it->match)); + int same_day = 0; + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day)) continue; + if (++same_day == 8) return RescheduleStatus::day_full; + const Fixture other = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4)); + const uint8_t oh = uint8_t(other.home), oa = uint8_t(other.away), fh = uint8_t(own.home), fa = uint8_t(own.away); + if (fh == oh || fa == oa || fa == oh || fh == oa) return RescheduleStatus::team_clash; + } + const uint32_t at = kPostponed + uint32_t(slot) * 6; + g.memory.set16(at, uint16_t(day)); + g.memory.set8(at + 2, uint8_t(it->round)); + g.memory.set8(at + 3, uint8_t(league)); + g.memory.set8(at + 4, uint8_t(it->match)); + g.results.at(result_at(league, it->round, it->match)) = kRescheduledMark; + const uint32_t high = kCalendar + uint32_t(day) * 2 + 1; + g.memory.set8(high, g.memory.u8(high) | 0x40); + return RescheduleStatus::moved; +} + +std::vector moved_matches(const GameState& g, int manager) { + std::vector out; + const int team = manager_team(g, manager); + if (team < 0 || !memory_ok(g)) return out; + const int league = team_league(team); + const int today = g.season_day(); + // CalendarCell: a click on a replay day (calendar bit 0xe) finds the club's replay with + // RescheduleTargetDays(day, team, league) and calls UndoReschedule when its result byte is 0xCE + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + const int day = g.memory.u16(at); + if (day == 0 || day <= today || g.memory.u8(at + 3) != league) continue; + if (team_replay_on(g, day, team, league) != e + 1) continue; + const int round = g.memory.u8(at + 2), m = g.memory.u8(at + 4); + if (round == 0 || round + 2 >= league_matchdays(league)) continue; + if ((g.results.at(result_at(league, round, m)) & 0xcf) != kRescheduledMark) continue; + const Fixture f = round_fixtures(league, round).at(size_t(m)); + out.push_back({day, round, league, m, f.home, f.away}); + } + std::sort(out.begin(), out.end(), [](const LeagueMatchRef& a, const LeagueMatchRef& b) { return a.day < b.day; }); + return out; +} + +bool undo_reschedule(GameState& g, int manager, int day) { + const std::vector moved = moved_matches(g, manager); + if (std::none_of(moved.begin(), moved.end(), [&](const LeagueMatchRef& m) { return m.day == day; })) return false; + const int team = manager_team(g, manager); + // UndoReschedule(day, 1, team): every replay of the club on that day, whatever its league + for (int e = 0; e < kPostponedEntries; e++) { + const uint32_t at = kPostponed + uint32_t(e) * 6; + if (g.memory.u16(at) != uint16_t(day)) continue; + const int league = g.memory.u8(at + 3), round = g.memory.u8(at + 2), m = g.memory.u8(at + 4); + const Fixture f = round_fixtures(league, round).at(size_t(m)); + if (f.home != team && f.away != team) continue; + g.results.at(result_at(league, round, m)) = kNotPlayed; + g.memory.set16(at, 0); + } + return true; +} + +} // namespace bmh diff --git a/src/game/reschedule.hpp b/src/game/reschedule.hpp new file mode 100644 index 0000000..a19246f --- /dev/null +++ b/src/game/reschedule.hpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Rescheduling a home league match (desk menu 7, "Verlegen", H2 p. 49; BMH.exe V2.24 + +// supported rule profile patch). The original does it on the calendar screen CalendarCell with mode 2: +// +// 1. The manager clicks a matchday of his own league. The match of his club on that day +// is selected when it is a home match, still in the future, not on the first matchday +// and not on one of the last two matchdays. +// 2. The calendar then marks the days the match can move to (draw loop of CalendarCell, +// see reschedule_target_days). With floodlights (manager record +0x0e) the day before +// the matchday (the Friday) is offered as well. +// 3. A click on a marked day moves the match with RescheduleLeagueMatch(day, league, match, slot, +// -0x32, round): the match becomes a "replay" on that day (postponed list Postponed), +// its result byte becomes 0xCE and the calendar day gets bit 0x4000. On the original +// matchday the 0xCE turns into 0xCD (matchday_setup) and the match is played on the +// new day like a winter postponement. +// 4. A click on the new day of a moved match takes the move back (UndoReschedule(day, 1, +// team)): the entry is freed and the result byte is 0xCC again. The calendar keeps bit +// 0x4000, as in the original. +// +// Everything here works on the saved GameState only: no random numbers are drawn, so a +// rescheduled career stays deterministic. + +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +// A league match: day of the season (index into the calendar CompetitionCalendar), the 0-based +// league round, the league and the index of the match in the fixture list of that round. +struct LeagueMatchRef { + int day = -1; + int round = -1; + int league = -1; + int match = -1; + int home = -1; // team ids + int away = -1; + bool operator==(const LeagueMatchRef&) const = default; +}; + +enum class RescheduleStatus : uint8_t { + moved, + invalid_manager, // no human manager with a club in league play + invalid_match, // not one of reschedulable_matches() + invalid_day, // not one of reschedule_target_days() + no_free_slot, // all 40 entries of the postponed list are used + day_full, // eight replays on that day already (message Controller_CalendarFromGame_TextPointer) + team_clash, // a team of the match already plays a replay that day (Controller_CalendarFromGame_TextPointer) +}; + +// The own home league matches that can be moved: future days, rounds 1 .. matchdays - 3 +// (0-based), result byte still 0xCC (not played, not postponed). Only clubs of leagues +// 0-4 (calendar bits 0-3) take part: the lower leagues have no own calendar bit. +std::vector reschedulable_matches(const GameState& g, int manager); + +// The days `match` can be moved to (the days CalendarCell marks in mode 2), ascending. +// Days that already hold a replay of one of the teams in the same league are left out, as +// the second click refuses them (RescheduleTargetDays). +std::vector reschedule_target_days(const GameState& g, int manager, const LeagueMatchRef& match); + +// Moves `match` to `day` (RescheduleLeagueMatch with param_5 = -0x32). Returns moved on success; on +// failure nothing is changed. +RescheduleStatus reschedule_league_match(GameState& g, int manager, const LeagueMatchRef& match, int day); + +// The own matches moved with reschedule_league_match that can still be taken back: their new +// day (`day`) is in the future, the result byte is 0xCE and the round is one the screen +// accepts (1 .. matchdays - 3). Winter postponements (0xCD) are not listed. Like the +// original the club need not be the home side: in a hot seat game the opponent's manager can +// take back a move as well. +std::vector moved_matches(const GameState& g, int manager); + +// Takes back the move of the club's match on `day` (one of moved_matches) - UndoReschedule with +// param_2 = 1: every replay on that day with the club gets result byte 0xCC and its entry is +// freed. Returns false if there is no such match. +bool undo_reschedule(GameState& g, int manager, int day); + +} // namespace bmh diff --git a/src/game/save.cpp b/src/game/save.cpp new file mode 100644 index 0000000..affcb2a --- /dev/null +++ b/src/game/save.cpp @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/save.hpp" + +#include +#include +#include + +#include "formats/savestate.hpp" +#include "game/career.hpp" +#include "game/national.hpp" + +namespace bmh { + +namespace { + +void put(Bytes& d, const uint8_t* src, size_t n) { + for (size_t i = 0; i < n && i < d.size(); i++) d[i] = src[i]; +} +void put(Bytes& d, const std::vector& v) { put(d, v.data(), v.size()); } +void put16(Bytes& d, const std::vector& v) { + for (size_t i = 0; i < v.size() && 2 * i + 1 < d.size(); i++) d[2 * i] = uint8_t(v[i]), d[2 * i + 1] = uint8_t(v[i] >> 8); +} +void put32(Bytes& d, size_t at, uint32_t x) { + for (int i = 0; i < 4 && at + size_t(i) < d.size(); i++) d[at + size_t(i)] = uint8_t(x >> (8 * i)); +} + +// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a +// four-year leap cycle that starts with the third year). +std::string date_text(uint32_t counter) { + static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int cycle = 3, years = 0, month = 7; + while (counter > uint32_t(364 + (cycle == 4))) { + if (cycle == 4) cycle = 0, --counter; + ++years, counter -= 365, ++cycle; + } + auto days = [&] { return month == 2 ? 28 + (cycle == 4) : kDays[month]; }; + while (counter > uint32_t(days())) { + counter -= uint32_t(days()); + if (++month == 13) month = 1, ++years; + } + int day = int(counter) + 1; + if (day > days()) { + day -= days(); + if (++month == 13) month = 1, ++years; + } + char buf[16]; + std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, 2026 + years); + return buf; +} + +} // namespace + +Bytes save_stream(const GameState& live) { + // NationalCoachAfterLoad writes a Bundestrainer's game with the slots swapped back (national.hpp) + const bool coach = live.memory.has(::bmh::layout::CoachActive) && live.memory.u8(::bmh::layout::CoachActive) != 0; + const GameState swapped = coach ? national_coach_save_form(live) : GameState{}; + const GameState& g = coach ? swapped : live; + const bool records = g.memory.has(::bmh::layout::ClubSeasonRecords) && g.memory.u32(::bmh::layout::ClubSeasonRecords) != 0; + Bytes stream; + for (const SaveBlock& b : save_layout(DbCounts{}, records)) { + Bytes d(b.size, 0); + if (b.heap) { + switch (b.address) { + case ::bmh::layout::PlayerBonuses: put(d, g.player_bonus); break; + case ::bmh::layout::TeamMorale: put(d, g.team_morale); break; + case ::bmh::layout::ClubBadgeSelectors: put(d, g.club_heap_78); break; + case ::bmh::layout::TeamFlags: put16(d, g.team_flags); break; + case ::bmh::layout::ClubIdentities: put16(d, g.club_ids); break; + case ::bmh::layout::PlayerNameOffsets: put16(d, g.player_name_offsets); break; + case ::bmh::layout::MasterDatabaseMetadata: put(d, g.master_database_metadata); break; + case ::bmh::layout::ClubAuxiliaryWords: put(d, g.club_heap_bc); break; + case ::bmh::layout::LeagueRankHistory: put(d, g.position_history); break; + case ::bmh::layout::ClubAuxiliaryBytes: put(d, g.club_heap_b8); break; + case ::bmh::layout::SquadSlots: put16(d, g.squad_slots); break; + case ::bmh::layout::PlayerCards: put16(d, g.player_cards); break; + case ::bmh::layout::ManagerMailbox: put(d, g.mailbox); break; + case ::bmh::layout::TournamentName: put(d, g.tournament_name); break; + case ::bmh::layout::ClubSeasonRecords: put(d, g.club_table); break; + case ::bmh::layout::PlayerConditionTechniqueForm: + case ::bmh::layout::PlayerSkillWords: + case ::bmh::layout::PlayerIdentityWords: + for (size_t i = 0; i < g.players.size(); i++) { + const Player& p = g.players[i]; + put32(d, i * 4, b.address == ::bmh::layout::PlayerConditionTechniqueForm ? p.w35c : b.address == ::bmh::layout::PlayerSkillWords ? p.w368 : p.w364); + } + break; + default: break; + } + } else { + for (size_t i = 0; i < b.size; i++) + if (g.memory.has(b.address + uint32_t(i))) d[i] = g.memory.u8(b.address + uint32_t(i)); + // the blocks GameState keeps in typed fields + switch (b.address) { + case ::bmh::layout::ManagerRecords: put(d, g.manager_records); break; + case ::bmh::layout::ManagerMatchHistory: put(d, g.manager_results); break; + case ::bmh::layout::ManagerRatings: put(d, g.manager_ratings); break; + case ::bmh::layout::LeagueResults: put(d, g.results); break; + case ::bmh::layout::LeagueRoundCounters: put(d, g.league_rounds); break; + case ::bmh::layout::TacticsBoards: put(d, g.tactics); break; + case ::bmh::layout::StockExchange: put(d, g.stocks); break; + case ::bmh::layout::ManagerAutomation: put(d, g.manager_options); break; + case ::bmh::layout::Formations: put(d, g.formations); break; + case ::bmh::layout::ForeignClubStrength: put(d, g.foreign_strength); break; + case ::bmh::layout::Difficulty: d[0] = uint8_t(g.level); break; + case ::bmh::layout::CalendarDay: put32(d, 0, g.date); break; + case ::bmh::layout::DaysIntoSeason: d[0] = uint8_t(g.date - g.season_start), d[1] = uint8_t((g.date - g.season_start) >> 8); break; + case ::bmh::layout::PlayerDevelopmentBalance: put32(d, 0, uint32_t(g.development_balance)); break; + case ::bmh::layout::SeasonIndex: d[0] = uint8_t(g.season), d[1] = uint8_t(uint16_t(g.season) >> 8); break; + default: break; + } + } + stream.insert(stream.end(), d.begin(), d.end()); + } + for (const std::vector* pool : {&g.club_names, &g.player_names, &g.referee_names, &g.stadium_names}) { + stream.push_back(uint8_t(pool->size())); + stream.push_back(uint8_t(pool->size() >> 8)); + stream.insert(stream.end(), pool->begin(), pool->end()); + } + // the English cup memory has no place in the original layout: OpenBMH extension + std::vector extension; + for (const auto& [at, size] : kEnglishCompetitionBlocks) + if (g.memory.has(at) && g.memory.has(at + size - 1)) { + Bytes bytes(size); + for (uint32_t i = 0; i < size; ++i) bytes[i] = g.memory.u8(at + i); + extension.push_back({at, std::move(bytes)}); + } + append_save_extension(stream, extension); + return stream; +} + +Bytes save_header(const GameState& g) { + const int managers = g.memory.u8(::bmh::layout::ManagerCount); + Bytes h; + h.push_back(uint8_t(managers)); + const std::string date = date_text(g.date); + for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0); + Bytes list(0xa0, 0); + for (int m = 0; m < managers && m < 4; m++) { + const size_t rec = size_t(m) * 0xb0c; + const int team = int16_t(g.manager_records.at(rec + 0x290) | g.manager_records.at(rec + 0x291) << 8); + const bool national = team == 0x165; + const size_t at = size_t(m) * 0x28; + list[at] = national ? 0x1e : g.manager_records.at(rec + 0x210); // (0x1e: high byte of the loop word) + list[at + 1] = national ? 1 : 0; + for (size_t i = 0; i < 0x13; i++) list[at + 2 + i] = g.manager_records.at(rec + 0xa8 + i); + const size_t name = g.club_ids.at(size_t(team)); + for (size_t i = 0; i < 0x13 && name + i < g.club_names.size(); i++) list[at + 0x15 + i] = g.club_names[name + i]; + } + h.insert(h.end(), list.begin(), list.end()); + return h; +} + +Savegame make_savegame(const GameState& g, WatcomRandom& rand) { + Savegame s; + s.plain_header = save_header(g); + s.id1 = 0; + s.version = "V2.24"; + const uint32_t hi = uint32_t(rand.range(0, 0x8fff)), lo = uint32_t(rand.range(0, 0x8fff)); + s.id2 = lo + hi * 0x10000 + 1; + s.key = uint8_t(rand.range(0, 0xff) + 'n'); + s.random = uint8_t(rand.range(0, 0xff)); + s.stream = save_stream(g); + uint8_t sum = s.key; + for (uint8_t b : s.stream) sum = uint8_t(sum + b); + s.checksum = sum; + s.checksum_ok = true; + return s; +} + +Bytes savegame_bytes(const Savegame& s) { + Bytes out = s.plain_header; + static const char magic[10] = {'K', 'R', 'O', 'N', '_', 'F', 'B', 'M', 0, 'k'}; + out.insert(out.end(), magic, magic + 10); + for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id1 >> (8 * i))); + for (size_t i = 0; i < 6; i++) out.push_back(i < s.version.size() ? uint8_t(s.version[i]) : 0); + for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id2 >> (8 * i))); + out.push_back(s.random); + out.push_back(s.key); + Bytes enc = s.stream; + fbm_encrypt(enc.data(), enc.size(), s.key); + out.insert(out.end(), enc.begin(), enc.end()); + out.push_back(s.checksum); + return out; +} + +void write_savegame(const std::filesystem::path& path, const Savegame& s) { + const Bytes b = savegame_bytes(s); + std::ofstream f(path, std::ios::binary | std::ios::trunc); + if (!f) throw FormatError("cannot write " + path.string()); + f.write(reinterpret_cast(b.data()), std::streamsize(b.size())); + const bool written = bool(f); + f.close(); + // Buffered final bytes can fail only at close, after write reported the + // complete size. The autosave caller must not publish that temporary file. + if (!written || !f) throw FormatError("short write " + path.string()); +} + +} // namespace bmh diff --git a/src/game/save.hpp b/src/game/save.hpp new file mode 100644 index 0000000..9fec2d6 --- /dev/null +++ b/src/game/save.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Writing savegames (MakeSavegame with FbmDecrypt2 and NationalCoachAfterLoad). +// +// A GameState keeps part of the savegame in typed fields (players, squads, records, ...) +// and the rest in StaticMemory; save_stream puts both back into the block order of the +// original, so that loading a savegame and saving it again gives the same stream. + +#include +#include + +#include "formats/binary.hpp" +#include "formats/fbm.hpp" +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// The decrypted stream of a savegame: the 125 state blocks (NationalCoachAfterLoad, with the club +// records when their pointer ClubSeasonRecords is set) and the four name pools. +Bytes save_stream(const GameState& g); + +// FbmDecrypt2: the plain header read by the load list - the number of managers, the date +// ("TT.MM.JJJJ") and per manager (0x28 bytes): start league, national team flag, his name +// and his club's name (0x13 bytes each). The original leaves stack bytes in the unused +// parts; they are zero here. +Bytes save_header(const GameState& g); + +// MakeSavegame from the header on: "KRON_FBM", the previous id (here 0), "V2.24", the new +// id W(0, 0x8fff) << 16 + W(0, 0x8fff) + 1, the key byte W(0, 0xff) + 'n' and a random byte +// W(0, 0xff) (the four Watcom draws of saving), the encrypted stream and its checksum. +Savegame make_savegame(const GameState& g, WatcomRandom& rand); + +// The file bytes of a savegame (inverse of load_savegame). +Bytes savegame_bytes(const Savegame& s); +void write_savegame(const std::filesystem::path& path, const Savegame& s); + +} // namespace bmh diff --git a/src/game/schedule.cpp b/src/game/schedule.cpp new file mode 100644 index 0000000..b56d090 --- /dev/null +++ b/src/game/schedule.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/schedule.hpp" +#include "formats/executable_layout.hpp" +#include "formats/le.hpp" + +#include +#include + +namespace bmh { + +namespace { + +// Fixture content belongs to the selected installation. Explicit callers install +// the loaded tables before scheduling; no copied or generated fallback is used. +FixtureTableCache fixture_tables; + +const char* round_string(int teams, int round) { + const auto table = fixture_tables.find(teams); + if (table == fixture_tables.end()) + throw std::invalid_argument("fixture table is not installed for this league size"); + if (round < 1 || size_t(round) > table->second.size()) + throw std::out_of_range("fixture round out of range"); + return table->second[size_t(round - 1)].c_str(); +} + +} // namespace + +void set_fixture_tables(FixtureTableCache tables) { + if (tables.empty()) throw std::invalid_argument("fixture tables are empty"); + for (const auto& [teams, rounds] : tables) { + if (teams != 4 && teams != 6 && teams != 12 && teams != 16 && teams != 18 && teams != 20) + throw std::invalid_argument("unsupported fixture table size"); + if (rounds.size() != size_t(teams - 1)) + throw std::invalid_argument("fixture table has an invalid round count"); + for (const auto& round : rounds) { + if (round.size() != size_t(teams)) + throw std::invalid_argument("fixture round has an invalid length"); + uint32_t seen = 0; + for (unsigned char ch : round) { + const int team = int(ch) - 'a'; + if (team < 0 || team >= teams || (seen & (uint32_t(1) << team))) + throw std::invalid_argument("fixture round has an invalid or duplicate team"); + seen |= uint32_t(1) << team; + } + } + } + fixture_tables.swap(tables); +} + +void install_fixture_tables(const LeImage& exe) { + struct Binding { int teams; uint32_t table; }; + static constexpr Binding german[] = { + {4, layout::CareerSession_RuntimeError_RuntimeField}, + {6, layout::CareerSession_RuntimeError_RuntimeField2}, + {12, layout::CareerSession_RuntimeError_RuntimeField3}, + {16, layout::CareerSession_RuntimeError_ExecutableField3}, + {18, layout::CareerSession_RuntimeError_ExecutableField}, + {20, layout::CareerSession_RuntimeError_ExecutableField2}, + }; + static constexpr Binding english[] = { + {4, layout::EnglishFourTeamFixtureTable}, + {6, layout::EnglishSixTeamFixtureTable}, + {12, layout::EnglishTwelveTeamFixtureTable}, + {20, layout::EnglishTwentyTeamFixtureTable}, + }; + FixtureTableCache tables; + const auto read = [&](const auto& bindings) { + for (const auto& [teams, table] : bindings) { + if (!exe.contains(table) || !exe.contains(table + uint32_t(teams * 4 - 1))) + throw std::invalid_argument("fixture pointer table is outside the loaded image"); + const uint32_t empty = exe.u32(table); + if (!exe.contains(empty) || exe.u8(empty) != 0) + throw std::invalid_argument("fixture table has no empty initial round"); + auto& rounds = tables[teams]; + for (int round = 1; round < teams; ++round) { + const uint32_t at = exe.u32(table + uint32_t(round * 4)); + if (!exe.contains(at) || uint64_t(at) + uint64_t(teams) >= uint64_t(exe.base()) + exe.size()) + throw std::invalid_argument("fixture round is outside the loaded image"); + if (exe.u8(at + uint32_t(teams)) != 0) + throw std::invalid_argument("fixture round has no terminating NUL"); + std::string text; + for (int i = 0; i < teams; ++i) text.push_back(char(exe.u8(at + uint32_t(i)))); + rounds.push_back(std::move(text)); + } + } + }; + if (exe.u8(layout::LeagueSizes) == 20) read(english); + else read(german); + set_fixture_tables(std::move(tables)); +} + +int league_first_team(int league) { + int first = 0; + for (int l = 0; l < league; l++) first += kLeagueSizes[l]; + return first; +} + +int team_league(int team) { + int end = 0; + for (int l = 0; l < kLeagueCount; l++) { + end += kLeagueSizes[l]; + if (team < end) return l; + } + return kLeagueCount; +} + +std::vector generate_fixtures(int teams, int matchday, int rounds, int first_team) { + // GenerateFixtures: reduce the matchday into the first half, toggling home/away for every + // half season that is skipped. + bool swap = false; + while (matchday > rounds) { + matchday -= rounds; + swap = !swap; + } + const char* s = round_string(teams, matchday); + std::vector out; + // The original loops (rounds + 1) / 2 times, which equals teams / 2 for a full league. + for (int m = 0; m < (rounds + 1) / 2; m++) { + int a = s[2 * m] - 'a', b = s[2 * m + 1] - 'a'; + if (swap) std::swap(a, b); + out.push_back({first_team + a, first_team + b}); + } + return out; +} + +int league_table_teams(int league) { return league < 5 ? kLeagueSizes[0] : kLeagueSizes[5]; } + +void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]) { + int total = 0; + for (int l = 0; l < kLeagueCount; l++) total += sizes[l]; + const auto has_table = [](int teams) { return teams == 20 || teams == 18 || teams == 16 || teams == 12; }; + if (total != 138 || !has_table(sizes[0]) || !has_table(sizes[5])) + throw std::invalid_argument("league sizes do not describe 138 league teams with fixture tables"); + for (int l = 0; l < kLeagueCount; l++) + if (sizes[l] < 2 || sizes[l] > (l < 5 ? sizes[0] : sizes[5])) + throw std::invalid_argument("a league is larger than its fixture table"); + for (int l = 0; l < kLeagueCount; l++) kLeagueSizes[l] = sizes[l]; +} + +void set_league_groups(const uint8_t (&first)[8], const uint8_t (&count)[8]) { + uint8_t bit[kLeagueCount]; + for (int l = 0; l < kLeagueCount; l++) bit[l] = 0xff; + for (int b = 0; b < 8; b++) { + if (first[b] + count[b] > kLeagueCount) throw std::invalid_argument("calendar groups outside the leagues"); + // (bits 4-7 are the four international leagues, all on calendar bit 4) + for (int l = first[b]; l < first[b] + count[b]; l++) bit[l] = uint8_t(b < 4 ? b : 4); + } + for (int b = 0; b < 8; b++) kGroupLeague[b] = first[b], kGroupLeagues[b] = count[b]; + for (int l = 0; l < kLeagueCount; l++) kLeagueBit[l] = bit[l]; +} + +std::vector league_fixtures(int league, int matchday) { + const int teams = kLeagueSizes[league]; + return generate_fixtures(league_table_teams(league), matchday, teams - 1, league_first_team(league)); +} + +} // namespace bmh diff --git a/src/game/schedule.hpp b/src/game/schedule.hpp new file mode 100644 index 0000000..49bb103 --- /dev/null +++ b/src/game/schedule.hpp @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// League fixtures and results. +// +// Team ids +// Every club has an index into all per-club tables (names, stadiums, squads, ...). +// Leagues are contiguous ranges of these ids: league 0 is ids 0..17, league 1 the next +// 18 ids and so on (sizes in kLeagueSizes, LeagueSizes; team -> league is +// TeamLeague2). When a new game starts the clubs of a league are shuffled by swapping +// all their table entries (swap function around 0x685xx), so a team's position inside +// its league is its "draw position" for the fixture list. The master database order is +// therefore NOT the order used by a running game; always take names from the savegame. +// +// Fixtures (GenerateFixtures) +// The fixture list is not stored. For each league size there is a fixed table of +// "round strings" loaded from the executable: round r of the first half of the season is a +// string of letters, each consecutive pair "xy" is one match, home team = draw position +// x - 'a', away team = y - 'a'. The second half repeats the rounds with home and away +// swapped, and so on for leagues that play more than twice (the round index wraps). +// +// Results (block LeagueResults, 0xD5C bytes) +// results[league * 380 + (matchday - 1) * 10 + match] = home_goals << 4 | away_goals +// Room for 9 leagues x 38 matchdays x 10 matches. 0xCC marks a match not yet played +// (the whole block is filled with 0xCC at season start, FUN at layout field in the dump); +// the code also tests (value & 0xCF) against 0xCC/0xCD/0xCE for postponed matches. + +#include +#include +#include +#include + +namespace bmh { + +class LeImage; +// Round strings are installation content. Sparse authored caches are supported +// for isolated callers; real sessions install the tables from their executable. +using FixtureTableCache = std::map>; +// Validates every supplied table before replacing the current cache. Throws +// std::invalid_argument for malformed rows, team ids, sizes or round counts. +void set_fixture_tables(FixtureTableCache tables); +void install_fixture_tables(const LeImage& exe); + +// Number of teams per league, LeagueSizes of the loaded game: the German versions have 5 +// leagues of 18 and 4 of 12; the English Football Limited 20 20 20 20 10 and the same four +// international leagues of 12 (both 138 league teams, so the squad layout is the same). +// The German sizes are the default; set_league_sizes() installs those of the loaded game +// (app::CareerSession does it from the EXE table). One game per process. +constexpr int kLeagueCount = 9; +inline uint8_t kLeagueSizes[kLeagueCount] = {18, 18, 18, 18, 18, 12, 12, 12, 12}; +// Installs the league sizes of the loaded game; throws std::invalid_argument unless they +// add up to 138 (the league teams of every version) and every league has a fixture table (20, 18, 16, 12 or 10 teams). +void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]); + +// The calendar groups of the loaded game: competition bits 0-7 play the leagues +// kGroupLeague[bit] .. + kGroupLeagues[bit] - 1 (CalendarFirstLeague / CalendarLeagueCounts), and a league +// plays on calendar bit kLeagueBit[league] (LeagueCalendarBits). German: 3. Liga A and B share +// bit 2; English: every division has its own bit and the 10-team fifth league none (0xff +// in kLeagueBit, not played). Set with the league sizes from the EXE tables. +inline uint8_t kGroupLeague[8] = {0, 1, 2, 4, 5, 6, 7, 8}; +inline uint8_t kGroupLeagues[8] = {1, 1, 2, 1, 1, 1, 1, 1}; +inline uint8_t kLeagueBit[kLeagueCount] = {0, 1, 2, 2, 3, 4, 4, 4, 4}; +void set_league_groups(const uint8_t (&first)[8], const uint8_t (&count)[8]); + +// The promotion ladder of the loaded game (Void / English ClubName), set with +// the league sizes from the EXE tables: +// - kLeagueRelegation[league]: relegation places (CareerSession_InstallLeagueSizes_RuntimeField2; German 3 4 2 2 3, English +// 4 4 4 4 4), +// - kGroupBelow[group] .. + kGroupBelowCount[group] - 1: the league(s) a promotion group +// takes its promoted clubs from (CareerSession_InstallLeagueSizes_RuntimeField5 / CareerSession_InstallLeagueSizes_RuntimeField4; German 1 | 2 | 4 with the +// two Regionalligen in one group, English 1 | 2 | 3), +// - kLeagueSuffix[league]: the letter after a league's name (CareerSession_InstallLeagueSizes_RuntimeField3, two bytes per +// league; German A/B for the Regionalligen, English none), +// - kNewcomerFirst / kNewcomerCount: the clubs the lowest league is refilled from +// (CareerSession_DispatchLineup_RuntimeField / CareerSession_InstallLeagueSizes_RuntimeField6; German the 30 amateur clubs 138-167; the English game +// draws from its 12 further English clubs 138-149 - its later ids have no name - so the +// session counts only named clubs). +inline uint8_t kLeagueRelegation[kLeagueCount] = {3, 4, 2, 2, 3, 0, 0, 0, 0}; +// European places per league for the table prediction (CareerSession_InstallLeagueSizes_RuntimeField; German 0 3 2 2 4 - league +// 0 uses 4 in the prediction -, English 0 4 4 4 4) +inline uint8_t kLeagueEurope[kLeagueCount] = {0, 3, 2, 2, 4, 0, 0, 0, 0}; +inline uint8_t kGroupBelow[8] = {1, 2, 4, 5, 6, 7, 8, 0}; +inline uint8_t kGroupBelowCount[8] = {1, 2, 1, 1, 1, 1, 1, 0}; +inline char kLeagueSuffix[kLeagueCount] = {0, 0, 'A', 'B', 0, 0, 0, 0, 0}; +inline int kNewcomerFirst = 0x8a, kNewcomerCount = 0x1e; + +// The English competition structure (Football Limited): an FA Cup of 68 clubs with a +// qualifying stage (cup entries 0 and 28) and a League Cup (entries 25-27). Its cup memory +// lies partly in blocks of its own (career.hpp, english_competition_blocks). Set with the +// league sizes: a first league of 20 clubs is the English structure. +inline bool kEnglishCompetitions = false; + +// First team id of a league (sum of the sizes of all previous leagues). +int league_first_team(int league); +// League of a team id, or kLeagueCount for teams outside league play (TeamLeague2). +int team_league(int team); +// The round-string table a league plays with (its team count): the original points leagues +// 0-4 at the table of the first league and 5-8 at the 12-team table (DE CareerFirstSteps2, EN +// LeagueTableTeams). The same as the league size except for the English fifth league (10 teams), +// which belongs to no calendar group and is never played. +int league_table_teams(int league); + +struct Fixture { + int home; // team id + int away; // team id +}; + +// Matches of a league matchday (1-based), home/away as team ids. `rounds` is the number of +// rounds per half season, normally team count - 1 (the original passes matchdays / 2). +std::vector league_fixtures(int league, int matchday); + +// Raw fixture generator, a direct port of GenerateFixtures: +// teams - league size, selects the round-string table +// matchday - 1-based +// rounds - rounds per half season (normally teams - 1) +// first_team - id of the league's first team, added to every draw position +std::vector generate_fixtures(int teams, int matchday, int rounds, int first_team); + +constexpr uint8_t kNotPlayed = 0xCC; +constexpr size_t kResultsSize = 0xD5C; + +struct Result { + bool played = false; + int home_goals = 0; + int away_goals = 0; +}; + +// Decodes one result byte of block LeagueResults. +inline Result decode_result(uint8_t v) { + if ((v & 0xCF) >= 0xCC) return {}; + return {true, v >> 4, v & 0x0F}; +} + +// Index into the results block for a league match. +inline size_t result_index(int league, int matchday, int match) { + return size_t(league) * 0x17C + size_t(matchday - 1) * 10 + size_t(match); +} + +} // namespace bmh diff --git a/src/game/season.cpp b/src/game/season.cpp new file mode 100644 index 0000000..7bef5ec --- /dev/null +++ b/src/game/season.cpp @@ -0,0 +1,1689 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/season.hpp" + +#include +#include +#include +#include +#include + +#include "game/career.hpp" +#include "game/matchday.hpp" +#include "game/month.hpp" +#include "game/national.hpp" +#include "game/cup.hpp" +#include "game/lineup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "game/messages.hpp" +#include "game/prediction.hpp" +#include "game/week.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +namespace { + +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes +constexpr uint32_t kListEntry = 0x58; +constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField +constexpr uint32_t kOffers = ::bmh::layout::OfferSlots; // OfferSlots: 4 offers, -1 = free +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; + +uint32_t board32(const GameState& g, size_t at) { + return uint32_t(g.tactics.at(at) | g.tactics.at(at + 1) << 8 | g.tactics.at(at + 2) << 16) | + uint32_t(g.tactics.at(at + 3)) << 24; +} + +} // namespace + +void answer_offers(GameState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report, GameRandom* game) { + StaticMemory& mem = g.memory; + const int team = g.manager_teams.at(size_t(manager)); + const SquadRange range = squad_range(team); + for (uint32_t k = 0; k < 4; k++) { + const uint32_t offer = mem.u32(kOffers + k * 4); + if (offer == 0xFFFFFFFFu || int(offer & 0x1f) != manager) continue; + const int player = int(offer >> 10) & 0xFFF; + size_t slot = range.first; + while (slot < range.first + range.count && (g.squad_slots.at(slot) & 0xFFF) != player) slot++; + if (slot != range.first + range.count) { + const uint32_t e = kTransferList + (0x28 + k) * kListEntry; + const size_t board = size_t(manager) * kBoard + (slot - range.first) * kBoardSlot; + if (!(offer & 0x80000000u)) { + if (!game) { + report.fail("an offer for a player: the transfer (IncomingTransferScreen)"); + return; + } + // Opening the negotiation restarts the game generator and picks the negotiator. + game->set_seed(int32_t(mem.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + game->range(0x5c, 0x6c); + // The fee offer is decided on its own (GameState::transfer_decision); `accept` + // answers the salary demands below. Without a controller the manager refuses + // the release, as in all recordings of the original. + const int offered_by = int16_t(mem.u16(e)); + const bool sell = g.transfer_decision && + g.transfer_decision(g, manager, player, offered_by, int32_t(mem.u32(e + 0x1c)), + int32_t(mem.u32(e + 0x0c))); + if (sell) { + const int buyer = offered_by; + if (buyer >= 0) { + const SquadRange target = squad_range(buyer); + size_t free = target.first; + while (free < target.first + target.count && g.squad_slots.at(free) != 0x0fff) free++; + if (free < target.first + target.count) { + if (!remove_from_seller(g, team, player, report)) return; + g.squad_slots.at(free) = uint16_t(player); + book_money(g, manager, -int32_t(mem.u32(e + 0x1c)), true, true); + lineup_after_transfer(g, team); + lineup_after_transfer(g, buyer); + } + } + } + g.squad_slots.at(kPoolSlots + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + continue; + } + // " fordert ein Gehalt von X EU - sonst nutzt er seine Ausstiegsklausel!" + if (!accept) { + if (!game) { + report.fail("a salary demand declined: the player leaves (IncomingTransferScreen)"); + return; + } + // "NEIN": IncomingTransferScreen opens the negotiation ("Entscheidung") like for a fee + // offer - the game generator restarts, the negotiator is drawn - and the + // manager refuses the release (right click): the offer is gone, the player + // stays (confirmed by the game 1 and 2P recordings against the original) + game->set_seed(int32_t(mem.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2))); + game->range(0x5c, 0x6c); + g.squad_slots.at(kPoolSlots + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + continue; + } + if (!(offer & 0x20)) { + // the new salary and its percentage of the market salary (AddToSquad with + // 98 % and the contract years left) + uint32_t fee = 0, salary = 0; + market_value(g, int(slot), 0, 0x62, fee, salary, (g.tactics.at(board + 0xc) + 6) / 0xc, 0, rand); + const uint32_t offered = mem.u32(e + 0xc); + for (int i = 0; i < 4; i++) g.tactics.at(board + 0x50 + size_t(i)) = uint8_t(offered >> (8 * i)); + // Deliberate deviation (#40): the original stores the percentage in the mood + // byte without a limit, so a raise to more than 255 % of the market salary + // (a rival's offer against few months left) wraps it to almost 0 - the player + // then asks for next to nothing at his renewal (60.900 -> 8.500 in the QA). + // Purchase and renewal clamp the same byte to 255; here too. + g.tactics.at(board + 0xd) = uint8_t(std::min(offered * 100 / salary, 0xff)); + } + } + g.squad_slots.at(kPoolSlots + 0x28 + k) = 0x0FFF; + mem.set32(kOffers + k * 4, 0xFFFFFFFFu); + } + (void)board32; +} + +void free_offer_slots(GameState& g) { + for (size_t k = 0; k < 4; k++) g.squad_slots.at(kPoolSlots + 0x28 + k) = 0x0FFF; + for (uint32_t k = 0; k < 4; k++) g.memory.set32(kOffers + k * 4, 0xFFFFFFFFu); +} + +void reset_club_moods(GameState& g, GameRandom& game, WatcomRandom& rand, bool new_career) { + const StaticMemory& mem = g.memory; + // the title holders (cup table entries 0, 15, 19 and 21, +0x22) start at the top + const uint16_t holders[4] = {mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6), mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5)}; + rand.range(0, 2); // local_18, a counter that is not used + for (size_t team = 0; team < g.team_flags.size(); team++) { + g.team_morale.at(team) = uint8_t((g.team_morale.at(team) & 0xc0) | rand.range(0x14, 0x1e)); + g.team_flags.at(team) = uint16_t(game.range(0, 2) * 2); + int high = 3, low = 0; // iVar7 (bits 14-15), iVar8 (bits 12-13) + if (new_career) { + high = 1, low = 1; // their initial values, never changed in this mode + } else if (std::find(std::begin(holders), std::end(holders), uint16_t(team)) == std::end(holders)) { + const int pos = int16_t(table_position(g, int(team))); // TablePosition + high = std::max(3 - pos / 6, 0); + if (rand.range(0, 4) == 0) high = rand.range(0, 3); + low = std::min(pos / 5, 3); + if (rand.range(0, 6) == 0) low = rand.range(0, 3); + } + g.team_flags.at(team) = uint16_t(g.team_flags.at(team) | low << 12 | high << 14); + club_balance(g, int(team), rand); // CareerSeasonSetup4 + } +} + +void club_balance(GameState& g, int team, WatcomRandom& rand) { + // condition against technique of the whole squad, defence against attack, each shaken a + // little and cut to 51..149 %, give bits 8-9 and 10-11 of the club flags + const int a1 = team_average(g, team, 0xf1, &rand).value; + const int a2 = team_average(g, team, 0xf2, &rand).value; + const int a3 = team_average(g, team, 0x2f, &rand).value; + const int a4 = team_average(g, team, 0x8f, &rand).value; + uint32_t c = uint32_t(a1 * 100) / uint32_t(a2); + uint32_t d = uint32_t(a3 * 100) / uint32_t(a4); + c = (c & 0xffff) - uint32_t(int(c & 0xffff) / rand.range(2, 7)); + d = uint32_t(int(d & 0xffff) / rand.range(2, 6)) + (d & 0xffff); + const int cc = std::clamp(int(int16_t(c)), 0x33, 0x95); // ClampInteger + const int dd = std::clamp(int(int16_t(d)), 0x33, 0x95); + uint16_t f = uint16_t(g.team_flags.at(size_t(team)) & 0xf0ff); + f = uint16_t(f | ((cc - 0x32) / 0x19) << 8 | ((dd - 0x32) / 0x19) << 10); + g.team_flags.at(size_t(team)) = f; +} + +namespace { + +// TeamLeague2: the league of a club; ids above 0x164 (national teams) count as league 0 +int club_league(int team) { return team > 0x164 ? 0 : team_league(team); } + +// The European entrants (Career_CompetitionPointersEnglish_ExecutableField25 UEFA Cup, Career_CompetitionPointersEnglish_RuntimeField14 Champions League, +// Career_CompetitionPointersEnglish_ExecutableField19 Cup Winners' Cup) and their counts (Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3). +struct Entrants { + StaticMemory& mem; + static constexpr uint32_t kList[3] = {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}; + static constexpr uint32_t kCount[3] = {::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3}; + // EuropeanClub: 1 UEFA Cup, 2 Champions League, 3 Cup Winners' Cup, 0 none + int find(int team) const { + for (int l = 0; l < 3; l++) + for (int i = 0; i < int(int8_t(mem.u8(kCount[l]))); i++) + if (mem.u16(kList[l] + uint32_t(i) * 2) == uint16_t(team)) return l + 1; + return 0; + } + void add(int l, int team) { + const int n = int8_t(mem.u8(kCount[l])); + mem.set16(kList[l] + uint32_t(n) * 2, uint16_t(team)); + mem.set8(kCount[l], uint8_t(n + 1)); + } +}; + +// OnTableJust(league, rank, ranks): the club with that final rank (0 if none) +int club_at_rank(int league, int rank, const uint8_t* ranks) { + for (int i = 0; i < kLeagueSizes[league]; i++) + if (ranks[i] == rank) return league_first_team(league) + i; + return 0; +} + +// LeagueEntrants(league, cup winner, cup finalist, uefa places): the European places of a +// league - its champion (and the Champions League holder if he plays there, else the +// runner-up), the cup winner (or the finalist) and the cup winners' cup holder, the UEFA +// Cup holder and `uefa` more clubs by rank. Human managers note where they play. +void league_entrants(GameState& g, int league, int winner, int finalist, int uefa) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + const LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, 1); + uint8_t ranks[24] = {}; + for (int i = 0; i < t.size; i++) ranks[i] = uint8_t(t.rank(i)); + en.add(1, club_at_rank(league, 0, ranks)); + const int cl_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5); + if (club_league(cl_holder) == league) en.add(1, en.find(cl_holder) == 0 ? cl_holder : club_at_rank(league, 1, ranks)); + if (en.find(winner) == 0) en.add(2, winner); + else if (en.find(finalist) == 0) en.add(2, finalist); + const int cw_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6); + if (club_league(cw_holder) == league) { + if (en.find(cw_holder) == 0) en.add(2, cw_holder); + else if (en.find(finalist) == 0) en.add(2, finalist); + } + const int uefa_holder = mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4); + if (club_league(uefa_holder) == league) { + if (en.find(uefa_holder) == 0) en.add(0, uefa_holder); + else uefa++; + } + for (int rank = 1; uefa != 0; rank++) { + const int team = club_at_rank(league, rank, ranks); + if (en.find(team) == 0) { + en.add(0, team); + uefa--; + } + } + static const uint8_t kRound[3] = {1, 3, 2}; // SeasonRuntimeField + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const int kind = en.find(g.manager_teams[m]); + if (kind == 0) continue; + // ManagerOf(manager, 2, ...): the European campaign of this season + const size_t at = m * 0xB0C + 0xda + 2 + size_t(std::min(g.season, 0x31)) * 3; + g.manager_records.at(at) = uint8_t(kRound[kind - 1] + (kind - 1) * 0x20); + } +} + +// CareerSeasonSetup(1) up to the German entrants: the cup tables restart, the international +// tournament of the year (competition 7 - season % 4, national teams from id 357) is drawn +// and the European entrants are found (SeasonEntrantsFromGame). +void observe_initial_international_groups(GameState& g, WatcomRandom& rand, int competition, + const SeasonCupDrawHook& hook) { + StaticMemory& mem = g.memory; + const int first = find_cup(mem, competition); + int group_ordinal = 0; + for (int index = first; index >= 0;) { + const uint32_t entry = cup_entry_address(index); + SeasonCupDrawEvent event; + event.entry_address = entry; + event.competition = competition; + event.flags = mem.u8(entry + 0x14); + event.group_stage = (event.flags & 4) == 0; + event.group_index = group_ordinal; + event.group_count = mem.u8(entry + 0x1e) & 0xf; + event.round = cup_round(mem, index); + event.offset = 0; + event.count = mem.u8(entry + 0x1a); + const uint32_t list = mem.pointer(entry); + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) event.participants.push_back(mem.u16(list + uint32_t(i) * 2)); + event.phase = SeasonCupDrawPhase::draw; + if (hook) hook(g, event); + event.phase = SeasonCupDrawPhase::overview; + cup_group_overview_effects(g, event.group_index); + if(event.group_stage) { + const int schedule_teams=cup_group_schedule_teams(mem,entry); + const int rounds=mem.u8(entry+0x1b)/((event.flags&1)+1); + const uint32_t teams=mem.pointer(entry); + for(const Fixture& fixture:generate_fixtures(schedule_teams,event.round+1,rounds,0)) { + for(int position:{fixture.home,fixture.away}) { + const int team=mem.u16(teams+uint32_t(position)*2); + const bool manager_national=mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField2)&&mem.has(::bmh::layout::CupDraw_FormatError_RuntimeField3)&& + mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField2)==0x165&&mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)==team; + const bool human_owned=g.manager_of(team)>=0||manager_national; + if(team<168||team==kNoTeam||!human_owned)continue; + SeasonCupDrawEvent::GroupAverageSnapshot snapshot; + snapshot.runtime_id=uint16_t(team); + snapshot.values={team_average(g,team,0x0f1,&rand).value, + team_average(g,team,0x0f2,&rand).value, + team_average(g,team,0x0f4,&rand).value, + team_average(g,team,0x0f8,&rand).value, + team_average(g,team,0x0ff,&rand).value}; + event.group_average_snapshots.push_back(snapshot); + } + } + } + if (hook) hook(g, event); + if (int8_t(mem.u8(entry + 0x17)) == 0) break; + ++index; // CupDrawFromGame advances to the adjacent 0x28-byte record + ++group_ordinal; + } +} + +void european_setup(GameState& g, GameRandom& game, WatcomRandom& rand, const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + for (uint32_t i = 0; i < 0x24; i++) mem.set8(::bmh::layout::MatchdaySetup_IndoorTournamentReset_RuntimeField + i * 0x28, 0); // played counters + const std::pair blocks[8] = {{::bmh::layout::Career_CompetitionPointers_ExecutableField, 0x7e}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22, 0x80}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23, 0x80}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17, 0x9a}, + {::bmh::layout::Savestate_Layout_ExecutableField4, 0x62}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26, 0x40}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21, 0x40}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13, 0x68}}; + for (const auto& [at, size] : blocks) + for (uint32_t i = 0; i < size; i++) + if (mem.has(at + i)) mem.set8(at + i, 0xcc); + if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc); + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (size_t i = 0; i < 2; i++) g.manager_records.at(m * 0xB0C + 0xdb + size_t(g.season) * 3 + i) = 0; + // the international tournament: its host (or last winner and finalist) and more teams + // drawn from four pools, none twice and none of the last field + static const uint8_t kPoolFixed[16] = {2, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 10, 4, 8, 0}; // SeasonRuntimeField2 + static const uint8_t kField[4] = {4, 8, 6, 24}; // SeasonRuntimeField3 + static const uint8_t kPoolFrom[4] = {0x00, 0x0f, 0x20, 0x2f}; // SeasonRuntimeField4 + static const uint8_t kPoolTo[4] = {0x0f, 0x20, 0x2f, 0x3e}; // SeasonRuntimeField5 + constexpr uint32_t kField0 = ::bmh::layout::Field0; + if (!mem.has(kField0)) mem.add_block(kField0, 0x30); + const int s = g.season % 4; + const int base = 0xbd + 0x8a + 0x1e; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + int n = 1; + std::vector last; + if (s % 2 == 0) { + mem.set16(kField0, uint16_t(base)); + } else { + const uint32_t e = cup_entry_address(0xe - s / 2); + const int count = mem.u8(e + 0x1a); + for (int i = 0; i < count; i++) last.push_back(mem.u16(kField0 + uint32_t(i) * 2)); + mem.set16(kField0, mem.u16(e + 0x22)); + if (mem.u8(e + 0x1f) == 2) mem.set16(kField0 + 2, mem.u16(e + 0x24)), n = 2; + } + for (int k = 0; k < 4; k++) { + const int fixed = kPoolFixed[k + s * 4]; + int left = fixed != 0 ? rand.range(fixed - 2, fixed) : kField[s] - n; + while (int16_t(left) != 0) { + const uint16_t t = uint16_t(rand.range(base + kPoolFrom[k], kPoolTo[k] + base - 1)); + mem.set16(kField0 + uint32_t(n) * 2, t); + bool twice = false; + for (int i = 0; i < n && !twice; i++) twice = mem.u16(kField0 + uint32_t(i) * 2) == t; + if (!twice && std::find(last.begin(), last.end(), t) == last.end()) n++, left--; + } + } + for (uint32_t i = 0; i < kField[s]; i++) { // PrepareEvent + const uint32_t j = uint32_t(game.range(0, kField[s] - 1)); + const uint16_t a = mem.u16(kField0 + i * 2); + mem.set16(kField0 + i * 2, mem.u16(kField0 + j * 2)); + mem.set16(kField0 + j * 2, a); + } + // CupDrawFromGame(entry of competition 7 - s): the draw of the tournament's first round, + // shown unless switched off + const int shown_type = 7 - s; + if (mem.u8(::bmh::layout::LeaguePresentationOptions + uint32_t(shown_type + 5) * 9) == 0) + observe_initial_international_groups(g, rand, shown_type, cup_draw); + // SeasonEntrantsFromGame: the entrants of the first division (cup winner and finalist) and of + // the four foreign leagues (two random clubs), then the holders not placed yet + Entrants en{mem}; + mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField, 0), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField3, 0), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField2, 0); + static const uint8_t kLeague[5] = {0, 5, 6, 7, 8}; // SeasonRuntimeField6 + static const uint8_t kUefa[5] = {4, 4, 4, 4, 3}; // SeasonRuntimeField7 + for (int u = 0; u < 5; u++) { + int a = 0, b = 0; + if (u == 0) { + // the national cup winner and finalist (+0x22/+0x24): entry 0, in the English + // structure the FA Cup proper, entry 28 (U16: SeasonRuntimeField8/83c) + const uint32_t cup = kEnglishCompetitions ? ::bmh::layout::CupTable + 28 * 0x28 : ::bmh::layout::CupTable; + a = mem.u16(cup + 0x22), b = mem.u16(cup + 0x24); + if (mem.has(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7)) mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7, uint16_t(a)); + } else { + a = rand.range(0, kLeagueSizes[kLeague[u]] - 1); + do b = rand.range(0, kLeagueSizes[kLeague[u]] - 1); while (b == a); + } + const int first = kLeague[u] == 0 ? 0 : league_first_team(kLeague[u]); + league_entrants(g, kLeague[u], uint8_t(a + first), uint8_t(b + first), kUefa[u]); + } + const int holders[3][2] = {{0, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4)}, {1, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5)}, {2, mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6)}}; + for (const auto& h : holders) + if (en.find(h[1]) == 0) en.add(h[0], h[1]); + // CompetitionWinnerScreen(1, 2..4, list, count): the German clubs in each competition are shown + // (the first pause of the recording) +} + +// The rest of CareerSeasonSetup(1): the three European fields are filled up with foreign +// clubs (from id 168 on, one of every block of seven, none twice), shuffled +// (PrepareEvent) and their first rounds shown (CupDrawFromGame, no draws while switched off): +// Cup Winners' Cup to SeasonRuntimeField9 (32), Champions League to 24, UEFA Cup to +// SeasonRuntimeField10 (64, two per block after the first 16 blocks). +void european_fields(GameState& g, GameRandom& game, WatcomRandom& rand) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + const int pool = 0x8a + 0x1e; // CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6: the first foreign club + auto pick = [&](int from) { + int t; + do t = rand.range(from, from + 6); while (en.find(t) != 0); + return t; + }; + auto shuffle = [&](uint32_t list, int n) { // PrepareEvent + for (uint32_t i = 0; i < uint32_t(n); i++) { + const uint32_t j = uint32_t(game.range(0, n - 1)); + const uint16_t a = mem.u16(list + i * 2); + mem.set16(list + i * 2, mem.u16(list + j * 2)); + mem.set16(list + j * 2, a); + } + }; + int from = pool; + for (int i = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField3)); i < 0x20; i++, from += 7) en.add(2, pick(from)); + shuffle(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, 0x20); + from = pool; + for (int i = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField2)); i < 0x18; i++, from += 7) en.add(1, pick(from)); + shuffle(mem.pointer(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5), 0x10); // (the team list of cup entry 16, Career_CompetitionPointersEnglish_ExecutableField5) + from = pool; + const int start = int8_t(mem.u8(::bmh::layout::Career_EuropeanClub_ExecutableField)); + int per = 2; + for (int i = start; i < 0x40; i++, from += 7) { + for (int k = 0; k < per; k++) en.add(0, pick(from)); + if (i - start == 0x10) per = 1; + } + shuffle(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, 0x40); + mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField, 0x40), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField2, 0x18), mem.set8(::bmh::layout::Career_EuropeanClub_ExecutableField3, 0x20); +} + +int32_t rec32(const GameState& g, int m, size_t o) { + const size_t at = size_t(m) * 0xB0C + o; + return int32_t(uint32_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8 | g.manager_records.at(at + 2) << 16) | + uint32_t(g.manager_records.at(at + 3)) << 24); +} +void set_rec32(GameState& g, int m, size_t o, int32_t v) { + for (size_t i = 0; i < 4; i++) g.manager_records.at(size_t(m) * 0xB0C + o + i) = uint8_t(uint32_t(v) >> (8 * i)); +} +uint8_t& rec8(GameState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * 0xB0C + o); } +uint16_t mem_u16(const GameState& g, uint32_t a) { return g.memory.u16(a); } + +// HighscoreScore(mask, 0, 0xff): bit 0 the account (+0x314), 1 the deposit (+0x318), 2 the +// fixed deposits (Advertising_OriginalShareAdjustment_RuntimeField x FundBlock), 3 the shares (block StockExchange), 4 the credits: with +// mask 0x10 alone what is still owed (Analytics_SourceAssetMaskE_RuntimeField - bd720), otherwise minus the amounts +int32_t assets(const GameState& g, int m, int mask) { + const StaticMemory& mem = g.memory; + int32_t sum = 0; + if (mask & 1) sum += rec32(g, m, 0x314); + if (mask & 2) sum += rec32(g, m, 0x318); + if (mask & 4) + for (uint32_t k = 0; k < 6; k++) + sum += int32_t(mem.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c) * mem.u32(::bmh::layout::FundBlock + k * 0x1c)); + if (mask & 8) + for (size_t k = 0; k < 12; k++) + sum += int32_t(uint32_t(g.stocks.at(k * 0x5c + 0x50 + size_t(m) * 2) | g.stocks.at(k * 0x5c + 0x51 + size_t(m) * 2) << 8) * + uint32_t(g.stocks.at(k * 0x5c + 0x4e) | g.stocks.at(k * 0x5c + 0x4f) << 8)); + if (mask & 0x10) + for (uint32_t b = 0; b < 5; b++) { + const uint32_t at = ::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + b * 0x18; + sum += mask == 0x10 ? int32_t(mem.u32(at) - mem.u32(at + 0x10)) : -int32_t(mem.u32(at)); + } + return sum; +} + +// ClubAttraction(club, pay): how popular a club is (0..100) - its European campaign, the +// championship and the cups it holds, its strength and position. With `pay` the +// manager (ActiveManager) gets the premiums for the titles (messages, record +0x874). +int club_popularity(GameState& g, int m, int team, bool pay) { + StaticMemory& mem = g.memory; + Entrants en{mem}; + static const uint8_t kKind[4] = {0, 1, 3, 2}; // SeasonRuntimeField11 + static const uint8_t kEntry[4] = {0x00, 0x0f, 0x13, 0x15}; // SeasonRuntimeField12 + static const uint8_t kPlus[4] = {0x14, 0x1e, 0x14, 0x0f}; // SeasonRuntimeField13 + static const int32_t kPremium[4] = {500000, 1500000, 2500000, 1500000}; // SeasonRuntimeField14 + int8_t p = int8_t(kKind[en.find(team)] * 10 + 10); + if (team == mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6)) { + if (pay) { + post_composed(g, m, kChampionshipBonusText); // ChampionshipBonusText + book_money(g, m, -700000, true); + set_rec32(g, m, 0x874, rec32(g, m, 0x874) + 1000000); + } + p = int8_t(p + 10); + } + for (int k = 0; k < 4; k++) { + if (team != mem.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField + uint32_t(kEntry[k]) * 0x28)) continue; + p = int8_t(p + kPlus[k]); + if (pay) { + post_composed(g, m, message_text(g, ::bmh::layout::Season_ClubPopularity_TextPointer) + message_text(g, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(k) * 4) + + message_text(g, ::bmh::layout::Season_ClubPopularity_TextPointer2) + format_amount(g, kPremium[k]) + "."); + book_money(g, m, -kPremium[k], true); + set_rec32(g, m, 0x874, rec32(g, m, 0x874) + kPremium[k]); + } + } + const int avg = team_average(g, team, 0xff).value; + int pos = int8_t(table_position(g, team)); + if (pos == -1) pos = 10; + int league = club_league(team); + if (int8_t(league) > 2) league--; + int v = int16_t((int(p) << 2) / 5) + int16_t(uint32_t(uint16_t((4 - int8_t(league)) * 0x16 + (0x14 - int8_t(pos)))) * 0x28 / 0x6c) + + int16_t(uint32_t(uint16_t(avg)) * 2 / 10); + return std::clamp(int(int16_t(v)), 0, 100); // ClampInteger +} + +// CareerSeasonSetup2(manager): the season tickets - popularity above the league's base plus +// W(0, 10) in steps of 300 on top of the base number (SeasonRuntimeField15), less 5 % per game +// level, sold at the league's price (SeasonRuntimeField16); record +0x2ac, +0x754, +0x868 +void season_tickets(GameState& g, int m, WatcomRandom& rand) { + static const uint8_t kBase[5] = {50, 40, 30, 30, 20}; // SeasonRuntimeField17 + static const uint16_t kTickets[5] = {5000, 2000, 1000, 1000, 300}; // SeasonRuntimeField15 + static const uint16_t kPrice[5] = {330, 270, 240, 240, 225}; // SeasonRuntimeField16 + const int team = g.manager_teams.at(size_t(m)); + const int league = std::min(club_league(team), 4); + const int pop = club_popularity(g, m, team, true); + const int low = std::max(pop - kBase[league], 0); + const int r = rand.range(low, low + 10); + const int sold = ((100 - g.level * 5) * (kTickets[league] + r * 300)) / 100; + g.manager_records.at(size_t(m) * 0xB0C + 0x2ac) = uint8_t(sold); + g.manager_records.at(size_t(m) * 0xB0C + 0x2ad) = uint8_t(sold >> 8); + const int32_t income = int32_t(kPrice[league]) * int16_t(sold); + book_money(g, m, -income, true); + set_rec32(g, m, 0x754, rec32(g, m, 0x754) + income); + set_rec32(g, m, 0x868, rec32(g, m, 0x868) + income); + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer) + format_number(g, int16_t(sold), 1) + message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer2) + + format_amount(g, income) + message_text(g, ::bmh::layout::Season_SeasonTickets_TextPointer3)); +} + +// SeasonEvent: a random event of the summer (a bonus, a fine, ...) for a manager whose +// finances went badly; otherwise only its draw is spent +void season_event(GameState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int32_t worth = assets(g, m, 0xf) - assets(g, m, 0x10) + game.range(500000, 1000000); + // Int64T: bankrupt, or out of credit + const uint8_t cut = rec8(g, m, 0x220); + const int32_t total = int32_t(rec8(g, m, 0x26f)) * 80000 + (assets(g, m, 0xf) - assets(g, m, 0x10)); + if (total < -6000000 || ((cut >> 5) == 2 && int32_t(cut & 0x1f) * 100000 <= rec32(g, m, 0x330))) return; + if (g.memory.u8(::bmh::layout::GameMode) < 3) set_rec32(g, m, 0x320, rec32(g, m, 0x314) - rec32(g, m, 0x324)); + bool poor = false; + int32_t w = worth; + if (rec32(g, m, 0x314) - rec32(g, m, 0x324) < rec32(g, m, 0x320) - 1000000) { + poor = true; + if (rec8(g, m, 0x26f) < 0x3c) w -= 1500000; + } + if ((!poor || rand.range(0, 1) == 0) && w + int32_t(rec8(g, m, 0x26f)) * 80000 > -3000001) return; + (void)report; + // The board's sanction (kind G(0, 3)): 0 and 2 last n weeks/points, 1 cuts the credit line + // to n * 100000, 3 is a fine paid at once. Ranges SeasonRuntimeField18 / SeasonRuntimeField19, factor + // SeasonRuntimeField20 (above 1: thousands of money). + static const int kMin[4] = {4, 8, 2, 4}, kMax[4] = {8, 15, 6, 10}, kFactor[4] = {1, 100, 1, 50}; + const int kind = game.range(0, 3); + std::string text = kind == 0 || kind == 3 ? message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer3) : std::string(); + int n = game.range(kMin[kind], kMax[kind]); + int32_t value = kFactor[kind] * n; + if (kFactor[kind] > 1) value *= 1000; + text += message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer + uint32_t(kind) * 4); // Season_SeasonEvent_TextPointer[kind] + // FormatNumber: the number (an amount of money for kinds 1 and 3), then Season_SeasonEvent_TextPointer2[kind] + text += format_number(g, value, kind == 1 || kind == 3 ? 0x101 : 1) + message_text(g, ::bmh::layout::Season_SeasonEvent_TextPointer2 + uint32_t(kind) * 4); + if (kind == 0) n--; + if (kind == 3) { + book_money(g, m, value, true, true); // FinanceStatisticsEnabled = 1: into the statistics + } else { + // Season_SeasonAccounts_RuntimeField[manager]: becomes the record's sanction byte +0x220 at the season change + if (!g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) g.memory.add_block(::bmh::layout::Season_SeasonAccounts_RuntimeField, 4); + g.memory.set8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m), uint8_t(n | (kind + 1) << 5)); + } + post_composed(g, m, text); // PostMessage +} + +} // namespace + +int32_t season_profit_tax(int32_t profit) { + // GameEndTaxAnimationScreen/SeasonProfitTax: six progressive bands. The original rounds the + // annual result to 100 EU before this point, divides each band by ten first, + // then multiplies by its 0..5 rate. Preserve that integer order. + if (profit <= 100000) return 0; + int32_t remaining = profit; + int32_t tax = 0; + for (int band = 0; band < 6 && remaining > 0; ++band) { + int32_t taxable = remaining; + if (band < 5 && taxable > 100000) taxable = 100000; + tax += (taxable / 10) * band; + remaining -= taxable; + } + return tax; +} + +int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit, + int32_t previous_tax_paid) { + if (profit >= 100000 || previous_taxable_profit <= 0 || previous_tax_paid <= 0 || + previous_taxable_profit / 100 == 0) + return 0; + // Keep GameEndTaxAnimationScreen's division and multiplication order. A malformed saved + // denominator is safely ignored; valid source values are rounded to 100 EU. + int32_t base = profit + previous_taxable_profit; + if (base < 200000) base = 200000; + int32_t retained_tax = (((previous_tax_paid / 100) * ((base - 200000) / 1000)) / + (previous_taxable_profit / 100)) * 1000; + if (retained_tax < 0) retained_tax = 0; + return std::max(previous_tax_paid - retained_tax, 0); +} + +void season_apply_profit_tax(GameState& g, int manager, int32_t profit, + GameRandom& game, WatcomRandom& rand, + const SeasonTaxHooks& hooks, SeasonTaxState* continuation) { + if (profit <= 100000) return; + SeasonTaxEvent event; + event.manager_slot = manager; + event.team = g.manager_teams.at(size_t(manager)); + event.profit = profit; + event.legal_tax = season_profit_tax(profit); + event.paid_tax = event.legal_tax; + event.fine = continuation ? continuation->carried_fine : 0; + // SystemIdentity is an acknowledgement, not PostMessage mailbox delivery. + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer) + format_amount(g, profit) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer2) + format_amount(g, event.legal_tax) + ")."; // SeasonRuntimeField21 + if (hooks.observe) hooks.observe(g, event); + event.kind = SeasonTaxEventKind::question; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer3); + const bool adjust = hooks.choose && hooks.choose(g, event); + if (adjust) { + event.caught = game.range(1, 10) >= 10; + event.animation_variant = event.caught ? 4 : rand.range(1, 3); + event.kind = SeasonTaxEventKind::animation; + event.text.clear(); + if (hooks.observe) hooks.observe(g, event); + if (!event.caught) { + event.paid_tax = int32_t(uint32_t(event.legal_tax) * uint32_t(game.range(6, 9))) / 10; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer6) + format_amount(g, event.legal_tax) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer7) + format_amount(g, event.paid_tax) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer8); + } else { + event.fine = rand.range(1, 3) * 100000; + if (continuation) continuation->carried_fine = event.fine; + event.text = message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer4) + format_amount(g, event.fine) + + message_text(g, ::bmh::layout::Season_SeasonApplyProfitTax_TextPointer5); + // Source SeasonRuntimeField22: the last ten competition-4 ratings of this manager. + for (size_t i = 0; i < 10; ++i) + g.manager_ratings.at(size_t(manager) * 0x3c + 0x28 + i) = 0; + rec8(g, manager, 0x26f) = uint8_t(std::clamp(int(rec8(g, manager, 0x26f)) - 10, 0, 100)); + } + event.kind = SeasonTaxEventKind::outcome; + if (hooks.observe) hooks.observe(g, event); + } + // Both Source carries describe the tax, while the forced debit includes the fine. + set_rec32(g, manager, 0x328, event.paid_tax); + set_rec32(g, manager, 0x32c, profit); + book_money(g, manager, event.paid_tax + event.fine, true); +} + +namespace { + +} // namespace + +// OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules. +// YouthAcademyPlayer(manager) with the supported rule profile patch (SeasonOperation2, SeasonOperation3, SeasonOperation4, +// SeasonOperation5): the youth academy's player at the season accounts. Only when the academy +// was paid in full this season (record +0x880 reached the league's price, TeamLeague3) and +// the squad has at most 22 players (SquadCount(team, 3)). A computer club's young player +// moves to the club: the slots 0x86f..0 of the big clubs are searched downwards (squads of +// human managers skipped) for a player not on loan whose age (years after 16) is at most +// G(t, t + 3), t starting at 15 and lowered by one for every pass that finds none. He leaves +// his club (ReleasePlayer), gets new values around a level of the club's league +// (GeneratePlayer with 0x3000: G(79, 95) first division, G(69, 85) second, G(49, 68) third, +// G(29, 48) below), a place in the squad with a fresh board entry (PendingOfferAnswer with the +// player id | 0xf000), mood 0x69 and an age of W(0, 4) (16..20). Returns whether a player +// came. The original's G(0, 0) before the search is kept. +bool youth_academy_player(GameState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + const int team = g.manager_teams.at(size_t(m)); + const int league = club_league(team); + const uint32_t price = league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000; + if (uint32_t(rec32(g, m, 0x880)) < price) return false; + if (squad_count(g, team, 3) > 0x16) return false; + const SquadRange own = squad_range(team); + if (game.range(0, 0) != 0) return false; + for (int t = 0xf;; --t) { + for (int s = 0x86f; s >= 0; --s) { + const int club = s / 24; + if (g.manager_of(slot_team(s)) >= 0) { + s -= 0x17; // the whole squad of a human manager + continue; + } + const int player = g.squad_slots.at(size_t(s)) & 0xfff; + if (player == 0xfff) continue; + bool loan = false; // BoughtEntry + for (int k = 0; k < 200 && !loan; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + loan = e != 0 && int(e & 0xfff) == player; + } + if (loan) continue; + const int age = int((g.players.at(size_t(player)).w364 >> 21) & 0x1f); + if (age > game.range(t, t + 3)) continue; + if (!remove_from_seller(g, club, player, report)) return false; + static const int kLevel[4][2] = {{0x4f, 0x5f}, {0x45, 0x55}, {0x31, 0x44}, {0x1d, 0x30}}; + const int band = league == 0 ? 0 : league == 1 ? 1 : league < 4 ? 2 : 3; + const int level = game.range(kLevel[band][0], kLevel[band][1]); + generate_player(g, player, level | 0x3000, game, rand); + // PendingOfferAnswer(manager, player | 0xf000, -1, squad start) + int slot = -1; + for (size_t q = own.first; q < own.first + 24 && slot < 0; q++) + if (g.squad_slots.at(q) == 0xfff) slot = int(q); + if (slot < 0) return false; // (the original shows PendingOffer_FormatError_ExecutableField) + g.squad_slots.at(size_t(slot)) = uint16_t(player); + new_board_entry(g, m, slot - int(own.first), slot, rand); + g.tactics.at(size_t(m) * 0x840 + size_t(slot - int(own.first)) * 0x58 + 0xd) = 0x69; + uint32_t& w = g.players.at(size_t(player)).w364; + w = (w & 0xff00ffffu) | uint32_t(uint8_t(rand.range(0, 4) << 5)) << 16; + return true; + } + if (t == 0) return false; + } +} + +namespace { + +// GameEndTaxAnimationScreen for one manager (SeasonProfitTax repeats it for the others): the summer +// event, the players' season bonuses, the championship mark, the new credit line from +// the season's result, taxes on a profit and refunds, then the season tickets +void season_accounts(GameState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const SeasonTaxHooks& tax_hooks, SeasonTaxState& tax_state) { + for (size_t i = 0; i < 0xc; i++) rec8(g, m, 0x754 + i) = 0; + if (!g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) g.memory.add_block(::bmh::layout::Season_SeasonAccounts_RuntimeField, 4); // (runtime only, not saved) + g.memory.set8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m), 0); + season_event(g, m, game, rand, report); + if (report.unsupported) return; + const int team = g.manager_teams.at(size_t(m)); + rec8(g, m, 0x21f) = 0; + if (g.manager_teams.size() > 1) rec8(g, m, 0x21c) = 0; + const int pos = int16_t(table_position(g, team)); + const int league = club_league(team); + const SquadRange range = squad_range(team); + for (size_t s = 0; s < 24; s++) + if (g.squad_slots.at(range.first + s) != 0x0FFF) season_bonus(g, m, int(s), uint8_t(pos), true); + // OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules. +// YouthAcademyPlayer: the youth academy's player (supported rule profile), posted as Season_SeasonAccounts_TextPointer + if (youth_academy_player(g, m, game, rand, report)) post_text(g, m, text_id(::bmh::layout::Season_SeasonAccounts_TextPointer)); + if (report.unsupported) return; + if (league == 0 && pos < 100) rec8(g, m, 0x21c) = 1; // the best human club of the first division + set_rec32(g, m, 0x324, rec32(g, m, 0x324) + rec32(g, m, 0x30c)); + set_rec32(g, m, 0x30c, 0); + const int32_t result = ((rec32(g, m, 0x314) - rec32(g, m, 0x324)) / 100) * 100; + const int32_t before = rec32(g, m, 0x320); + const int16_t step = int16_t(int64_t(std::abs(result - before)) / 200000); + int16_t credit = 0; + if (result < 0 && result + 1000000 + (10 - g.level) * 100000 < before) credit = int16_t(-step); + if (result > 0 && std::abs(result + 800000 - before) < 1500000) credit = int16_t(result / 250000 - step); + credit = int16_t(std::clamp(int(int16_t(credit + rec8(g, m, 0x26f))), 0, 100)); + set_rec32(g, m, 0x31c, credit * 20000); + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer2) + format_amount(g, credit * 20000) + message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer3)); + rec8(g, m, 0x26f) = uint8_t(credit); + if (result > 100000) { + season_apply_profit_tax(g, m, result, game, rand, tax_hooks, &tax_state); + } + const int32_t taxed = rec32(g, m, 0x32c), tax = rec32(g, m, 0x328); + if (result < 100000 && taxed != 0 && tax != 0) { + const int32_t back = season_profit_tax_refund(result, taxed, tax); + if (back > 0) { + post_composed(g, m, message_text(g, ::bmh::layout::Season_SeasonAccounts_TextPointer4) + format_amount(g, back) + "."); + set_rec32(g, m, 0x314, rec32(g, m, 0x314) + back); + } + } + if (result < 0x186a1) set_rec32(g, m, 0x32c, 0); + set_rec32(g, m, 0x320, 0); + set_rec32(g, m, 0x324, rec32(g, m, 0x314)); + for (size_t i = 0; i < 0x48; i++) rec8(g, m, 0x85c + i) = 0; + season_tickets(g, m, rand); // ChangePlaces -> CareerSeasonSetup2 +} + +// ClubsChangePlaces(a, b): two clubs (ids below 168) change places - every table per club id +// swaps its entries, lists of club ids replace the one by the other. Squads, position +// histories and loans only move between league clubs (ids below 138); the table *ClubAuxiliaryBytes +// swaps twice for them (no change), once otherwise. +void change_places(GameState& g, int a, int b) { + StaticMemory& mem = g.memory; + if (a >= 0x8a + 0x1e || b >= 0x8a + 0x1e) return; + auto swap_bytes = [](std::vector& v, size_t x, size_t y, size_t n) { + for (size_t i = 0; i < n; i++) + if (x + i < v.size() && y + i < v.size()) std::swap(v[x + i], v[y + i]); + }; + auto swap_mem8 = [&](uint32_t base) { + const uint8_t t = mem.u8(base + uint32_t(a)); + mem.set8(base + uint32_t(a), mem.u8(base + uint32_t(b))); + mem.set8(base + uint32_t(b), t); + }; + auto replace = [&](uint32_t at, int n) { // U163 + for (int i = 0; i < n; i++) { + const uint16_t v = mem.u16(at + uint32_t(i) * 2); + if (v == uint16_t(a)) mem.set16(at + uint32_t(i) * 2, uint16_t(b)); + else if (v == uint16_t(b)) mem.set16(at + uint32_t(i) * 2, uint16_t(a)); + } + }; + const bool league_clubs = a < 0x8a && b < 0x8a; + if (league_clubs) + for (uint32_t k = 0; k < 200; k++) { // loans: seller and buyer + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0) continue; + int seller = int(e >> 12) & 0x3ff, buyer = int(e >> 22) & 0x3ff; + seller = seller == a ? b : seller == b ? a : seller; + buyer = buyer == a ? b : buyer == b ? a : buyer; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4, (e & 0xfff) | uint32_t(seller) << 12 | uint32_t(buyer) << 22); + } + if (!g.club_table.empty() && a < 0xa8 && b < 0xa8) swap_bytes(g.club_table, size_t(a) * 0x4a, size_t(b) * 0x4a, 0x4a); + std::swap(g.club_ids.at(size_t(a)), g.club_ids.at(size_t(b))); + swap_bytes(g.club_heap_bc, size_t(a) * 2, size_t(b) * 2, 2); + std::swap(g.team_morale.at(size_t(a)), g.team_morale.at(size_t(b))); + swap_mem8(::bmh::layout::ClubShortNameOffsets); + swap_mem8(::bmh::layout::ClubKitSelectors); + swap_bytes(g.club_heap_78, size_t(a) * 2, size_t(b) * 2, 2); + std::swap(g.team_flags.at(size_t(a)), g.team_flags.at(size_t(b))); + if (league_clubs) { + swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2); + swap_bytes(g.position_history, size_t(a) * 0x1a, size_t(b) * 0x1a, 0x1a); + const SquadRange ra = squad_range(a), rb = squad_range(b); + for (size_t i = 0; i < ra.count; i++) std::swap(g.squad_slots.at(ra.first + i), g.squad_slots.at(rb.first + i)); + } + swap_bytes(g.club_heap_b8, size_t(a) * 2, size_t(b) * 2, 2); + replace(::bmh::layout::Titles, 0x1c2); // title holders + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 2); + if (!mem.has(::bmh::layout::CareerSession_FormatError_RuntimeField6) || mem.u8(::bmh::layout::CareerSession_FormatError_RuntimeField6) == 0) { + replace(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, 0x20); + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, 0x20); + replace(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, 0x40); + // (the English national cup field: 68 clubs at layout field, InitializeNationalCup(0x44, ...)) + if (kEnglishCompetitions) { + if (mem.has(kEnglishFaField)) replace(kEnglishFaField, 0x44); + } else { + replace(::bmh::layout::Field, 0x40); + } + replace(::bmh::layout::Cup_AdvanceCup_RuntimeField6, 3); + } + for (size_t m = 0; m < g.manager_teams.size(); m++) { + auto& t = g.manager_teams[m]; + const int old = t; + if (old == a) t = b; + else if (old == b) t = a; + if (t != old) { + g.manager_records.at(m * 0xB0C + 0x290) = uint8_t(t); + g.manager_records.at(m * 0xB0C + 0x291) = uint8_t(uint16_t(t) >> 8); + } + for (size_t i = 0; i < 12; i++) { // record +0x292 + const size_t at = m * 0xB0C + 0x292 + i * 2; + const uint16_t v = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8); + const uint16_t w = v == uint16_t(a) ? uint16_t(b) : v == uint16_t(b) ? uint16_t(a) : v; + g.manager_records.at(at) = uint8_t(w), g.manager_records.at(at + 1) = uint8_t(w >> 8); + } + swap_bytes(g.manager_results, size_t(a) * 10 + m * 0x690, size_t(b) * 10 + m * 0x690, 10); + } +} + +// Getenv(teams, offset): the national cup's ties from `offset` on (list of cup +// entry 0): a lower club (from the third division on, SeasonRuntimeField23) gets home advantage, +// then the ties are ordered by the leagues' weight (SeasonRuntimeField24), heaviest first. +void order_cup_ties(GameState& g, int teams, int offset) { + StaticMemory& mem = g.memory; + uint32_t list = mem.pointer(::bmh::layout::CupTable) + uint32_t(offset) * 2; + if (kEnglishCompetitions) { + // the Football Limited CupField: the FA Cup stage decides the range - qualifying + // round 1 (48 clubs from 0), round 2 (24 from 48), the proper rounds (entry 28); + // with 0x80 the League Cup (entry 25) + if ((teams & 0x80) == 0) { + const uint8_t played = mem.u8(::bmh::layout::CupTable + 0x1d); + if (played == 0) teams = 0x30, offset = 0; + if (played == 1) teams = 0x18, offset = 0x30; + const uint32_t base = played == 3 ? mem.pointer(::bmh::layout::CupTable + 28 * 0x28) : mem.pointer(::bmh::layout::CupTable); + list = base + uint32_t(offset) * 2; + } else { + teams ^= 0x80; + list = mem.pointer(::bmh::layout::CupTable + 25 * 0x28) + uint32_t(offset) * 2; + } + } + static const uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0}; // SeasonRuntimeField24 + const int lower = league_first_team(2); + std::vector w; + for (int i = 0; i < teams; i += 2) { + const uint32_t at = list + uint32_t(i) * 2; + if (int16_t(mem.u16(at + 2)) >= lower && int16_t(mem.u16(at)) < lower) { + const uint16_t t = mem.u16(at); + mem.set16(at, mem.u16(at + 2)); + mem.set16(at + 2, t); + } + w.push_back(uint8_t(kWeight[club_league(mem.u16(at))] + kWeight[club_league(mem.u16(at + 2))])); + } + for (int i = 0; i < teams / 2 - 1; i++) + for (int j = i + 1; j < teams / 2; j++) + if (w[size_t(i)] < w[size_t(j)]) { + std::swap(w[size_t(i)], w[size_t(j)]); + for (uint32_t k = 0; k < 2; k++) { + const uint32_t x = list + uint32_t(i) * 4 + k * 2, y = list + uint32_t(j) * 4 + k * 2; + const uint16_t t = mem.u16(x); + mem.set16(x, mem.u16(y)); + mem.set16(y, t); + } + } +} + +} // namespace + +void clubs_change_places(GameState& g, int a, int b) { change_places(g, a, b); } + +// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): slot 4 +// of the running competitions is this year's international tournament (7 - season % 4), +// the screen state of the manager (CareerSession_DispatchOtherGames_RuntimeField) is reset, and the friendlies +// (competition 0xc) run while their entry (cup entry 30) has teams. +void cup_overview_effects(GameState& g) { + StaticMemory& mem = g.memory; + if (mem.has(::bmh::layout::CareerSession_FormatError_RuntimeField3)) mem.set8(::bmh::layout::CareerSession_FormatError_RuntimeField3, uint8_t(7 - uint16_t(g.season) % 4)); + // CupGroupOverviewEffects normalizes the active manager byte before selecting that manager's + // screen-state slot. This is a real Source mutation (and is serialized where present). + uint8_t active = mem.has(::bmh::layout::ActiveManager) ? mem.u8(::bmh::layout::ActiveManager) : 0; + if (active > 3) { + active = 0; + if (mem.has(::bmh::layout::ActiveManager)) mem.set8(::bmh::layout::ActiveManager, active); + } + if (mem.has(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + active)) mem.set8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField + active, 0x80); + if (mem.u8(::bmh::layout::FriendlyPlanCount) == 0) { + end_competition(mem, 0xc); + } else { + for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xc) + if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == 0xc) break; + if (mem.u8(::bmh::layout::ActiveSelectors + i) == 0x14) { + mem.set8(::bmh::layout::ActiveSelectors + i, 0xc); + break; + } + } + } +} + +void cup_group_overview_effects(GameState& g, int group_index) { + // This Source traversal cursor is runtime state, absent from native FBMs. + // Own it at the overview boundary even after loading a saved career. + if (!g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField8)) g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField8, 1); + g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField8, uint8_t(group_index)); + cup_overview_effects(g); +} + +namespace { + +// Getenv2: every club of every league changes places with a random other club of the +// same league (ClubsChangePlaces) - this mixes the fixture positions of the new season +void shuffle_leagues(GameState& g, WatcomRandom& rand) { + int first = 0; + for (int l = 0; l < kLeagueCount; l++) { + const int end = first + kLeagueSizes[l]; + for (int t = first; t < end; t++) { + int r; + do r = rand.range(first, end - 1); while (uint8_t(r) == uint8_t(t)); + change_places(g, t, r); + } + first = end; + } +} + +// CareerSeasonSetup(2): the national cup's field - the first 18 of the first two divisions and +// the first 14 of the two third divisions by the final tables, shuffled (PrepareEvent). +// Human managers note the cup in their season record (ManagerOf(m, 1, 1)). Its first +// round is shown (CupDrawFromGame on cup entry 0) unless switched off; then Getenv gives +// the lower club home advantage and sorts the ties by the leagues' weight (SeasonRuntimeField24). +void observe_cup_draw(const GameState& g, SeasonCupDrawPhase phase, + const SeasonCupDrawHook& hook) { + if (!hook) return; + const StaticMemory& mem = g.memory; + constexpr uint32_t entry = kCupTable; + SeasonCupDrawEvent event; + event.phase = phase; + event.entry_address = entry; + event.competition = mem.u8(entry + 0x18); + event.flags = mem.u8(entry + 0x14); + event.group_stage = (event.flags & 4) == 0; + event.group_index = mem.u8(entry + 0x1e) >> 4; + event.group_count = mem.u8(entry + 0x1e) & 0xf; + event.round = cup_round(mem, 0); + event.offset = cup_round_offset(mem, 0, event.round); + event.count = size_t(mem.u8(entry + 0x1a)) >> event.round; + const uint32_t field = mem.pointer(entry) + uint32_t(event.offset) * 2; + event.participants.reserve(event.count); + for (size_t i = 0; i < event.count; ++i) + event.participants.push_back(mem.u16(field + uint32_t(i) * 2)); + hook(g, event); +} + +// The English national cups (the Football Limited CupFieldsEnglish(2)): the FA Cup field of 68 +// clubs - the first three divisions complete and the best 8 of the fourth - whose 20 Premier +// League clubs and 48 others are shuffled apart (the 48 play the qualifying stage of entry +// 0), and the League Cup field of 44 - the first two divisions and the best 4 of the third, +// 20 and 24 shuffled apart (entry 25) - whose ties are ordered (CupField(0x98, 0)). +void cup_fields_english(GameState& g, GameRandom& game, const uint8_t (&ranks)[4][24], + const std::function& pause, const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + english_competition_blocks(mem); + auto shuffle = [&](uint32_t list, uint32_t n) { // Uint32T2 = PrepareEvent + for (uint32_t i = 0; i < n; i++) { + const uint32_t j = uint32_t(game.range(0, int(n) - 1)); + const uint16_t a = mem.u16(list + i * 2); + mem.set16(list + i * 2, mem.u16(list + j * 2)); + mem.set16(list + j * 2, a); + } + }; + uint32_t n = 0; + for (int l = 0; l < 4; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 3 && i >= 8) continue; + const int team = club_at_rank(l, i, ranks[l]); + mem.set16(kEnglishFaField + n++ * 2, uint16_t(team)); + if (const int m = g.manager_of(team); m >= 0) + g.manager_records.at(size_t(m) * 0xB0C + 0xda + 1 + size_t(std::min(g.season, 0x31)) * 3) = 1; + } + shuffle(kEnglishFaField, 0x14); + shuffle(kEnglishFaQualifyingField, 0x30); + if (mem.u8(::bmh::layout::LeaguePresentationOptions + 5 * 9) == 0) { // CupOverviewEffects(entry 0) unless the draw display is off + observe_cup_draw(g, SeasonCupDrawPhase::draw, cup_draw); + if (pause) pause("the FA Cup draw (CupOverviewEffects)"); + order_cup_ties(g, 0x30, 0); // (CupOverviewEffects orders the ties: CupField, stage 0) + cup_overview_effects(g); + observe_cup_draw(g, SeasonCupDrawPhase::overview, cup_draw); + } + n = 0; + for (int l = 0; l < 3; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 2 && i >= 4) continue; + mem.set16(kEnglishLeagueCupField + n++ * 2, uint16_t(club_at_rank(l, i, ranks[l]))); + } + shuffle(kEnglishLeagueCupField, 0x14); + shuffle(kEnglishLeagueCupField + 0x28, n - 0x14); + order_cup_ties(g, 0x98, 0); // CupField(0x98, 0): the League Cup ties +} + +void cup_field(GameState& g, GameRandom& game, const std::function& pause, + const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + uint8_t ranks[4][24] = {}; + for (int l = 0; l < 4; l++) { + const LeagueTable t = compute_league_table(g, l, 0, league_matchdays(l), 7, 1); + for (int i = 0; i < t.size; i++) ranks[l][i] = uint8_t(t.rank(i)); + } + if (kEnglishCompetitions) { + cup_fields_english(g, game, ranks, pause, cup_draw); + return; + } + constexpr uint32_t kField = ::bmh::layout::Field; + uint32_t n = 0; + for (int l = 0; l < 4; l++) + for (int i = 0; i < kLeagueSizes[l]; i++) { + if (l >= 2 && i >= 0xe) continue; + const int team = club_at_rank(l, i, ranks[l]); + mem.set16(kField + n++ * 2, uint16_t(team)); + if (const int m = g.manager_of(team); m >= 0) + g.manager_records.at(size_t(m) * 0xB0C + 0xda + 1 + size_t(std::min(g.season, 0x31)) * 3) = 1; + } + for (uint32_t i = 0; i < 0x40; i++) { // PrepareEvent + const uint32_t j = uint32_t(game.range(0, 0x3f)); + const uint16_t a = mem.u16(kField + i * 2); + mem.set16(kField + i * 2, mem.u16(kField + j * 2)); + mem.set16(kField + j * 2, a); + } + if (mem.u8(::bmh::layout::LeaguePresentationOptions + 5 * 9) != 0) return; // the draw display is switched off + observe_cup_draw(g, SeasonCupDrawPhase::draw, cup_draw); + if (pause) pause("the national cup draw (CupDrawFromGame)"); + order_cup_ties(g, mem.u8(::bmh::layout::CupTable + 0x1a), 0); // (round 0 of cup entry 0) + cup_overview_effects(g); // CupGroupOverviewEffects lists the ties + observe_cup_draw(g, SeasonCupDrawPhase::overview, cup_draw); +} + +// GeneratePlayer: see generate_player (career.hpp) +void regenerate_player(GameState& g, int player, int strength, GameRandom& game, WatcomRandom& rand) { + generate_player(g, player, strength, game, rand); +} + +// SetAge(player, age): the age (w364 bits 21-25); bits 2-12 are cleared as well +void set_age(GameState& g, int player, int age) { + Player& p = g.players.at(size_t(player)); + p.w364 = (p.w364 & 0x1fe003u) | uint32_t(age) << 21; +} + +} // namespace + +// MonthChange(slot): a player leaves his club for the free agents (foreigners to their own +// pool): his loan entry and youth mark go, he gets new values (RegeneratePlayer: all but w35c), +// an age W(4, 15) and no injury; the club closes the gap (ReleasePlayer) +bool release_player(GameState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0 || int(e & 0xFFF) != player) continue; + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4, 0); + for (uint32_t i = 0; i < 12; i++) + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2) == uint16_t(player)) { + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xFFF); + const uint32_t owner = ::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(int8_t(mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + i))); + mem.set8(owner, uint8_t(mem.u8(owner) - 1)); + } + break; + } + const int team = slot_team(slot); + const bool foreign = nationality(g, player) != 0; + const int start = foreign ? 0xbec : 0xb9c, count = foreign ? 0x14 : 0x50; // FirstFreeSlotSquad + int free = -1; + for (int s = start; s < start + count && free < 0; s++) + if (g.squad_slots.at(size_t(s)) == 0x0FFF) free = s; + const uint32_t skills = g.players.at(size_t(player)).w35c; // RegeneratePlayer + regenerate_player(g, player, 0x32, game, rand); + Player& p = g.players.at(size_t(player)); + p.w35c = skills; + g.player_bonus.at(size_t(player)) &= 0x80; + p.w368 &= 0xf8003fffu; + p.w364 &= 3; + p.w364 |= uint32_t(rand.range(4, 0xf)) << 21; + p.w35c &= 0x07ffffffu; + if (free < 0) { + // no room among the free agents: a club takes him (TransferBid(slot, 0, 0, -1)) + transfer_bid(g, slot, 0, false, -1, game, rand, report); + if (report.unsupported) return false; + } else { + g.squad_slots.at(size_t(free)) = uint16_t(player); + } + if (team >= 0) return remove_from_seller(g, team, player, report); + return true; +} + +namespace { + +// CareerSeasonSetup3: the players' new season. Records and boards of the managers restart +// (with new advertising offers, TransferListCountdown2); then every squad and pool slot: players +// out for their career recover now and then with a human club's good doctor, else leave; +// everybody grows a year older (w364 bits 21-25), and at a computer club an old player +// retires (unless the squad is small: then he is replaced by a young one) - the first old +// one of every club always goes (a quirk: the counter starts at 0xFF). Last the rounds, +// cards, position histories and results of the old season are cleared. +void season_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + auto fill8 = [&](uint32_t at, uint32_t n, uint8_t v) { + for (uint32_t i = 0; i < n; i++) + if (mem.has(at + i)) mem.set8(at + i, v); + }; + auto fill16 = [&](uint32_t at, uint32_t n, uint16_t v) { + for (uint32_t i = 0; i < n; i++) + if (mem.has(at + i * 2)) mem.set16(at + i * 2, v); + }; + // Fill8: desk and screen states + fill8(::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField, 4, 0x80), fill8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField, 4, 1); + fill16(::bmh::layout::LeagueTableDisplayModes, 4, 0x11), fill16(::bmh::layout::ManagerSettings, 4, 0x1ff), fill16(::bmh::layout::CareerSession_AnyOf_ExecutableField, 4, 0x15), fill16(::bmh::layout::Savestate_Layout_ExecutableField3, 4, 0xdf0); + fill8(::bmh::layout::Flags, 0xc, 0x40); + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (size_t i = 0; i < 10; i++) rec8(g, int(m), 0x8b6 + i) = 0xff; + end_competition(mem, 0xd); // EndCompetition + fill8(::bmh::layout::Season_SeasonPlayers_ExecutableField, 1, 0); + for (size_t mi = 0; mi < g.manager_teams.size() && !report.unsupported; mi++) { + const int m = int(mi); + // CareerSeasonSetup3 invokes StartingSponsors for each manager before resetting + // seasonal records and constructing new advertising offers. + starting_sponsors(g, m); + rec8(g, m, 0x284) = 0, rec8(g, m, 0x21e) = 0, rec8(g, m, 0x283) = 0; + set_rec32(g, m, 0x330, 0); + rec8(g, m, 0x28b) = 0; + for (size_t i = 0; i < 3; i++) rec8(g, m, 0x28c + i) = 0; + for (size_t i = 0; i < 10; i++) rec8(g, m, 0x170 + i) = 0; + for (size_t i = 0; i < 0x48; i++) rec8(g, m, 0x1ae + i) = 0; + for (size_t i = 0; i < 0x30; i++) rec8(g, m, 0x718 + i) = 0; + for (size_t i = 0; i < 0xc; i++) rec8(g, m, 0x8c0 + i) = 0, rec8(g, m, 0x748 + i) = 0; + advertising_offers(g, m, rand, report); // TransferListCountdown2 + if (report.unsupported) return; + set_rec32(g, m, 0x33c, 0), set_rec32(g, m, 0x338, 0), set_rec32(g, m, 0x334, 0); + for (size_t s = 0; s < 24; s++) { + const size_t at = mi * 0x840 + s * 0x58; + g.tactics.at(at + 6) = 0; + g.tactics.at(at + 0xf) = uint8_t(rand.range(0x14, 0x32)); + } + for (uint32_t i = 0; i < 12; i++) + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2) != 0xfff && int8_t(mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + i)) == m) { + mem.set8(::bmh::layout::Season_SeasonPlayers_RuntimeField + i * 0x58, 0); + mem.set8(::bmh::layout::Season_SeasonPlayers_RuntimeField2 + i * 0x58, uint8_t(rand.range(0x14, 0x32))); + } + } + if (g.date > 0) { + g.lineups_frozen = true; // LineupRuntimeField + uint8_t loans[0x1d3] = {}; + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e != 0) loans[(e >> 12) & 0x3ff]++; + } + uint16_t last_team = 0xffff; // local_30 + uint8_t count = 0xff; // local_20 + int8_t owner = -1; // local_24: the club's human manager + size_t board_first = 0; // local_3c + for (int s = 0; s < 0xc00 && !report.unsupported; s++) { + for (;;) { + const int player = g.squad_slots.at(size_t(s)) & 0xFFF; + if (player == 0xFFF) break; + const int team = slot_team(s); + if (team != int(last_team)) { // (-1 for the pool never equals 0xFFFF) + count = 0xff; + const int mm = g.manager_of(team); + owner = int8_t(mm >= 0 ? mm : -1); + if (mm >= 0) board_first = squad_range(team).first; + } + Player& p = g.players.at(size_t(player)); + bool leaves = false; + if (s < 0xb70 && (p.w35c >> 27) == 0x1f) { + // out for his career + bool gone = true; + if (owner != -1) { + std::string text; + const int doctor = int16_t(g.manager_records.at(size_t(owner) * 0xB0C + 0x8ae) | + g.manager_records.at(size_t(owner) * 0xB0C + 0x8af) << 8); + if (doctor > rand.range(700, 0x4b0)) { + text = message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer2); + gone = false; + p.w35c &= 0x07ffffffu; + p.w364 &= ~(0x1fu << 16); + } else { + text = g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer3); + const size_t board = size_t(owner) * 0x840 + size_t(s - int(board_first)) * 0x58; + const int8_t insured = int8_t(g.tactics.at(board + 0x43)); + if (insured != 0) { + const int k = (insured >> 6) & 3; + const int32_t pay = int32_t(uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16) | + uint32_t(g.tactics.at(board + 0x53)) << 24) * + int8_t(k * 3 + 3); + book_money(g, owner, -pay, true); + text += message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer4) + format_amount(g, pay) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer5); + } + } + post_composed(g, owner, text); + } + if (gone) { + if (count != 0xff) count = uint8_t(squad_count(g, team, 2) + loans[team]); + if (owner == -1 && count <= 0xd) { + set_age(g, player, rand.range(0x12, 0x19) - 0x10); + } else { + count--; + leaves = true; + // a loaned player: his club's manager is told + for (uint32_t k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + k * 4); + if (e == 0 || int(e & 0xFFF) != player) continue; + const int mm = g.manager_of(int(e >> 12) & 0x3ff); + owner = int8_t(mm >= 0 ? mm : -1); + if (mm >= 0) + post_composed(g, mm, message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer6) + g.player_name(player) + message_text(g, ::bmh::layout::Season_SeasonPlayers_TextPointer7)); + break; + } + } + } + } + if (!leaves) { + // a year older + p.w368 &= 0xf8003fffu; + int age = int16_t(((p.w364 >> 21) & 0x1f) + 1); + if (s < 0xb70 && rand.range(0x10, 0x16) < age && owner == -1) { + if (count != 0xff) count = uint8_t(squad_count(g, team, 2) + loans[team]); + if (count > 0xd) { + count--; + leaves = true; + } else { + age = rand.range(0x12, 0x19) - 0x10; + } + } + if (!leaves) { + set_age(g, player, age); // SetAge + last_team = uint16_t(team); + break; + } + } + if (std::getenv("BMH_TRACE")) + std::printf(" [release slot %d player %d team %d age %u count %u]\n", s, player, team, (p.w364 >> 21) & 0x1f, count); + if (!release_player(g, s, game, rand, report)) return; + } + } + g.lineups_frozen = false; + } + for (size_t l = 0; l < g.league_rounds.size() && l < 9; l++) g.league_rounds[l] = 0; + fill8(::bmh::layout::DeskRecords_Teams_RuntimeField, 0x114, 0); + for (size_t i = 0; i < size_t(0x8a) * 0x1a && i < g.position_history.size(); i++) g.position_history[i] = 0; + std::fill(g.results.begin(), g.results.end(), uint8_t(0xcc)); +} + +// The end of the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest: histories beyond 50 seasons shift +// (SeasonEndSteps), the managers' season record starts (ManagerOf(m, 0, -2)), the +// limited game length counts down (CareerDuration), the days pass (DayStepRest) up to the +// first Wednesday, new players come onto the transfer list (CareerFirstSteps), and the new +// season starts on that day (DaysIntoSeason = 0) with its calendar cleared of replay days. +SeasonTransitionOutcome season_end_steps(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const SeasonHighscoreHook& highscore, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + if (g.season > 0x31) { // SeasonEndSteps + for (uint32_t k = 0; k < 9; k++) { + for (uint32_t i = 0; i < 0x62; i++) mem.set8(::bmh::layout::Titles + k * 100 + i, mem.u8(::bmh::layout::Season_SeasonEndSteps_RuntimeField + k * 100 + i)); + mem.set16(::bmh::layout::Season_SeasonEndSteps_RuntimeField2 + k * 100, 0xffff); + } + for (size_t m = 0; m < g.manager_teams.size(); m++) { + for (size_t i = 0; i < 0x93; i++) rec8(g, int(m), 0xda + i) = rec8(g, int(m), 0xdd + i); + const size_t at = m * 0xB0C + 0x2aa; + const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8) + 1; + g.manager_records.at(at) = uint8_t(n), g.manager_records.at(at + 1) = uint8_t(n >> 8); + } + } + for (size_t m = 0; m < g.manager_teams.size(); m++) + rec8(g, int(m), 0xda + size_t(std::min(g.season, 0x31)) * 3) = 0xfe; + // GameEndAlternateScoreScreen(0): update the external highscore table before decrement. + if (highscore) highscore(g, false); + if (mem.has(::bmh::layout::CareerDuration)) { + uint8_t left = mem.u8(::bmh::layout::CareerDuration); + if (left < 5) mem.set8(::bmh::layout::CareerDuration, --left); + if (left == 0) { + // DailyInterest returns here before first-Wednesday day steps. + if (highscore) highscore(g, true); + return SeasonTransitionOutcome::CareerComplete; + } + } + const bool full = (mem.u8(::bmh::layout::CompetitionSelection) & 1) != 0; + while (weekday_code(g.date) != 2) { // DayStepRest + g.date++; + daily_interest(g, rand); + if (std::getenv("BMH_TRACE")) + std::printf(" [day %u (weekday %d): game %llu, Watcom %llu]\n", g.date, weekday_code(g.date), (unsigned long long)game.calls(), + (unsigned long long)rand.calls()); + const int wd = weekday_code(g.date - 1); + if (wd == 2 || wd == 6) { + if (full && weekday_code(g.date) == 3) { + weekly_processing(g, game, rand, report, allocator); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + } + familiarity_decay(g, game, rand); + for (size_t m = 0; m < g.manager_teams.size(); m++) train_squad(g, int(m), game, rand); + } + if (full && month_code(g.date - 1) != month_code(g.date)) { + month_change(g, rand, report, &game); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + } + } + if (std::getenv("BMH_TRACE")) + std::printf(" [before CareerFirstSteps: game %llu, Watcom %llu]\n", (unsigned long long)game.calls(), (unsigned long long)rand.calls()); + new_transfer_list_entries(g, rand, report); // CareerFirstSteps + if (report.unsupported) return SeasonTransitionOutcome::Failed; + if (mem.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) mem.set16(::bmh::layout::CalendarState_FormatError_RuntimeField3, uint16_t(g.date)); // (a 16-bit copy of the date) + g.season_start = g.date; // DaysIntoSeason = 0 + mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, 0); + for (uint32_t d = 0; d < 0x16d; d++) + if ((mem.u16(::bmh::layout::CompetitionCalendar + d * 2) & 0x4f0e) == 0x4000) mem.set16(::bmh::layout::CompetitionCalendar + d * 2, 0); + return SeasonTransitionOutcome::NextSeason; +} + +// LicenceWithdrawals(league, ...): clubs losing their licence - a bankrupt human club placed +// below 6th (its manager's league marker was set to 0x1e before), and with fewer than six +// managers now and then (G(0, 12 - 7 * league) == 0) a computer club of the first two +// divisions placed 10th-15th. They go down first; `places` counts down. +void licence_withdrawals(GameState& g, int league, std::vector& down, int& places, const uint8_t* ranks, + GameRandom& game, WatcomRandom& rand) { + const int first = league_first_team(league); + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const int team = g.manager_teams[m]; + if (team < first || team >= first + kLeagueSizes[league] || ranks[team - first] <= 5) continue; + static const uint8_t kDownPlaces[kLeagueCount] = {3, 4, 2, 2, 3, 0, 0, 0, 0}; // CareerSession_InstallLeagueSizes_RuntimeField2 + if (kDownPlaces[league] == 0) continue; + const uint8_t cut = rec8(g, int(m), 0x220); + const int32_t total = int32_t(rec8(g, int(m), 0x26f)) * 80000 + (assets(g, int(m), 0xf) - assets(g, int(m), 0x10)); + const bool broke = total < -6000000 || ((cut >> 5) == 2 && int32_t(cut & 0x1f) * 100000 <= rec32(g, int(m), 0x330)); + if (broke && rec8(g, int(m), 0x210) == 0x1e) { + rec8(g, int(m), 0x210) = 0; + post_text(g, int(m), text_id(::bmh::layout::Season_LicenceWithdrawals_TextPointer)); + down.push_back(uint16_t(team)); + if (places != 0) places--; + } + } + if (g.manager_teams.size() < 6 && league < 2 && game.range(0, 12 - 7 * league) == 0) { + int t = 0, r = 0; + do { + do { + r = rand.range(0, kLeagueSizes[league] - 1); + t = first + r; + } while (g.manager_of(t) >= 0); + } while (ranks[r] < 10 || ranks[r] > 15); + down.push_back(uint16_t(t)); + post_composed(g, -1, message_text(g, ::bmh::layout::Season_LicenceWithdrawals_TextPointer2) + g.club_name(t) + message_text(g, ::bmh::layout::Season_LicenceWithdrawals_TextPointer3)); + places--; + } +} + +// A real club name has a letter; the English database fills unused club ids with blanks and +// punctuation (", ", " :"). +bool club_has_name(const std::string& name) { + return std::any_of(name.begin(), name.end(), [](char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }); +} + +// Void: settle transfers and compute each group's local lists. Source +// displays them with SeasonPromotionScreen immediately before that group's club swaps. +void promotion(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonPromotionHook& promotion_hook, TransferAllocatorContext allocator) { + transfer_list_countdown(g, game, rand, report, true, allocator); // TransferListCountdown(1) + if (report.unsupported) return; + std::vector was; // the managers' leagues before (record +0x210) + for (size_t m = 0; m < g.manager_teams.size(); m++) was.push_back(rec8(g, int(m), 0x210)), rec8(g, int(m), 0x210) = 0x1e; + uint8_t ranks[5][24] = {}; + for (int l = 0; l < 5; l++) { + const LeagueTable t = compute_league_table(g, l, 0, league_matchdays(l), 7, 1); + for (int i = 0; i < t.size; i++) ranks[l][i] = uint8_t(t.rank(i)); + } + // The league ladder is data of the loaded game (schedule.hpp, installed from the EXE): + // Void reads the German tables, the English ClubName its own copies - + // first league / number of leagues of each promotion group (kGroupLeague/s), relegation + // places (kLeagueRelegation), the league(s) below (kGroupBelow/Count). German: + // 0 | 1 | 2+3 (Regionalliga A/B) | 4; English: 0 | 1 | 2 | 3. + const uint8_t* kFirst = kGroupLeague; + const uint8_t* kCount = kGroupLeagues; + const uint8_t* kDown = kLeagueRelegation; + const uint8_t* kBelow = kGroupBelow; + const uint8_t* kBelowCount = kGroupBelowCount; + // The clubs that refill the lowest league: kNewcomerCount clubs from kNewcomerFirst + // (German: the 30 amateur clubs 138-167). The English game draws from its 12 further + // English clubs (ClubName: range(CareerSession_DispatchLineup_RuntimeField, CareerSession_DispatchLineup_RuntimeField + 11)); its later ids have no name. + // The span ends at the last named club, which keeps the German draws unchanged. + // (OpenBMH deviates from the English original here: its extra coin flip per draw is not + // ported.) + const int newcomer_first = kNewcomerFirst; + int newcomer_count = kNewcomerCount; + while (newcomer_count > 1) { + const std::string name = g.club_name(newcomer_first + newcomer_count - 1); + if (club_has_name(name)) break; + newcomer_count--; + } + for (int grp = 0; grp < 4; grp++) { + std::vector down, up; + for (int l = kFirst[grp]; l < kFirst[grp] + kCount[grp]; l++) { + int places = kDown[l]; + licence_withdrawals(g, l, down, places, ranks[l], game, rand); + for (int rank = kLeagueSizes[l] - 1; places != 0; rank--) { + const int team = club_at_rank(l, rank, ranks[l]); + if (std::find(down.begin(), down.end(), uint16_t(team)) == down.end()) down.push_back(uint16_t(team)), places--; + } + } + size_t count = down.size(); + if (grp < 3) { + // the top of the division(s) below; from the two third divisions their + // champions and the play-off winners (Season_Promotion_ExecutableField2 / Season_Promotion_ExecutableField), without a play-off + // only the champions + size_t per = count / kBelowCount[grp]; + for (int l = kBelow[grp]; l < kBelow[grp] + kBelowCount[grp]; l++) { + if (kBelowCount[grp] > 1) { + if (mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField) == 0) count = 2; + else up.push_back(l > kBelow[grp] ? mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField) : mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField2)); + per = 1; + } + for (size_t i = 0; i < per; i++) up.push_back(uint16_t(club_at_rank(l, int(i), ranks[l]))); + } + } else { + // into the fourth division come amateur clubs (ids 138-167) at random + for (size_t i = 0; i < count; i++) { + uint16_t t; + do t = uint16_t(rand.range(newcomer_first, newcomer_first + newcomer_count - 1)); + // (never a club without a name: the English range has gaps; German draws are + // unchanged, all thirty amateur clubs have names) + while (std::find(up.begin(), up.end(), t) != up.end() || + !club_has_name(g.club_name(t))); + up.push_back(t); + } + } + static const char* kScreen[4] = {"promotion and relegation of the first division (SeasonPromotionScreen)", + "promotion and relegation of the second division (SeasonPromotionScreen)", + "promotion and relegation of the third divisions (SeasonPromotionScreen)", + "promotion and relegation of the fourth division (SeasonPromotionScreen)"}; + if (std::getenv("BMH_TRACE")) { + std::printf(" [group %d: count %zu down", grp, count); + for (uint16_t t : down) std::printf(" %d", t); + std::printf(" up"); + for (uint16_t t : up) std::printf(" %d", t); + std::printf(" a3204 %d a3206 %d]\n", mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField), mem_u16(g, ::bmh::layout::Season_Promotion_ExecutableField2)); + } + if (promotion_hook) promotion_hook(g, SeasonPromotionEvent{grp, count, down, up}); + if (pause) pause(kScreen[grp]); + for (size_t i = 0; i < count && i < up.size() && i < down.size(); i++) { + if (grp == 3 && g.manager_of(down[i]) >= 0) continue; + const int m = g.manager_of(up[i]); + if (m >= 0) { + // a promoted human club: its advertising contracts are marked, and a message + for (size_t k = 0; k < 0x12; k++) rec8(g, m, 0xa3a + k * 0xc) |= 0x80; + post_text(g, m, text_id(::bmh::layout::Season_Promotion_TextPointer)); + } + change_places(g, up[i], down[i]); + } + } + // the managers' leagues (record +0x210) and the desk buttons of leagues they left or + // joined (block LeaguePresentationOptions, 9 per league) + StaticMemory& mem = g.memory; + bool left[5] = {}, joined[5] = {}; + for (size_t m = 0; m < g.manager_teams.size(); m++) { + const uint8_t before = uint8_t(was[m]); + const int now = club_league(g.manager_teams[m]); + rec8(g, int(m), 0x210) = uint8_t(now); + if (now < 5) joined[now] = true; + if (before < 5) left[before] = true; + for (uint32_t k = 0; k < 4; k++) + if (mem.u8(::bmh::layout::LeaguePresentationOptions + uint32_t(before) * 9 + k) == 0) mem.set8(::bmh::layout::LeaguePresentationOptions + uint32_t(now) * 9 + k, 0); + } + for (int l = 0; l < 5; l++) + if (!joined[l] && left[l]) + for (uint32_t k = 0; k < 4; k++) mem.set8(::bmh::layout::LeaguePresentationOptions + uint32_t(l) * 9 + k, 1); +} + +} // namespace + +// LeagueName(buf, league): the name of a league (< 5): the texts from Achievements_FormatError_TextPointer3 on - a +// league whose suffix letter (CareerSession_InstallLeagueSizes_RuntimeField3, two bytes per league) is set shares the text of +// the one before when its letter is from 'B' on (LeagueName2) - with " " + the letter. +std::string league_name(const GameState& g, int league) { + // CareerSession_InstallLeagueSizes_RuntimeField3 of the loaded game (schedule.hpp: German A/B for the two Regionalligen, + // English none - its four divisions are one ladder) + const char* kSuffix = kLeagueSuffix; + int index = 0; + for (int l = 0; l < league; l++) + if (uint8_t(kSuffix[l + 1]) < 0x42) index++; + std::string name = message_text(g, ::bmh::layout::Achievements_FormatError_TextPointer3 + uint32_t(index) * 4); + if (kSuffix[league] != 0) { + name += message_text(g, ::bmh::layout::Manager_FormatError_TextPointer2); + if (!name.empty()) name.back() = kSuffix[league]; + } + return name; +} + +namespace { + +// TopScorersFromGame(league, flags): the ten best scorers of a league into Season_List_RuntimeField (10 x +// slot, team, goals, assists): goals (w364 bits 2-7, flag 2) plus assists (w368 bits 18-23, +// flag 4); flag 1 only counts human clubs. A player goes before the first one with fewer +// points (equal ones keep the earlier club / squad slot first). Returns the team of the best. +int best_scorer_team(GameState& g, int league, int flags) { + std::vector list(40, 0); + for (int i = 0; i < 40; i += 4) list[size_t(i)] = 0xfff, list[size_t(i) + 1] = 0xfff; + int16_t best[10] = {}; + const int first = league_first_team(league); + for (int team = first; team < first + kLeagueSizes[league]; team++) { + if (g.manager_of(team) < 0 && (flags & 1)) continue; + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0xfff; + if (player == 0xfff) continue; + const Player& p = g.players.at(size_t(player)); + const uint16_t goals = (flags & 2) ? uint16_t((p.w364 >> 2) & 0x3f) : 0; + const uint16_t assists = (flags & 4) ? uint16_t((p.w368 >> 18) & 0x3f) : 0; + const uint8_t points = uint8_t(goals + assists); + if (points == 0) continue; + for (int i = 0; i < 10; i++) { + if (best[i] >= int16_t(points)) continue; + for (int k = 9; k > i; k--) { + best[k] = best[k - 1]; + for (int j = 0; j < 4; j++) list[size_t(k * 4 + j)] = list[size_t((k - 1) * 4 + j)]; + } + list[size_t(i * 4)] = uint16_t(s), list[size_t(i * 4 + 1)] = uint16_t(team); + list[size_t(i * 4 + 2)] = goals, list[size_t(i * 4 + 3)] = assists; + best[i] = int16_t(points); + break; + } + } + } + if (g.memory.has(::bmh::layout::Season_List_RuntimeField)) + for (uint32_t i = 0; i < 40; i++) g.memory.set16(::bmh::layout::Season_List_RuntimeField + i * 2, list[i]); + return list[1]; +} + +// FairPlayStateFromGame(league, 0): the fair play table - 4 points per red card (high byte of the +// club's card counter DeskRecords_Teams_RuntimeField) and 1 per yellow, sorted ascending (Games). +// Returns the club with the fewest points. +int fair_play_team(const GameState& g, int league) { + const int first = league_first_team(league), count = kLeagueSizes[league]; + std::vector teams(static_cast(count)); + std::vector points(static_cast(count)); + for (int i = 0; i < count; i++) { + teams[size_t(i)] = int16_t(first + i); + const uint16_t cards = g.memory.u16(::bmh::layout::DeskRecords_Teams_RuntimeField + uint32_t(first + i) * 2); + points[size_t(i)] = uint32_t((int16_t(cards) >> 8) * 4 + (cards & 0xff)); + } + quicksort_by_key(teams.data(), points.data(), count, true); + return teams[0]; +} + +} // namespace + +void season_awards(GameState& g) { + static const uint8_t kFlags[2] = {2, 6}; // SeasonRuntimeField25: top scorer, best scorer (+ assists) + // SeasonRuntimeField26: the prizes in 10000s per league (top scorer, best scorer, fair play) + static const uint8_t kPrize[5][3] = {{30, 20, 25}, {20, 15, 17}, {15, 10, 12}, {15, 10, 12}, {10, 7, 9}}; + for (int kind = 0; kind < 3; kind++) + for (int league = 0; league < 5; league++) { + const int team = kind < 2 ? best_scorer_team(g, league, kFlags[kind]) : fair_play_team(g, league); + for (size_t m = 0; m < g.manager_teams.size(); m++) { + if (g.manager_teams[m] != team) continue; + const int32_t prize = int32_t(kPrize[league][kind]) * 10000; + // "Ihr Spieler / Ihre Mannschaft gewinnt den ... der . Prämie: ." + std::string text = message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer3) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer2 + (kind == 2 ? 4u : 0u)) + + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer4) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer + uint32_t(kind) * 4) + + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer5) + league_name(g, league) + message_text(g, ::bmh::layout::Season_SeasonAwards_TextPointer6) + + format_amount(g, prize) + "."; + post_composed(g, int(m), text); + book_money(g, int(m), -prize, true, true); // BookMoney2(team, -prize, 1), FinanceStatisticsEnabled + } + } +} + +SeasonTransitionOutcome season_transition(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonHighscoreHook& highscore, + const SeasonTaxHooks& tax_hooks, + const SeasonPromotionHook& promotion_hook, + const SeasonCupDrawHook& cup_draw, + TransferAllocatorContext allocator) { + if (g.memory.has(::bmh::layout::CareerDuration) && g.memory.u8(::bmh::layout::CareerDuration) == 0) { + report.fail("season transition: career already completed"); + return SeasonTransitionOutcome::Failed; + } + g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 0); + if (g.memory.has(::bmh::layout::Season_SeasonTransition_RuntimeField)) g.memory.set8(::bmh::layout::Season_SeasonTransition_RuntimeField, 0); + g.season = int16_t(g.season + 1); // SeasonIndex + reset_club_moods(g, game, rand); + european_setup(g, game, rand, cup_draw); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + if (pause) pause("the German entrants (CompetitionWinnerScreen)"); + european_fields(g, game, rand); + SeasonTaxState tax_state; + for (size_t m = 0; m < g.manager_teams.size() && !report.unsupported; m++) + season_accounts(g, int(m), game, rand, report, tax_hooks, tax_state); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + promotion(g, game, rand, report, pause, promotion_hook, allocator); // Void + if (report.unsupported) return SeasonTransitionOutcome::Failed; + // DailyInterest: the summer sanctions (SeasonEvent, Season_SeasonAccounts_RuntimeField) take effect + if (g.memory.has(::bmh::layout::Season_SeasonAccounts_RuntimeField)) + for (size_t m = 0; m < g.manager_teams.size(); m++) rec8(g, int(m), 0x220) = g.memory.u8(::bmh::layout::Season_SeasonAccounts_RuntimeField + uint32_t(m)); + cup_field(g, game, pause, cup_draw); // CareerSeasonSetup(2) + // Getenv2: every club changes places with a random one of its league (the new + // fixtures), then the cup's ties are ordered again (Getenv(0x40, 0)) + auto trace = [&](const char* what) { + if (std::getenv("BMH_TRACE")) + std::printf(" [%s: game %llu, Watcom %llu draws so far]\n", what, (unsigned long long)game.calls(), + (unsigned long long)rand.calls()); + }; + trace("after the cup draw"); + shuffle_leagues(g, rand); + trace("after Getenv2"); + order_cup_ties(g, 0x40, 0); + season_players(g, game, rand, report); // CareerSeasonSetup3 + trace("after CareerSeasonSetup3"); + if (report.unsupported) return SeasonTransitionOutcome::Failed; + const auto outcome = season_end_steps(g, game, rand, report, highscore, allocator); + trace("after the day steps"); + return outcome; +} + +} // namespace bmh + +namespace bmh { + +bool career_season_setup(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause, + const SeasonCupDrawHook& cup_draw) { + StaticMemory& mem = g.memory; + g.team_morale.at(0x165) |= 0x80; + for (int team = 0; team < 0x8a; team++) { + club_balance(g, team, rand); + auto_lineup(g, team, g.manager_of(team) >= 0 ? 0xe4 : 100); // (byte 100 - 0x80 for humans) + } + // the title holders of the cup entries (+0x22): none yet, the placeholder clubs + const uint16_t first_small = 90; // TeamsWithSquads + const uint16_t foreign = 189 + 138 + 30; // ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 + CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (0x165) + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField2, foreign); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField6, uint16_t(first_small + 7)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField, 7); + if (kEnglishCompetitions) mem.set16(::bmh::layout::CupTable + 28 * 0x28 + 0x22, 7); // (EN: the FA Cup proper, SeasonRuntimeField8) + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField5, uint16_t(first_small + 0x1f)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField4, uint16_t(first_small + 0x13)); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField3, uint16_t(foreign + 1)); + mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, 0); + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, 0); + mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, 7); + mem.set16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField7, 7); + european_setup(g, game, rand, cup_draw); // CareerSeasonSetup(3) + if (report.unsupported) return false; + if (pause) pause("the German entrants (CompetitionWinnerScreen)"); + european_fields(g, game, rand); + cup_field(g, game, pause, cup_draw); + for (size_t m = 0; m < g.manager_teams.size(); m++) season_tickets(g, int(m), rand); // CareerSeasonSetup2 + order_cup_ties(g, 0x40, 0); + season_players(g, game, rand, report); // CareerSeasonSetup3 + return !report.unsupported; +} + +} // namespace bmh + +namespace bmh { + +bool career_first_steps(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + g.memory.set32(::bmh::layout::CareerSession_Invalid_RuntimeField2, uint32_t(game.seed())); // CareerFirstSteps2: CareerSession_Invalid_RuntimeField2 = CareerSession_Save_RuntimeField + g.memory.set8(::bmh::layout::ActiveManager, 4); + g.autosave_month = 7; // DailyInterest(0): SeasonRuntimeField27 + shuffle_leagues(g, rand); // Getenv2 + new_transfer_list_entries(g, rand, report); // CareerFirstSteps + return !report.unsupported; +} + +} // namespace bmh diff --git a/src/game/season.hpp b/src/game/season.hpp new file mode 100644 index 0000000..42db130 --- /dev/null +++ b/src/game/season.hpp @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#pragma once +// OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules. +// From one season to the next (BMH.exe V2.24 + supported rule profile patch). +// +// On 1 July the "Weiter" loop (DailyInterest) ends the season: CareerSession_RuntimeError_RuntimeField4 = 1, the season +// bonuses (SeasonAwards) and the manager's desk "Saisonende". When he leaves it with +// "Anstoss" the offers still open for his players are answered (DispatchClubPlayerPendingOffers, from +// AdvanceTurn) and the new season is set up (the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest): +// season + 1 (SeasonIndex), the clubs' moods and flags (ClubBalance), the European +// cups and their foreign clubs (CareerSeasonSetup(1)), contracts (GameEndTaxAnimationScreen, Void), +// the league tables to the cups (CareerSeasonSetup(2)), the German clubs in Europe shown +// (SeasonOperation), the national cup draw (Getenv), promotion and relegation +// (CareerSeasonSetup3, SeasonEndSteps), the managers' season records (ManagerOf), the day steps +// up to the first Wednesday and the new transfer list (CareerFirstSteps); the season day +// DaysIntoSeason restarts at 0. +// Annual accounts expose the Original acknowledgement/decision boundary before +// booking tax. Headless callers without a selector use the Original NO branch. + +#include +#include +#include + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh { + +enum class SeasonTaxEventKind { notice, question, animation, outcome }; +struct SeasonTaxEvent { + SeasonTaxEventKind kind = SeasonTaxEventKind::notice; + int manager_slot = -1; + int team = -1; + int32_t profit = 0; + int32_t legal_tax = 0; + int32_t paid_tax = 0; + int32_t fine = 0; + int animation_variant = 0; + bool caught = false; + std::string text; // owned Original-encoding text, prepared by the accounting engine +}; +struct SeasonTaxHooks { + std::function observe; + std::function choose; +}; +// SeasonProfitTax continues GameEndTaxAnimationScreen's loop without reinitialising its local fine. +// This state lives for one annual-accounts pass across all human managers. +struct SeasonTaxState { + int32_t carried_fine = 0; +}; + +// CupDrawFromGame: the generated order, then Getenv/CupGroupOverviewEffects. +// Participants are owned copies of the current round at each boundary. +enum class SeasonCupDrawPhase { draw, overview }; +struct SeasonCupDrawEvent { + SeasonCupDrawPhase phase = SeasonCupDrawPhase::draw; + uint32_t entry_address = ::bmh::layout::CupTable; + int competition = 0; + int round = 0; + int offset = 0; + uint8_t flags = 0; + bool group_stage = false; + int group_index = 0; + int group_count = 0; + size_t count = 0; + std::vector participants; + struct GroupAverageSnapshot { + uint16_t runtime_id = 0; + std::array values{}; + }; + // Void6 calls TeamRating for owned foreign teams at the live Source + // boundary. The overview owns those values so a renderer never rerolls. + std::vector group_average_snapshots; +}; +using SeasonCupDrawHook = std::function; + +// DispatchClubPlayerPendingOffers (the loop at the end of AdvanceTurn): the offers for players of human +// manager `manager` (OfferSlots) are answered. A salary demand (a club tries to lure the +// player away) is accepted with `accept`: the board salary becomes the offered one and +// its percentage of the market salary is noted (+0xd). Declining it needs the transfer +// (IncomingTransferScreen) and is reported. A fee offer opens the negotiation screen (IncomingTransferScreen / +// OpenTransferEditor), which restarts the game generator from CareerSession_Invalid_RuntimeField2 and draws the +// negotiator's picture; with `game` the manager refuses the release (right click, the +// message box "Sie verweigern dem Spieler die Freigabe!"). A transfer_decision callback +// may accept a fee offer. Interactive Main uses process_natural_pending_offers_after_desk +// with its typed presenters and shared human-buyer settlement instead of this legacy API. +// (The offer slots are freed by free_offer_slots after all desks.) +void answer_offers(GameState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report, + GameRandom* game = nullptr); +// The end of the desk loop of AdvanceTurn, after every manager's desk and answers: the four +// offer slots (transfer list entries 0x28..0x2b, OfferSlots) are freed. +void free_offer_slots(GameState& g); + +// OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules. +// YouthAcademyPlayer (supported rule profile youth academy, season accounts): when manager `m` paid the academy in +// full this season (+0x880) and has room, a young player of a computer club joins his squad +// with values by the league (see season.cpp). Returns whether one came. +bool youth_academy_player(GameState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubBalance(0): every club's mood (TeamMorale, W(20, 30)) and flags (*TeamFlags): a random +// base, two levels from the final table position (title holders get the top one) with +// random exceptions, and two from the balance of its squad (CareerSeasonSetup4). +// CareerSeasonSetup4(team): bits 8-11 of the club flags from the balance of its squad (W draws). +void club_balance(GameState& g, int team, WatcomRandom& rand); + +// The end of InitializeCareer (a new career, after the managers): the national team flag, every +// league club's balance (CareerSeasonSetup4) and automatic line-up (humans with the bit 0x80), +// the title holders of the cups, CareerSeasonSetup(3) (international tournament, European +// entrants, national cup field), the season tickets (CareerSeasonSetup2), Getenv(0x40, 0) and +// the players' season (CareerSeasonSetup3). +// `pause` is called at the screens the original waits at (as in season_transition). +bool career_season_setup(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause = nullptr, + const SeasonCupDrawHook& cup_draw = {}); + +// CareerFirstSteps2 after InitializeCareer and the start of DailyInterest(0): the game generator's seed is +// saved (CareerSession_Invalid_RuntimeField2), the clubs of each league change places at random (Getenv2) and the +// transfer list gets its first players (CareerFirstSteps). The "Weiter" loop then prepares the +// first event (AdvanceTurn) up to the first desk. +bool career_first_steps(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubsChangePlaces(a, b): two clubs (ids below 168) change places in every table per club id. +void clubs_change_places(GameState& g, int a, int b); + +// With `new_career` (ClubBalance(1), start of a career) both levels are 1 for every club and +// the position draws are skipped. +void reset_club_moods(GameState& g, GameRandom& game, WatcomRandom& rand, bool new_career = false); + +// The CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest (see above). Missing runtime context or +// invalid state is reported through MinuteReport; presenters are supplied by the caller. +// `pause` is called where the original waits for the manager (a screen): week_check compares +// the recorded pauses there. +enum class SeasonTransitionOutcome { NextSeason, CareerComplete, Failed }; +// Void -> SeasonPromotionScreen: already computed local lists, before swaps. +// The arrays are owned; only their first `count` entries are displayed/swapped. +// In group 1 without play-offs, count may be smaller than relegated.size(). +struct SeasonPromotionEvent { + int group = 0; // 0..3: first division, second, both third divisions, fourth + size_t count = 0; + std::vector relegated; + std::vector promoted; +}; +using SeasonPromotionHook = std::function; +using SeasonHighscoreHook = std::function; + +SeasonTransitionOutcome season_transition(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + const std::function& pause = {}, + const SeasonHighscoreHook& highscore = {}, + const SeasonTaxHooks& tax_hooks = {}, + const SeasonPromotionHook& promotion_hook = {}, + const SeasonCupDrawHook& cup_draw = {}, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// GameEndTaxAnimationScreen/SeasonProfitTax profit branch: show ACK, ask JA/NEIN, perform its exact RNG +// and sanctions, then store the carry values and debit tax plus any fine once. +// The caller supplies the already rounded seasonal profit, before ticket income. +void season_apply_profit_tax(GameState& g, int manager, int32_t profit, + GameRandom& game, WatcomRandom& rand, + const SeasonTaxHooks& hooks = {}, + SeasonTaxState* continuation = nullptr); + +// GameEndTaxAnimationScreen / SeasonProfitTax: progressive tax on a rounded seasonal profit. +// Exposed so the threshold and integer-rounding rules can be tested directly. +int32_t season_profit_tax(int32_t profit); +// GameEndTaxAnimationScreen: next-season tax refund after a lower profit; returns zero when +// the original conditions do not grant a refund. +int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit, + int32_t previous_tax_paid); + +// SeasonAwards, on 1 July before the "Saisonende" desk: per league (< 5) the club of the +// top scorer (goals), of the best scorer (goals + assists, list Season_List_RuntimeField) and the fair +// play winner (fewest card points); a human manager's club gets the prize (SeasonRuntimeField26) +// with a message. +void season_awards(GameState& g); + +// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): the +// running competitions' slot 4 (this year's international tournament), the manager's screen +// state and the friendlies 0xc while their entry 30 has teams. +void cup_overview_effects(GameState& g); +// CupGroupOverviewEffects's group cursor is owned by this stage entry; the national cup's +// existing overview path intentionally keeps its original effects unchanged. +void cup_group_overview_effects(GameState& g, int group_index); + +// LeagueName: the name of a league below 5 (with its letter, e.g. for the third divisions). +std::string league_name(const GameState& g, int league); + +// MonthChange(absolute squad slot): the player leaves his club for the free agents with new +// values (W and game draws) and an age W(4, 15); his club closes the gap (ReleasePlayer, +// with a human club its tactics board as well). False if the source ownership/state +// cannot be validated; the player movement and human board compaction are implemented. +bool release_player(GameState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh diff --git a/src/game/source_tip.cpp b/src/game/source_tip.cpp new file mode 100644 index 0000000..da80b09 --- /dev/null +++ b/src/game/source_tip.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/source_tip.hpp" + +#include +#include + +namespace bmh { + +uint8_t source_tip_result(GameRandom& game, const std::array& gap, + int home_rating, int away_rating, + int home_secondary, int away_secondary) { + uint8_t home = uint8_t((away_secondary + 0x14 < home_secondary) + game.range(0, 1)); + uint8_t away = uint8_t((away_secondary < home_secondary) + game.range(0, 1)); + const uint32_t wrapped = uint32_t(home_rating) - uint32_t(away_rating); + const int32_t signed_difference = std::bit_cast(wrapped); + int32_t scaled = signed_difference / 10; + if (scaled < 0) scaled = -scaled; + uint8_t local_c = uint8_t(scaled); + if (home_rating > away_rating) { + if (local_c > 9) local_c = 9; + home = uint8_t(home + game.range(0, int(gap[local_c]) + 1)); + } + if (home_rating < away_rating) { + // ComputeLeagueTableForecast negates the byte before clamping it to the gap table. + local_c = uint8_t(-int(local_c)); + if (local_c > 9) local_c = 9; + away = uint8_t(away + game.range(0, int(gap[local_c]))); + if (local_c < 5) home = uint8_t(home + 1); + } + for (;;) { + const int cap = game.range(2, 6); + if (int(home) + int(away) <= cap) break; + if (home) --home; + if (away) --away; + } + return uint8_t((home << 4) | away); +} + +} // namespace bmh diff --git a/src/game/source_tip.hpp b/src/game/source_tip.hpp new file mode 100644 index 0000000..e5d1450 --- /dev/null +++ b/src/game/source_tip.hpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include + +#include "game/random.hpp" + +namespace bmh { + +// ComputeLeagueTableForecast's pure score arithmetic after the caller has obtained the four +// QuoteNationalFriendlyMatch ratings. Each invocation consumes the same G draws, including +// the final goal-cap draw that terminates the loop. +uint8_t source_tip_result(GameRandom& game, const std::array& gap, + int home_rating, int away_rating, + int home_secondary, int away_secondary); + +} // namespace bmh diff --git a/src/game/sportschau_awards.cpp b/src/game/sportschau_awards.cpp new file mode 100644 index 0000000..06e1c36 --- /dev/null +++ b/src/game/sportschau_awards.cpp @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/sportschau_presentation.hpp" +#include +#include "game/matchday.hpp" +#include "game/messages.hpp" +#include "game/season.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +std::optional matchday_intro_view(const GameState& state, + const std::vector& groups) { + if (groups.empty() || !state.memory.has(::bmh::layout::SportschauAwards_MatchdayIntroView_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_MatchdayIntroView_RuntimeField) != 0) + return std::nullopt; + MatchdayIntroView view; int previous_type = 100; + for (const auto& group : groups) { + const int type = group.desc.at(0); + // Original emits every league, but only the first adjacent cup type. + if (type != 0 && type == previous_type) continue; + previous_type = type; + std::string name; + if (type == 0) { + const uint32_t league = le32(group.desc, 0xcc); + if (league >= 9) throw FormatError("matchday intro: invalid Source league"); + // LeagueName with TeamStatistics_SourceLeagueName_RuntimeField=1 includes the secondary-league prefix. + name = league < 5 ? league_name(state, int(league)) : + message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(0x165 + int(league) - 4); + } else { + if (type > 14) throw FormatError("matchday intro: invalid Source competition type"); + name = message_text(state, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(type) * 4); + // StrcpySoHallReplacesItsCurrentTournament is strcpy, so Hall replaces its current tournament name. + if (type == 12) name = message_text(state, ::bmh::layout::MatchdayResults_CompetitionName_TextPointer); + } + view.competition_names.push_back(std::move(name)); + } + return view; +} + +std::string sportschau_competition_title(const GameState& state, const MatchGroup& group) { + const uint32_t id = le32(group.desc, 0xcc); + int index = int(id); + if (id > 20) index = state.memory.u8(id + 0x18) + 9; + else if (index >= 9) index = std::min(index + 12, 19); + if (index < 5) return league_name(state, index); + if (index < 9) return state.club_name(0x165 + index - 4); + return message_text(state, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(index - 9) * 4); +} + +std::optional sportschau_team_info_view(const GameState& state, + const MatchGroup& group, int group_index) { + const int setting = sportschau_source_setting_index(state, group); + if (!state.memory.has(::bmh::layout::SportschauAwards_SportschauTeamInfoView_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_SportschauTeamInfoView_RuntimeField) != 0 || + setting < 0 || setting >= 20 || !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) || + state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return std::nullopt; + if (group_index < 0 || group_index > 255) throw FormatError("sportschau: invalid team info group"); + SportschauTeamInfoView view; + view.group = uint8_t(group_index); view.competition_id = le32(group.desc, 0xcc); + view.competition_title = sportschau_competition_title(state, group); + // Eligible C4 already guarantees SportschauIntro's any-group predicate. B7 + // controls loading KB57 even when C7 suppresses the intro animation. + view.source_backdrop_available = state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField) && state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField) == 0; + for (size_t i = 0; i < 4; ++i) view.totals[i] = int32_t(le32(group.desc, 0xbc + i * 4)); + return view; +} + +std::optional finish_sportschau_awards(GameState& state, + const MatchGroup& group, int group_index) { + for (size_t i = 0; i < 11; ++i) if (group.desc.at(0x70 + i) == 0) return std::nullopt; + // The award-statistic update is movzbl [descriptor+70], not the displayed slot word. + // Preserve the Original statistic even if its presentation is disabled. + for (size_t i = 0; i < 11; ++i) { + const int manager = state.manager_of(slot_team(group.desc.at(0x70 + i))); + if (manager >= 0) { + auto& counter = state.manager_records.at(size_t(manager) * 0xb0c + 0x21e); + counter = uint8_t(counter + 1); + } + } + const int setting = sportschau_source_setting_index(state, group); + if (!state.memory.has(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) != 0 || + setting < 0 || setting >= 20 || !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) || + state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return std::nullopt; + if (group_index < 0 || group_index > 255) throw FormatError("sportschau: invalid awards group"); + SportschauAwardsView view; + view.group = uint8_t(group_index); view.competition_id = le32(group.desc, 0xcc); + view.competition_title = sportschau_competition_title(state, group); + view.source_backdrop_available = state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField) && state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField) == 0; + for (size_t i = 0; i < 11; ++i) { + auto& p = view.players[i]; + p.score = group.desc.at(0x70 + i); p.squad_slot = le16(group.desc, 0x9c + i * 2); + p.player_id = state.squad_slots.at(p.squad_slot) & 0xfff; + p.team_id = int16_t(slot_team(int16_t(p.squad_slot))); + p.player_name = state.player_name(p.player_id); p.club_name = state.club_name(p.team_id); + } + return view; +} + +} // namespace bmh diff --git a/src/game/sportschau_presentation.hpp b/src/game/sportschau_presentation.hpp new file mode 100644 index 0000000..cd08ec7 --- /dev/null +++ b/src/game/sportschau_presentation.hpp @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +// Immutable, source-word-preserving input to Sportschau presentation callbacks. +// Presentation callbacks remain immutable; Source replay and award work have +// separate Core owners, independent of whether a UI observer is installed. + +#include +#include +#include +#include +#include +#include + +#include "game/presentation.hpp" +#include "game/match_engine.hpp" + +namespace bmh { + +struct GameState; +struct MatchGroup; +class WatcomRandom; +class LeImage; + +// MatchdayIntro walks the group's flat 16-bit log in two-word steps. The third +// word it reads is a look-ahead into the next record, and some codes consume +// that next pair as a secondary player/distance. Keep both the decoded fields +// and exact words so a presenter cannot accidentally reinterpret the stream. +struct SportschauLogEvent { + uint8_t group = 0; + uint8_t fixture = 0; + uint16_t event_ordinal = 0; // ordinal after filtering this fixture's teams + uint16_t source_word_index = 0; // index of the first word in MatchGroup::log + uint16_t source_code_player_word = 0; + uint16_t source_team_value_word = 0; + uint8_t source_code = 0; // high four bits of the first word + uint16_t player_id = 0x0fff; + int16_t team_id = -1; + uint8_t source_value = 0; // low seven bits of the second word + bool consumes_following_pair = false; // source codes 0 (goal) and 1 (miss) + bool has_following_word = false; + bool has_following_pair = false; + uint16_t following_code_player_word = 0; + uint16_t following_team_value_word = 0; + std::vector player_name; // Original encoded bytes + std::vector following_player_name; // empty when no valid look-ahead player +}; + +struct SportschauFixtureView { + uint8_t group = 0; + uint8_t fixture = 0; + uint8_t competition_type = 0; + uint8_t fixture_flags = 0; + uint8_t source_footer_variant = 0; // MatchdayIntro local_44: 0 normal,1 extra-time,2 indoor + bool has_replay_progression_mode = false; + uint8_t replay_progression_mode = 0; // saved byte; controls selected-progressive scene path + bool has_replay_chance_mode = false; + uint8_t replay_chance_mode = 0; // saved byte; controls selected scene/panel restoration + bool source_selection_available = false; + bool source_selected = false; // ResetSportschauSelection(pair,1), resolved from pre-match state + uint32_t competition_id = 0; + int16_t source_setting_index = -1; // SportschauPresentationOperation(desc,5), or -1 if unavailable + int16_t home_team = -1; + int16_t away_team = -1; + uint8_t source_played_minute = 0; // descriptor +0x04, indexed by Source fixture ordinal + uint16_t home_badge_word = 0xffff; // raw ClubBadgeSelectors u16 consumed by SourceBadgeFallback + uint16_t away_badge_word = 0xffff; + bool score_known = false; + uint8_t home_goals = 0; + uint8_t away_goals = 0; + std::vector home_name; // Original encoded bytes + std::vector away_name; // Original encoded bytes + std::vector home_short_name; // exact ClubShortNameOffsets substring for team ids < 168 + std::vector away_short_name; + bool home_short_name_available = false; + bool away_short_name_available = false; + bool home_name_requires_font_fit = true; // caller trims by two bytes until FNT3 width < 48 + bool away_name_requires_font_fit = true; + bool home_name_requires_longest_word = false; // TextWidth foreign-team branch, team >= 168 + bool away_name_requires_longest_word = false; + std::vector log_events; // Source log order, fixture-filtered + std::vector show_events; // Distinct live-animation stream, not the report log +}; + +struct SportschauCompetitionView { + uint8_t group = 0; + uint8_t type = 0; + uint32_t id = 0; + int16_t source_setting_index = -1; +}; + +struct SportschauIntroView { + int group_index = -1; // -1 post-simulation, otherwise a Source group-entry point + std::vector groups; +}; + +// FinishEvent's pre-play KB136 competition list, independent of report selection. +struct MatchdayIntroView { + std::vector competition_names; // Original encoded bytes +}; +using MatchdayIntroHook = std::function; +std::optional matchday_intro_view(const GameState&, + const std::vector&); + +// Intro gets all group competition ids so App can evaluate Source's global +// setting-matrix eligibility test without guessing from the current fixture. +using SportschauIntroHook = std::function; +using SportschauFixtureHook = std::function; + +struct SportschauAwardPlayer { + uint16_t squad_slot = 0, player_id = 0x0fff; + int16_t team_id = -1; + uint8_t score = 0; + std::string player_name, club_name; // Original encoded bytes +}; +struct SportschauAwardsView { + uint8_t group = 0; + uint32_t competition_id = 0; + std::string competition_title; // Void4, Original encoded bytes + bool source_backdrop_available = true; // SportschauIntro/5c1c7, independent of C7 animation + std::array players; +}; +using SportschauAwardsHook = std::function; +// SportschauEleven: complete-eleven gate, Source manager counter, then pure viewer input. +// The statistic reads the score byte as a slot (confirmed in x86), whereas +// the displayed names use the separate u16 squad-slot array at descriptor+9c. +std::optional finish_sportschau_awards(GameState& state, + const MatchGroup& group, int group_index); + +struct SportschauTeamInfoView { + uint8_t group = 0; + uint32_t competition_id = 0; + std::string competition_title; + bool source_backdrop_available = true; + // Source descriptor +bc,+c0,+c4,+c8: yellow, red, spectators, goals. + std::array totals{}; +}; +using SportschauTeamInfoHook = std::function; +std::string sportschau_competition_title(const GameState& state, const MatchGroup& group); +std::optional sportschau_team_info_view(const GameState& state, + const MatchGroup& group, int group_index); + +struct SportschauReportStep { + size_t visible_log_entries = 0; + uint8_t progress_minute = 0; + bool minute_wait = false; + bool chance_wait = false; + bool terminal_wait = false; +}; +std::vector sportschau_report_steps(const SportschauFixtureView& fixture); + +struct SportschauSceneView { + SportschauReportStep report_step; + int home_goals_before = 0, away_goals_before = 0; + std::vector groups; // owned single-group context; shot.group ==0 + std::optional set_piece; + LiveShotEvent shot; +}; +struct SportschauReplayHooks { + // Return only the Source left=2 latch; Core applies it after a minute wait. + std::function step; + std::function scene; +}; + +// CompetitionWinnerScreen(param1=0), called at title settlement before title-history writes. +struct CompetitionWinnerView { uint8_t title = 0; uint16_t team = 0; }; +using CompetitionWinnerHook = std::function; + +struct SportschauPresentationHooks { + CompetitionWinnerHook winner; + MatchdayIntroHook kickoff; + SportschauIntroHook intro; + SportschauFixtureHook fixture; + SportschauReplayHooks replay; + SportschauAwardsHook awards; + SportschauTeamInfoHook team_info; +}; + +struct SportschauRatingTables { + std::array position_limit{}, opponent_misses{}, chance_actor{}, own_chances{}, scorer_bonus{}; + std::array award_begin{}, award_end{}; + uint16_t domestic_teams = 0; +}; +SportschauRatingTables sportschau_rating_tables(const LeImage& exe); +// MatchdayIntro, after replay and before morale/development. Updates eleven Source +// award scores and global squad-slot ids in the group's descriptor, not players. +void rate_sportschau_players(const GameState& state, MatchGroup& group, + const SportschauFixtureView& fixture, WatcomRandom& rand, const SportschauRatingTables& tables); + +struct SportschauSourceOptions { + uint8_t intro_after_matchday = 0; // unsaved EXE byte CareerSession_SportschauSourceOptions_ExecutableField + uint8_t intro_each_group = 0; // unsaved EXE byte CareerSession_DispatchTransferOffer_ExecutableField2 + uint16_t rated_club_threshold = 90; // EXE TeamsWithSquads, ResetSportschauSelection's extra fifty points + std::optional ratings; // loaded EXE policy, not FBM data +}; + +// Read-only projection for one already-completed fixture. Source's flat log is +// filtered by the two fixture teams, while its pair stride and look-ahead words +// remain intact. This helper does not mutate Native state or either RNG. +SportschauFixtureView sportschau_fixture_view(const GameState& state, const MatchGroup& group, + int group_index, int fixture_index, + const std::vector& show_events); +int sportschau_source_setting_index(const GameState& state, const MatchGroup& group); + +// ResetSportschauSelection modes0/2/1. Only the pre-match caller may rate candidates; foreign +// teams consume the real Watcom generator even with capacity A8 ==0. +void reset_sportschau_selection(GameState& state); +bool consider_sportschau_fixture(GameState& state, const MatchGroup& group, + int home, int away, WatcomRandom& rand); +bool sportschau_selected(const GameState& state, int home); + +// MatchdayIntro/ShotAnimation: owns scene draws between table updates and morale. +// With no UI callbacks, it still consumes the same enabled Source scene work. +void present_sportschau_replay(GameState& state, const MatchGroup& group, + const SportschauFixtureView& fixture, GameRandom& game, WatcomRandom& rand, + const SportschauReplayHooks& hooks); + +} // namespace bmh diff --git a/src/game/sportschau_rating.cpp b/src/game/sportschau_rating.cpp new file mode 100644 index 0000000..bf44bd5 --- /dev/null +++ b/src/game/sportschau_rating.cpp @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/sportschau_presentation.hpp" + +#include +#include +#include "formats/le.hpp" + +namespace bmh { + +SportschauRatingTables sportschau_rating_tables(const LeImage& exe) { + SportschauRatingTables t; + t.domestic_teams = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField); + for (size_t i = 0; i < 4; ++i) { + const auto offset = uint32_t(i); + t.position_limit[i] = std::bit_cast(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField + offset)); + t.opponent_misses[i] = std::bit_cast(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField2 + offset)); + t.chance_actor[i] = std::bit_cast(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField3 + offset)); + t.own_chances[i] = std::bit_cast(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField4 + offset)); + t.scorer_bonus[i] = std::bit_cast(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField5 + offset)); + t.award_begin[i] = exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField6 + offset); + t.award_end[i] = exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField7 + offset); + if (t.award_begin[i] >= t.award_end[i] || t.award_end[i] > 11 || + (i && t.position_limit[i] <= t.position_limit[i - 1])) + throw FormatError("sportschau: invalid executable award tables"); + } + return t; +} + +void rate_sportschau_players(const GameState& state, MatchGroup& group, + const SportschauFixtureView& fixture, WatcomRandom& rand, const SportschauRatingTables& t) { + // F7, D7, E7 and selected status only gate presentation. G7/C4 gate the + // rating even with the report hidden or skipped (5cd8a, 5c389). + if (!state.memory.has(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) != 0 || + fixture.source_setting_index < 0 || fixture.source_setting_index > 19 || + !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) || + state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) != 0) return; + + struct Actors { + uint8_t goals = 0, misses = 0; + std::vector scorers, assistants, missed; + }; + std::array actors; + auto add = [](std::vector& ids, uint16_t id) { + if (ids.size() < 12) ids.push_back(id); // independent twelve-entry buffers + }; + for (size_t i = 0; i + 1 < group.log.size(); i += 2) { + const int team = group.log[i + 1] >> 7; + if (team != fixture.home_team && team != fixture.away_team) continue; + auto& a = actors[size_t(team == fixture.away_team)]; + const int code = group.log[i] >> 12; + const uint16_t player = group.log[i] & 0xfff; + if (code > 1) continue; + if (code == 0) { ++a.goals; add(a.scorers, player); } + else { ++a.misses; add(a.missed, player); } + const bool following = i + 2 < group.log.size(); + const int following_code = following ? group.log[i + 2] >> 12 : 0; + const int kind = following && following_code > 6 ? following_code - 6 : 0; + i += 2; // both chance codes consume the next record, regardless of its team + if (i < group.log.size() && (following_code < 3 || following_code > 6)) { + const uint16_t assistant = group.log[i] & 0xfff; + if (assistant != 0xfff && (kind == 0 || kind == 3)) add(a.assistants, assistant); + } + } + + for (size_t side = 0; side < 2; ++side) { + const int team = side ? fixture.away_team : fixture.home_team; + if (team < 0 || team >= t.domestic_teams) continue; + const auto squad = squad_range(team); + const auto& a = actors[side]; const auto& opponent = actors[1 - side]; + for (size_t row = 0; row < squad.count; ++row) { + const uint16_t id = state.squad_slots.at(squad.first + row) & 0xfff; + if (id == 0xfff) continue; + const uint32_t flags = state.players.at(id).w364; + if ((flags & 0x1000) == 0 || ((flags >> 16) & 0x1f) != 0) continue; + int16_t score = int16_t(rand.range(0, 7) + 5); + int depth = 0, lane = 0; + state.formation_position(team, int(row), depth, lane); + size_t profile = 0; + while (profile < 4 && depth >= t.position_limit[profile]) ++profile; + if (profile == 4) throw FormatError("sportschau: formation depth outside award profiles"); + auto plus = [&](int value) { score = std::bit_cast(uint16_t(uint16_t(score) + value)); }; + plus((int(opponent.misses) - int(opponent.goals)) * t.opponent_misses[profile]); + int goals = 0; + if (t.chance_actor[profile]) { + if (profile == 1) plus(rand.range(0, 4)); + goals = int(std::count(a.scorers.begin(), a.scorers.end(), id)); + const int assists = int(std::count(a.assistants.begin(), a.assistants.end(), id)); + const int misses = int(std::count(a.missed.begin(), a.missed.end(), id)); + plus((goals + assists - misses) * t.chance_actor[profile]); + } + // SportschauRating_SportschauRatingTables_RuntimeField4 is a predicate, not a multiplier (5cf77..5cf8e). + if (t.own_chances[profile]) plus(int(a.goals) + int(a.misses)); + plus(goals * t.scorer_bonus[profile]); + + int minimum = 120; size_t selected = 0; + for (size_t slot = t.award_begin[profile]; slot < t.award_end[profile]; ++slot) { + const int prior = group.desc.at(0x70 + slot); + if (prior < minimum) { minimum = prior; selected = slot; } + } + // Equal scores replace the first minimum; score storage wraps to + // one byte. The u16 identity is a GLOBAL squad slot, not a player id. + if (score >= minimum) { + group.desc.at(0x70 + selected) = uint8_t(score); + const uint16_t slot = uint16_t(squad.first + row); + group.desc.at(0x9c + selected * 2) = uint8_t(slot); + group.desc.at(0x9d + selected * 2) = uint8_t(slot >> 8); + } + } + } +} + +} // namespace bmh diff --git a/src/game/sportschau_replay.cpp b/src/game/sportschau_replay.cpp new file mode 100644 index 0000000..8ec1b30 --- /dev/null +++ b/src/game/sportschau_replay.cpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/sportschau_presentation.hpp" + +namespace bmh { + +std::vector sportschau_report_steps(const SportschauFixtureView& fixture) { + std::vector steps{{0, 0, false, false}}; + uint16_t cursor = 1; + size_t visible = 0; + int baseline = 66; + while (visible < fixture.log_events.size()) { + const auto& event = fixture.log_events[visible]; + while (cursor < event.source_value) + steps.push_back({visible, uint8_t(cursor++), true, false}); + ++visible; + if (event.consumes_following_pair && visible < fixture.log_events.size() && + fixture.log_events[visible].source_word_index == event.source_word_index + 2) + ++visible; + if (baseline < 179) + steps.push_back({visible, uint8_t(cursor - 1), false, event.source_code < 2}); + if (event.source_code != 1) baseline += 7; + } + while (cursor <= fixture.source_played_minute) + steps.push_back({visible, uint8_t(cursor++), true, false, true}); + return steps; +} + +void present_sportschau_replay(GameState& state, const MatchGroup& group, + const SportschauFixtureView& fixture, GameRandom& game, WatcomRandom& rand, + const SportschauReplayHooks& hooks) { + if (!fixture.source_selection_available || !fixture.source_selected || + !fixture.has_replay_progression_mode || fixture.replay_progression_mode != 0 || + !state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField3) || state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField3) != 0 || + fixture.source_setting_index < 0 || fixture.source_setting_index > 19 || + !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) || + state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) != 0) return; + bool progressive = true; + for (const auto& step : sportschau_report_steps(fixture)) { + if (!progressive) continue; + const bool skip = hooks.step && hooks.step(state, fixture, step); + if (step.minute_wait && !step.terminal_wait && skip) progressive = false; + if (!step.chance_wait || !progressive || !fixture.has_replay_chance_mode || fixture.replay_chance_mode != 0) + continue; + const SportschauLogEvent* chance = nullptr; + int home_before = 0, away_before = 0; + for (size_t i = 0; i < step.visible_log_entries; ++i) { + const auto& event = fixture.log_events[i]; + const bool paired = event.consumes_following_pair && i + 1 < step.visible_log_entries && + fixture.log_events[i + 1].source_word_index == event.source_word_index + 2; + if (i + (paired ? 2 : 1) == step.visible_log_entries) chance = &event; + else if (event.source_code == 0) { + if (event.team_id == fixture.home_team) ++home_before; else ++away_before; + } + if (paired) ++i; + } + if (!chance || chance->source_code > 1 || chance->group != fixture.group || + chance->fixture != fixture.fixture || (chance->team_id != fixture.home_team && + chance->team_id != fixture.away_team)) throw FormatError("sportschau: invalid Source chance owner"); + const int side = chance->team_id == fixture.home_team ? 0 : 1; + const int kind = chance->has_following_word && (chance->following_code_player_word >> 12) > 6 + ? (chance->following_code_player_word >> 12) - 6 : 0; + if (kind > 3) throw FormatError("sportschau: unsupported Source set-piece code"); + SportschauSceneView scene; + scene.report_step = step; + scene.home_goals_before = home_before; scene.away_goals_before = away_before; + scene.groups = {group}; + std::vector referees; + MatchEngine engine{state, scene.groups, game, rand, referees}; + engine.live_set_piece = [&](const LiveSetPieceEvent& event) { scene.set_piece = event; }; + engine.live_shot = [&](const LiveShotEvent& event) { scene.shot = event; }; + if (kind) engine.set_piece_animation(kind, 0, 1 - side, 0, fixture.fixture, chance->source_value); + engine.shot_animation(chance->source_code == 1, kind == 2, side, 0, fixture.fixture, chance->source_value); + // The presentation adapter owns the unsaved music/ambience transition; + // the replay itself introduces no sound-related RNG or Native writes. + if (hooks.scene) hooks.scene(state, fixture, scene); + } +} + +} // namespace bmh diff --git a/src/game/stadium_blocks.cpp b/src/game/stadium_blocks.cpp new file mode 100644 index 0000000..4d392e1 --- /dev/null +++ b/src/game/stadium_blocks.cpp @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/stadium_blocks.hpp" + +#include "game/matchday.hpp" + +#include +#include + +namespace bmh { +namespace { +constexpr size_t kRecordSize = 0xb0c; +constexpr size_t kManagerClub = 0x290; +constexpr size_t kBuild = 0x34; +constexpr size_t kFlags = 0x44; +constexpr size_t kCapacity = 0x4c; +constexpr size_t kFutureCapacity = 0x54; +constexpr uint8_t kSeat = 1; +constexpr uint8_t kRoof = 2; +constexpr uint8_t kKnownFeatures = kSeat | kRoof; + +bool slot_index(StadiumBlockSlot slot, size_t& out) { + const auto raw = static_cast(slot); + if (raw >= 8) return false; + out = raw; + return true; +} + +uint16_t record_u16(const std::vector& records, size_t at) { + return uint16_t(records.at(at)) | uint16_t(records.at(at + 1)) << 8; +} + +std::optional checked_component(uint32_t price_per_1000, uint32_t places, + uint32_t multiplier, uint32_t divisor) { + const uint64_t units = places / 1000; + const uint64_t multiplied = uint64_t(price_per_1000) * units * multiplier; + if (multiplied > uint64_t(std::numeric_limits::max())) return std::nullopt; + return uint32_t(multiplied / divisor); +} + +bool valid_resolved_offer(const StandBlockOffer& offer, const StadiumBlockExpansionQuote& quote) { + if (offer.percent < 6 || offer.percent > 14 || offer.base_price != quote.base_price || + offer.base_days != quote.base_weeks || offer.base_days < 0 || offer.base_days > 255 || + offer.offered_price != uint32_t(uint64_t(quote.base_price) * uint32_t(100 + offer.percent) / 100) || + offer.price > uint32_t(std::numeric_limits::max())) + return false; + switch (offer.decision) { + case StandBlockOfferDecision::Declined: + return offer.price == offer.base_price && offer.construction_days == offer.base_days; + case StandBlockOfferDecision::Accepted: + // PrepareStandBlockOffer forms base_price * (100 + percent) in a signed + // 32-bit intermediate before dividing by 100. Do not accept a + // mathematically representable final uint32 when that Source + // intermediate would overflow. Declined offers do not use it. + return uint64_t(quote.base_price) * uint32_t(100 + offer.percent) <= + uint64_t(std::numeric_limits::max()) && + offer.price == offer.offered_price && + offer.construction_days <= offer.base_days - (offer.base_days >> 3) && + offer.construction_days >= offer.base_days - (offer.base_days >> 1); + case StandBlockOfferDecision::Pending: + default: + return false; + } +} +} // namespace + +std::optional quote_stadium_block_expansion( + const GameState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places, + uint8_t desired_features, int company_price_percent, + const StadiumBlockExpansionConstants& constants) { + size_t block = 0; + if (!slot_index(slot, block) || manager < 0 || + size_t(manager) >= g.manager_teams.size() || + (size_t(manager) + 1) * kRecordSize > g.manager_records.size()) + return std::nullopt; + const int club = g.manager_teams[size_t(manager)]; + const size_t rec = size_t(manager) * kRecordSize; + if (club < 0 || club == kNoTeam || record_u16(g.manager_records, rec + kManagerClub) != uint16_t(club)) + return std::nullopt; + + const uint8_t build_weeks = g.manager_records.at(rec + kBuild + block); + const uint8_t raw_flags = g.manager_records.at(rec + kFlags + block); + const uint8_t current_capacity = g.manager_records.at(rec + kCapacity + block); + const uint8_t future_capacity = g.manager_records.at(rec + kFutureCapacity + block); + const uint32_t maximum = constants.max_places[block]; + const uint32_t unit_price = constants.price_per_1000[block]; + const uint8_t duration = constants.weeks[block]; + + // Active construction and idle unknown bits are not editable A–H source states. + if (build_weeks != 0 || (raw_flags & uint8_t(~kKnownFeatures)) != 0 || + (desired_features & uint8_t(~kKnownFeatures)) != 0 || + (desired_features & uint8_t(raw_flags & kKnownFeatures)) != uint8_t(raw_flags & kKnownFeatures) || + company_price_percent < 0 || company_price_percent > 427 || unit_price == 0 || + maximum == 0 || maximum > 255000 || maximum % 1000 != 0 || duration == 0) + return std::nullopt; + + const uint32_t current_places = uint32_t(current_capacity) * 1000; + if (total_target_places < current_places || total_target_places > maximum || + total_target_places / 1000 > 255) + return std::nullopt; + const uint32_t new_places = total_target_places - current_places; + const auto new_cost = checked_component(unit_price, new_places, 1, 1); + if (!new_cost) return std::nullopt; + const uint32_t seats_places = (raw_flags & kSeat) != 0 ? new_places : total_target_places; + const uint32_t roof_places = (raw_flags & kRoof) != 0 ? new_places : total_target_places; + const auto seats_cost = (desired_features & kSeat) != 0 + ? checked_component(unit_price, seats_places, 45, 100) : std::optional(0); + const auto roof_cost = (desired_features & kRoof) != 0 + ? checked_component(unit_price, roof_places, 30, 100) : std::optional(0); + if (!seats_cost || !roof_cost) return std::nullopt; + + const uint64_t sum = uint64_t(*new_cost) + *seats_cost + *roof_cost; + if (sum > uint64_t(std::numeric_limits::max()) || + sum * uint32_t(company_price_percent) > uint64_t(std::numeric_limits::max())) + return std::nullopt; + const uint32_t price = uint32_t(sum * uint32_t(company_price_percent) / 100); + + StadiumBlockExpansionQuote quote; + quote.manager = manager; + quote.manager_club = club; + quote.slot = slot; + quote.current_build_weeks = build_weeks; + quote.current_raw_flags = raw_flags; + quote.current_capacity_thousands = current_capacity; + quote.current_future_capacity_thousands = future_capacity; + quote.total_target_places = total_target_places; + quote.desired_features = desired_features; + quote.company_price_percent = company_price_percent; + quote.price_per_1000 = unit_price; + quote.max_places = maximum; + quote.new_places = new_places; + quote.new_places_cost = *new_cost; + quote.seats_cost = *seats_cost; + quote.roof_cost = *roof_cost; + quote.undiscounted_cost = uint32_t(sum); + quote.base_price = price; + quote.base_weeks = duration; + return quote; +} + +bool build_stadium_block_expansion( + GameState& g, int manager, StadiumBlockSlot slot, + const StadiumBlockExpansionConstants& constants, + const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer, + WatcomRandom& rand, const ConstructionNoticeHook& payment_notice, + const SeasonTicketCompensationNoticeHook& compensation_notice) { + if (manager != quote.manager || slot != quote.slot || quote.base_price == 0 || + !valid_resolved_offer(resolved_offer, quote)) + return false; + const auto fresh = quote_stadium_block_expansion(g, manager, slot, quote.total_target_places, + quote.desired_features, quote.company_price_percent, constants); + if (!fresh || *fresh != quote) return false; + + // Sponsor is always false for Original A–H construction. In particular this + // preserves +0x171 and prevents pay_construction's sponsor-only W draws. + if (!pay_construction(g, manager, resolved_offer.price, false, rand, payment_notice)) return false; + + const size_t rec = size_t(manager) * kRecordSize; + const size_t block = static_cast(slot); + g.manager_records.at(rec + kBuild + block) = resolved_offer.construction_days; + g.manager_records.at(rec + kFlags + block) = uint8_t( + g.manager_records.at(rec + kFlags + block) | uint8_t(quote.desired_features << 4)); + g.manager_records.at(rec + kFutureCapacity + block) = uint8_t(quote.total_target_places / 1000); + season_ticket_compensation_source(g, manager, compensation_notice); + return true; +} + +} // namespace bmh diff --git a/src/game/stadium_blocks.hpp b/src/game/stadium_blocks.hpp new file mode 100644 index 0000000..671ea06 --- /dev/null +++ b/src/game/stadium_blocks.hpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/desk_actions.hpp" +#include "game/weekly.hpp" + +#include +#include +#include + +namespace bmh { + +// Source choices 8..15 map to eight independent A–H record slots. These must +// not be confused with StadiumInvestment's facilities 0..7. +enum class StadiumBlockSlot : uint8_t { A = 0, B, C, D, E, F, G, H }; + +struct StadiumBlockExpansionConstants { + std::array price_per_1000{}; + std::array weeks{}; + std::array max_places{}; +}; + +// An immutable quote binds the Source owner and every record/table value that +// affects the quote. Commit recomputes this value before it touches money. +struct StadiumBlockExpansionQuote { + int manager = -1; + int manager_club = -1; + StadiumBlockSlot slot = StadiumBlockSlot::A; + uint8_t current_build_weeks = 0; + uint8_t current_raw_flags = 0; + uint8_t current_capacity_thousands = 0; + uint8_t current_future_capacity_thousands = 0; + uint32_t total_target_places = 0; + uint8_t desired_features = 0; // Source low bits: seats=1, roof=2. + int company_price_percent = 0; + uint32_t price_per_1000 = 0; + uint32_t max_places = 0; + uint32_t new_places = 0; + uint32_t new_places_cost = 0; + uint32_t seats_cost = 0; + uint32_t roof_cost = 0; + uint32_t undiscounted_cost = 0; + uint32_t base_price = 0; + uint8_t base_weeks = 0; + bool operator==(const StadiumBlockExpansionQuote&) const = default; +}; + +// Pure Source projection. Manual totals need not be multiples of 1000; only the +// eventual +54 byte is floored to thousands. The supported source boundary is +// 0..427 company percent, 0..255 thousand places, a positive duration, and +// trusted table maxima <=255000. Current/target placement must satisfy +// current<=target<=maximum; busy blocks, unknown idle feature bits, owner +// mismatches, disabled existing features, malformed constants and any +// intermediate that overflows Source's signed 32-bit arithmetic have no quote. +// A valid zero-price quote remains previewable; commit refuses to construct it. +std::optional quote_stadium_block_expansion( + const GameState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places, + uint8_t desired_features, int company_price_percent, + const StadiumBlockExpansionConstants& constants); + +// Commit an already resolved tip decision exactly once. `Declined` proceeds at +// the base quote; `Accepted` uses its precomputed price and weeks. A zero-price +// quote never constructs. Notice exceptions propagate so the caller can restore +// its full transaction checkpoint. +bool build_stadium_block_expansion( + GameState& g, int manager, StadiumBlockSlot slot, + const StadiumBlockExpansionConstants& constants, + const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer, + WatcomRandom& rand, const ConstructionNoticeHook& payment_notice = {}, + const SeasonTicketCompensationNoticeHook& compensation_notice = {}); + +} // namespace bmh diff --git a/src/game/state.cpp b/src/game/state.cpp new file mode 100644 index 0000000..7e12be8 --- /dev/null +++ b/src/game/state.cpp @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/state.hpp" + +#include + +#include "game/rating.hpp" + +namespace bmh { + +namespace { + +// Squad table layout constants of V2.24 (TeamsWithSquads, LargeSquadClubCount, NoTeamSquadStart). +constexpr int kBigSquadTeams = 90; +constexpr size_t kNoTeamSquadStart = 3072; +constexpr int kTeamsWithSquads = 168; + +// C-style signed division by 8 as compiled by Watcom (rounds toward zero). +int div8(int x) { return x / 8; } + +} // namespace + +GameState GameState::from_save(const SaveState& save, const DbCounts& c) { + GameState g; + const SaveBlock& squads = save.block(::bmh::layout::SquadSlots); + for (size_t i = 0; i + 1 < squads.size; i += 2) + g.squad_slots.push_back(uint16_t(save.data(::bmh::layout::SquadSlots)[i] | save.data(::bmh::layout::SquadSlots)[i + 1] << 8)); + + auto word = [&](uint32_t block, size_t i) { + const uint8_t* p = save.data(block) + i * 4; + return uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24); + }; + g.players.resize(c.players); + for (size_t i = 0; i < c.players; i++) + g.players[i] = Player{"", word(::bmh::layout::PlayerConditionTechniqueForm, i), word(::bmh::layout::PlayerSkillWords, i), word(::bmh::layout::PlayerIdentityWords, i)}; + + const SaveBlock& morale = save.block(::bmh::layout::TeamMorale); + g.team_morale.assign(save.data(::bmh::layout::TeamMorale), save.data(::bmh::layout::TeamMorale) + morale.size); + + const SaveBlock& flags = save.block(::bmh::layout::TeamFlags); + for (size_t i = 0; i + 1 < flags.size; i += 2) + g.team_flags.push_back(uint16_t(save.data(::bmh::layout::TeamFlags)[i] | save.data(::bmh::layout::TeamFlags)[i + 1] << 8)); + + const SaveBlock& bonus = save.block(::bmh::layout::PlayerBonuses); + g.player_bonus.assign(save.data(::bmh::layout::PlayerBonuses), save.data(::bmh::layout::PlayerBonuses) + bonus.size); + + const SaveBlock& form = save.block(::bmh::layout::Formations); + g.formations.assign(save.data(::bmh::layout::Formations), save.data(::bmh::layout::Formations) + form.size); + + // Manager records: 5 x 0xB0C bytes, the team id is the i16 at +0x290. + int managers = save.data(::bmh::layout::ManagerCount)[0]; + for (int m = 0; m < managers; m++) { + const uint8_t* p = save.data(::bmh::layout::ManagerRecords) + m * 0xB0C + 0x290; + g.manager_teams.push_back(int16_t(p[0] | p[1] << 8)); + } + g.manager_records.assign(save.data(::bmh::layout::ManagerRecords), save.data(::bmh::layout::ManagerRecords) + save.block(::bmh::layout::ManagerRecords).size); + g.tactics.assign(save.data(::bmh::layout::TacticsBoards), save.data(::bmh::layout::TacticsBoards) + save.block(::bmh::layout::TacticsBoards).size); + g.level = save.data(::bmh::layout::Difficulty)[0]; + g.manager_options.assign(save.data(::bmh::layout::ManagerAutomation), save.data(::bmh::layout::ManagerAutomation) + save.block(::bmh::layout::ManagerAutomation).size); + + // Matchday bookkeeping. The club records are dumped twice (pointer, then the heap + // data if the pointer was set); the heap copy is the one needed. + for (const SaveBlock& b : save.blocks()) + if (b.address == ::bmh::layout::TournamentName && b.heap) + g.tournament_name.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size); + else if (b.address == ::bmh::layout::ClubSeasonRecords && b.heap) + g.club_table.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size); + else if (b.heap && (b.address == ::bmh::layout::ClubAuxiliaryWords || b.address == ::bmh::layout::ClubBadgeSelectors || b.address == ::bmh::layout::ClubAuxiliaryBytes)) { + auto& v = b.address == ::bmh::layout::ClubAuxiliaryWords ? g.club_heap_bc : b.address == ::bmh::layout::ClubBadgeSelectors ? g.club_heap_78 : g.club_heap_b8; + v.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size); + } else if (b.heap && b.address == ::bmh::layout::MasterDatabaseMetadata) { + g.master_database_metadata.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size); + } + auto words16 = [&](uint32_t address) { + std::vector v; + const SaveBlock& b = save.block(address); + for (size_t i = 0; i + 1 < b.size; i += 2) v.push_back(uint16_t(save.data(address)[i] | save.data(address)[i + 1] << 8)); + return v; + }; + g.club_ids = words16(::bmh::layout::ClubIdentities); + g.player_cards = words16(::bmh::layout::PlayerCards); + auto u32at = [&](uint32_t address) { + const uint8_t* p = save.data(address); + return uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24); + }; + g.date = u32at(::bmh::layout::CalendarDay); + g.season_start = g.date - uint32_t(save.data(::bmh::layout::DaysIntoSeason)[0] | save.data(::bmh::layout::DaysIntoSeason)[1] << 8); + g.development_balance = int32_t(u32at(::bmh::layout::PlayerDevelopmentBalance)); + // PlayerTrendRotation is not saved; it restarts at its initial value 0 after loading. + auto bytes = [&](uint32_t address) { + return std::vector(save.data(address), save.data(address) + save.block(address).size); + }; + g.manager_results = bytes(::bmh::layout::ManagerMatchHistory); + g.manager_ratings = bytes(::bmh::layout::ManagerRatings); + g.position_history = bytes(::bmh::layout::LeagueRankHistory); + g.league_rounds = bytes(::bmh::layout::LeagueRoundCounters); + g.results = bytes(::bmh::layout::LeagueResults); + g.stocks = bytes(::bmh::layout::StockExchange); + g.foreign_strength = bytes(::bmh::layout::ForeignClubStrength); + g.memory = StaticMemory(save); + // memory OpenBMH saves behind the trailer (the English cup blocks, career.hpp) + for (const auto& b : save.extension()) { + if (!g.memory.has(b.address)) g.memory.add_block(b.address, uint32_t(b.bytes.size())); + for (size_t i = 0; i < b.bytes.size(); ++i) g.memory.set8(b.address + uint32_t(i), b.bytes[i]); + } + g.mailbox = bytes(::bmh::layout::ManagerMailbox); + g.club_names = save.pool(0); + g.player_names = save.pool(1); + g.referee_names = save.pool(2); + g.stadium_names = save.pool(3); + g.player_name_offsets = words16(::bmh::layout::PlayerNameOffsets); + g.season = int16_t(save.data(::bmh::layout::SeasonIndex)[0] | save.data(::bmh::layout::SeasonIndex)[1] << 8); + return g; +} + +int GameState::manager_of(int team) const { + for (size_t m = 0; m < manager_teams.size(); m++) + if (manager_teams[m] == team) return int(m); + return -1; +} + +std::string GameState::club_name(int team) const { + team &= 0xFFF; + if (team == 0xFFF) return texts ? (*texts)[(::bmh::layout::NoClubText - ::bmh::layout::TextPointerTable) / 4] : std::string(); + std::string s; + for (size_t i = club_ids.at(size_t(team)); i < club_names.size() && club_names[i] != 0; i++) s.push_back(char(club_names[i])); + return s; +} + +std::string GameState::player_name(int player) const { + player &= 0xFFF; + if (player == 0xFFF) return texts ? (*texts)[(::bmh::layout::NoPlayerText - ::bmh::layout::TextPointerTable) / 4] : std::string(); + std::string s; + for (size_t i = player_name_offsets.at(size_t(player)); i < player_names.size() && player_names[i] != 0; i++) + s.push_back(char(player_names[i])); + return s; +} + +int GameState::formation(int team) const { + // FormationPosition: bit 4 selects bits 10-11 instead of bits 8-9 + unsigned v = team_flags.at(team); + return int(v >> (((v >> 4) & 1) * 2 + 8) & 3); +} + +void GameState::formation_position(int team, int slot, int& x, int& y) const { + int manager = manager_of(team); + if (manager >= 0) { + size_t at = size_t(manager) * 0x840 + size_t(slot) * 0x58; + x = int8_t(tactics.at(at + 0x41)); + y = int8_t(tactics.at(at + 0x42)); + return; + } + size_t base = (indoor ? 0xB0 : 0) + size_t(formation(team)) * 0x16 + size_t(slot); + x = formations.at(base); + y = formations.at(base + 11); +} + +SquadRange squad_range(int team) { + if (team == kNoTeam) return {kNoTeamSquadStart, 24}; + if (team < kBigSquadTeams) return {size_t(team) * 24, 24}; + if (team < 138) return {size_t(team) * 16 + kBigSquadTeams * 8, 16}; + return {0, 0}; +} + +TeamAverage team_average(const GameState& g, int team, uint16_t flags, WatcomRandom* rand) { + if (team >= kTeamsWithSquads && team != kNoTeam) { + // TeamRating(team, profile 2 at layout field): a random value around the club's level + if (!rand) throw std::invalid_argument("team_average: a team without squad needs the Watcom generator"); + RatingContext ctx; + ctx.rand = rand; + TeamAverage r; + r.value = team_rating(const_cast(g), team, kRatingProfiles[2], ctx); + r.players = 0; + return r; + } + + TeamAverage r; + int sum_condition = 0, sum_technique = 0, sum_form = 0, sum_morale = 0; + int counted = 0; // "local_14" in the original, a byte + + SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + uint16_t slot = g.squad_slots.at(s); + if (slot == kEmptySlot) continue; + if ((flags & avg::LINEUP_ONLY) && !(slot & kSlotInLineup)) continue; + const Player& p = g.players.at(slot & 0x0FFF); + if ((flags & avg::FIT_ONLY) && (p.w364 >> 16 & 0x1F) != 0) continue; + // position filter: bit (position + 4) of the flags, evaluated on the signed flags + if (!((int16_t(flags) >> (p.position() + 4)) & 1)) continue; + + int half = 0; // KO + TE of this player, for best_half_sum + if (flags & avg::CONDITION) { + half = p.condition(); + sum_condition += p.condition(); + } + if (flags & avg::TECHNIQUE) { + half += p.technique(); + sum_technique += p.technique(); + } + if (flags & avg::FORM) sum_form += p.form(); + if (flags & avg::MORALE) sum_morale += (g.team_morale.at(team) & 0x3F) * 2; + if (r.best_half_sum < half / 2) r.best_half_sum = half / 2; + counted++; + } + r.players = counted + (counted == 0); + counted &= 0xFF; + if ((flags & 0x1F0) == 0x1F0) counted = 11; + + int value = 0; + if ((flags & 3) == 0) { + if (flags == (avg::FORM | avg::MORALE)) value = (sum_morale + sum_form) / 2; + else value = (flags & avg::FORM) ? sum_form : sum_morale; + } else { + int attributes = 0; + if (flags & avg::CONDITION) value += sum_condition, attributes++; + if (flags & avg::TECHNIQUE) value += sum_technique, attributes++; + value /= attributes; + // form and morale scale the result by +-(average - 50) / 8 percent + if (sum_form != 0) value = (div8(sum_form / counted - 50) + 100) * value / 100; + if (sum_morale != 0) value = (div8(sum_morale / counted - 50) + 100) * value / 100; + } + if (!(flags & avg::NO_DIVIDE) && counted != 0) { + value /= counted; + if (value < 0) value = 0; + if (value > 99) value = 99; + } + if (value == 0) value = 1; + r.value = value; + return r; +} + +} // namespace bmh diff --git a/src/game/state.hpp b/src/game/state.hpp new file mode 100644 index 0000000..6369a41 --- /dev/null +++ b/src/game/state.hpp @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// In-memory game state used by the game logic. +// +// The original keeps its state in many global tables; GameState collects the ones the +// ported logic needs, decoded into typed vectors. It is filled from a savegame +// (SaveState) and will later be written back the same way. + +#include +#include +#include +#include +#include + +#include "formats/m3d.hpp" +#include "formats/savestate.hpp" +#include "formats/textd.hpp" +#include "game/memory.hpp" +#include "game/random.hpp" +#include "game/reality_motion.hpp" + +namespace bmh { + +struct TransferOfferListView; +struct TransferDecisionEvent; +struct HumanBuyerSaleHooks; + +// Special team id used by the original for "no club" / the player pool (0x165). +constexpr int kNoTeam = 0x165; + +// Squad slot values (u16 in table *SquadSlots): +// bits 0-11 player id, 0xFFF = empty slot +// bit 15 player is in the starting line-up +// bits 12-14 further flags (not yet decoded) +constexpr uint16_t kEmptySlot = 0x0FFF; +constexpr uint16_t kSlotInLineup = 0x8000; + +struct GameState { + std::vector squad_slots; // *SquadSlots, all squads back to back (see squad_range) + std::vector players; // *PlayerConditionTechniqueForm / *PlayerSkillWords / *PlayerIdentityWords, names not filled + std::vector team_morale; // *TeamMorale, per team: bits 0-5 morale / 2, bits 6-7 flags + // *TeamFlags, per team u16. Bits 8-9 and 10-11 hold two formation numbers (0-3); bit 4 + // selects which one is used (see formation()). Other bits not yet decoded. + std::vector team_flags; + // *PlayerBonuses, per player: bits 0-6 a bonus value (0-50 used, raises the player's rating by + // up to 25 %; probably experience/routine), bit 7 a flag. + std::vector player_bonus; + // Block Formations = contents of M3.DAT: formation tables, 2 sets (outdoor, indoor) of + // 0xB0 bytes = 8 formations x (11 x positions, 11 y positions). The engine uses 4. + std::vector formations; + // Team id managed by each human manager (manager record +0x290, CupDraw_FormatError_RuntimeField2), one entry + // per human manager (ManagerCount). + std::vector manager_teams; + bool indoor = false; // OpenBMH deviates from the original: retains designated set-piece selections in the supported manager-record extension. +// CareerSessionRuntimeField: indoor tournament in progress + // Block ManagerRecords: 5 manager records of 0xB0C bytes (raw). Known fields: +0x290 team id, + // +0x8ae staff value used by the club doctor, and from the supported rule profile patch the designated + // takers (player id + 1, u16) +0xafc penalty, +0xafe penalty follow-up, +0xb08 free + // kick, valid only if +0xb0a holds the marker 0x3253. + std::vector manager_records; + // Block TacticsBoards: tactics board of each human manager, 0x840 bytes = 24 slots of 0x58 + // bytes. Slot byte +0x41 = depth x, +0x42 = lane y (signed; x >= 31 and y >= 31 are + // positions between the grid lines), +0x43 = a flag read by the injury code. + std::vector tactics; + // Block ManagerAutomation: 5 option bytes per human manager. Byte 1 (StateRuntimeField2): the assistant + // coach may substitute; byte 2 (StateRuntimeField3): the assistant coach sets the attitude. + std::vector manager_options; + bool manager_option(int manager, int index) const { + size_t at = size_t(manager) * 5 + size_t(index); + return at < manager_options.size() && manager_options[at] != 0; + } + // OpenBMH deviates from the original: retains designated set-piece selections in the supported manager-record extension. +// CurrencySuffixText: the currency after a formatted amount, from the loaded EXE (supported rule profile " EU", + // CD and CLASSIC " DM", the English version " &" - the pound sign of its font). Set by the + // career session; " EU" until then. + std::string currency_suffix = " EU"; + // Runtime-only resort content, loaded for every career and saved-game session. + // Direct engine callers supply their own content before using training camps. + std::array training_camp_base_prices{}; + std::array, 8> training_camp_quality{}; + // Runtime-only copy of the executable credit factors (EXE +BankCredit_BankCreditContext_RuntimeField3), used by + // ChangeBankCreditInterest during weekly manager offers. Never serialized into FBM. + std::array credit_rate_table{}; + double credit_divisor = 0; + bool credit_rate_table_available = false; + int level = 0; // Difficulty: game level; above 3 the tactics board rates players + // ChanceRain / ChanceTemperature: rain and temperature (descriptor +0x50 / +0x30) of the + // match whose chance the minute loop handled last. player_value reads them (bad weather + // and heat cost players whose condition and technique differ), also when the side + // records of the next matchday are built - the values stay from the last chance. + // Run-time globals, not saved. + int chance_rain = 0; + int chance_temperature = 0; + // MatchEngineRuntimeField17: the shooter of the last real chance (0xFFF none); the penalty + // shoot-out still reads it. Run-time global, not saved. + int last_shooter = 0xFFF; + // MatchEngineRuntimeField: quality of the last player picked (PickTaker), also read later. + int last_pick_quality = 0; + // LiveSceneVisible: the live scene is shown this matchday (1 - option CareerSession_DispatchLiveTactic_RuntimeField3, set + // when the matchday starts). Run-time global, not saved. + bool live_scene = false; + RealityResidue reality; // unsaved MatchEngine_Minute_ExecutableField2/MatchEngine_Minute_ExecutableField/MatchEngine_Minute_ExecutableField3/MatchEngine_Minute_ExecutableField4 and previous grid + // StateRuntimeField4 / MatchdaySetupRuntimeField12: home teams of the matches chosen for the live display at + // kick-off (AutoLineup, at most 4). Run-time globals, not saved. + std::vector live_matches; + // ResetSportschauSelection: unsaved bd125 words / bd139 bytes, including insertion slot9. + // Reset clears priorities only; home words deliberately survive between days. + std::array sportschau_homes{}; + std::array sportschau_priorities{}; + bool sportschau_selection_available = false; + uint16_t sportschau_club_threshold = 90; // executable TeamsWithSquads, supplied by CareerSession + // MonthRuntimeField7: alternates 0/1 each time a computer club is looked for to put a + // player on the transfer list (Int5). Run-time static, starts at 0. + int list_toggle = 0; + // LineupRuntimeField: set while the players age at the season change (CareerSeasonSetup3); the + // automatic line-up (Int2) does nothing then. + bool lineups_frozen = false; + // InstallDefaultHooks(row): the contracts screen a human manager gets in the month change when + // the contract of the player in board row `row` has ended. Returns 1 when that contract + // was renewed (the screen may change other rows too), 0 when the player goes, -1 to stop + // (MinuteReport). Without it the month change reports the contract as not supported. + std::function contract_screen; + // DayStepRest2's borrower decision when an expiring loan can be kept: 1 = yes, + // 0 = no, negative = no dialog owner / abort before the month transaction commits. + std::function loan_return_screen; + // DayStepRest2's positive Month_ReturnLoans_TextPointer6 branch enters OpenTransferEditor on a temporary + // special row. The runtime owner must provide the real editor/settlement path. + std::function loan_return_offer_screen; + // How a human manager answers the JA/NEIN questions of the weekly offers (Bool, + // kinds 5, 8 and 10-15): false = NEIN. + bool offer_answer = false; + // Human transfer negotiation at the weekly list deadline. The callback receives the + // seller-manager slot, player, buyer club, fee and annual wage; absent a controller, + // an explicitly human-owned selling club declines rather than silently transferring. + std::function transfer_decision; + // Optional synchronous human-seller selector for the original multi-bid screen + // (IncomingTransferScreen). Return a stable raw bid slot 0..3 or -1 to decline. The legacy + // bool callback above remains the default path when this presenter is absent. + std::function transfer_offer_selector; + // Read-only presentation notification for IncomingTransferScreen's automatic decision + // animation and the subsequent successful-transfer confirmation. It never + // supplies a game decision; ranking, acceptance and transfer remain in Core. + std::function transfer_decision_observer; + // DeskActions_EditorFail_RuntimeField2 gates the original explicit-decline notice in IncomingTransferScreen. + // Runtime context only; it is not a save field. + bool transfer_notice_suppressed = false; + // PoolsOpenFlag == 0xcc: the pools coupon of the desk (BuildPoolsCoupon) is not evaluated + // yet. The desk sets it (also again after loading a game there); EvaluatePoolsCoupon(0) at the + // end of the next second half evaluates the coupon and overwrites the byte, so later + // matchdays leave the results alone. + bool pools_open = true; + // DeskRuntimeField5 / SeasonRuntimeField27: the autosave counter of the desk (DeskDate): months + // seen at the first manager's desk and the month code last seen. Run-time statics: + // a freshly started game has 0/0, so its first desk already counts as a new month. + int autosave_months = 0; + int autosave_month = 0; + + // --- matchday bookkeeping (see matchday.hpp) ------------------------------------------ + // *ClubSeasonRecords: league record per club, 0x4a bytes (168 clubs): + // +0x00 7 streaks x 3 bytes (all, home, away): 0 wins, 1 defeats, 2 draws, + // 3 without a win, 4 unbeaten, 5 without conceding, 6 without scoring + // +0x15 8 record results (home goals << 4 | away goals), see matchday.cpp + // +0x1e points, +0x20 goals for, +0x22 goals against, +0x24 wins, +0x26 draws, + // +0x28 defeats (u16 each) + // +0x2a 8 x u16 opponent of the record (club_ids of the opponent) + // +0x3a 8 x u16 date of the record (CalendarDay, 0xFFFF at most) + std::vector club_table; + std::vector club_ids; // *ClubIdentities, per club (a name/identity number) + // Further heap tables per club, so far only moved when clubs change leagues + // (ClubsChangePlaces): *ClubAuxiliaryWords (u16 per club, 168), *ClubBadgeSelectors (u16 per team, 419), *ClubAuxiliaryBytes (168 bytes) + std::vector club_heap_bc, club_heap_78, club_heap_b8; + // *MasterDatabaseMetadata (100 bytes from M3D.MAN) and the savegame trailer pools 2 (referees, *ba370) and + // 3 (stadiums, *ba360): not used by the engine, kept for writing savegames. + std::vector master_database_metadata, referee_names, stadium_names; + std::vector player_cards; // *PlayerCards, per player: card counters per competition + uint32_t date = 0; // CalendarDay: day counter + // DaysIntoSeason (day of the season, the calendar index) moves with the day counter within + // a season: season_day() = date - season_start. + uint32_t season_start = 0; + // *TournamentName (0x24 bytes, the text slot 590 rewritten at run time): the name of the + // indoor tournament, "In " followed by the longest word of the host club's name. + std::vector tournament_name; + int season_day() const { return int(date) - int(season_start); } + int32_t development_balance = 0; // PlayerDevelopmentBalance: sum of attribute changes (steers trends) + int trend_rotation = 0; // PlayerTrendRotation: next team trend handed out (0-2) + // ManagerMatchHistory: per human manager and opponent club the last results, 5 per venue + // (0x690 bytes per manager = 168 clubs x 2 venues x 5, home | away << 4 as seen by + // the manager's club). + std::vector manager_results; + // ManagerRatings: per manager 6 competitions x the last 10 match ratings (0-200); their + // weighted average is the manager's performance (record +0x8aa). + std::vector manager_ratings; + // *LeagueRankHistory: table position history, 13 u16 per team, three 5-bit positions each; + // LeagueRoundCounters: number of positions recorded per league (9 leagues). + std::vector position_history; + std::vector league_rounds; + // Block LeagueResults: season results, 9 leagues x 38 matchdays x 10 matches (schedule.hpp). + std::vector results; + int season = 0; // SeasonIndex: seasons played (index of the per-season manager records) + // Block StockExchange: 12 shares of 0x5c bytes (price, history, trend) for the stock market. + std::vector stocks; + // ForeignClubStrength: strength byte of each club without a squad (ids from 168 on, the + // foreign clubs): bits 5-7 the level (table RatingRuntimeField2), bits 1-3 strong lines, bit 0 style. + std::vector foreign_strength; + // The other static tables of the savegame, addressed like in the original (cups, ...). + StaticMemory memory; + // *ManagerMailbox: the managers' mailbox (40 entries of 0xA0 bytes, see messages.hpp). + std::vector mailbox; + // TEXTD.BLK for the texts of messages (not part of the savegame; may be null). + const TextDb* texts = nullptr; + // *ba374: the club name pool (trailer pool 0 of the savegame); *ClubIdentities (club_ids) + // holds each club's offset into it. + std::vector club_names; + // ClubName2: name of a club (0xFFF gives the text NoClubText, needs `texts`). + std::string club_name(int team) const; + // *PlayerNameOffsets / *ba36c: offset of each player's name in the player name pool (pool 1). + std::vector player_name_offsets; + std::vector player_names; + // PlayerName for a player id (0xFFF gives the text NoPlayerText, needs `texts`). + std::string player_name(int player) const; + + static GameState from_save(const SaveState& save, const DbCounts& counts = {}); + + // Human manager index of a team, or -1 for computer teams (FindManagerForClub, without the + // special case for manager slot 4). + int manager_of(int team) const; + // Formation number (0-3) a computer team plays with (used by FormationPosition). + int formation(int team) const; + // Formation position of line-up slot `slot` (0-10): x = depth (0 goalkeeper .. ~21 + // forward line), y = lane (0-8, 4 = centre). Human teams read their tactics board. + void formation_position(int team, int slot, int& x, int& y) const; +}; + +// Location of a team's squad inside squad_slots (SquadRange4): +// teams 0..89 (big squads) : 24 slots at team * 24 +// teams 90..137 (small) : 16 slots at team * 16 + 90 * 8 +// kNoTeam : 24 slots at 3072 +struct SquadRange { + size_t first = 0; + size_t count = 0; +}; +SquadRange squad_range(int team); + +// Selection and value flags of team_average (the "param_2" of QuoteNationalFriendlyMatch). +namespace avg { +constexpr uint16_t CONDITION = 0x001; // KO +constexpr uint16_t TECHNIQUE = 0x002; // TE +constexpr uint16_t FORM = 0x004; // FO +constexpr uint16_t MORALE = 0x008; // team morale (same value for every player) +constexpr uint16_t GOALKEEPER = 0x010; // position filters, bit (position + 4) +constexpr uint16_t DEFENDER = 0x020; +constexpr uint16_t MIDFIELDER = 0x040; +constexpr uint16_t FORWARD = 0x080; +constexpr uint16_t ALL_POSITIONS = 0x0F0; +constexpr uint16_t LINEUP_ONLY = 0x100; // only slots flagged kSlotInLineup +constexpr uint16_t NO_DIVIDE = 0x200; // return the sum instead of the per-player average +constexpr uint16_t FIT_ONLY = 0x400; // skip players with w364 bits 16-20 != 0 (injured?) +} // namespace avg + +struct TeamAverage { + int value = 1; // result, 1..99 unless NO_DIVIDE + int players = 0; // number of players that matched the filter (at least 1) + int best_half_sum = 0; // max over players of (KO + TE) / 2 for the selected attributes (CareerSession_FormatError_ExecutableField3) +}; + +// Port of QuoteNationalFriendlyMatch for league teams (id < 168) and kNoTeam. +// +// With CONDITION and/or TECHNIQUE the result is the average of the selected attributes, +// scaled by form and morale if those flags are set as well: +// value = mean(KO, TE) * (100 + (avg_form - 50) / 8) / 100 * (100 + (avg_morale - 50) / 8) / 100 +// With only FORM and/or MORALE the result is the respective average (both: their mean). +// Quirk kept from the original: if all four position bits and LINEUP_ONLY are set +// (flags & 0x1F0 == 0x1F0), the divisor is fixed to 11 players instead of the real count. +// Teams without squads (ids from 168 on) take their value from TeamRating with the +// rating profile 2, which draws from `rand` (required for them); players is then 0. +TeamAverage team_average(const GameState& state, int team, uint16_t flags, WatcomRandom* rand = nullptr); + +} // namespace bmh diff --git a/src/game/table.cpp b/src/game/table.cpp new file mode 100644 index 0000000..e7a936b --- /dev/null +++ b/src/game/table.cpp @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/table.hpp" + +#include + +#include "game/lineup.hpp" +#include "game/schedule.hpp" + +namespace bmh { + + +// AddResult3: one result (goals of both sides) for the two clubs (draw positions). +// flags 1 = count only the home side, 2 = only the away side. +void add_result(LeagueTable& t, const int club[2], const uint8_t goals_in[2], int flags, int win_bonus) { + if (club[0] > 0x13 || club[1] > 0x13) return; + const uint8_t goals[2] = {uint8_t(goals_in[0] & 0x1F), uint8_t(goals_in[1] & 0x1F)}; + const int first = flags == 2 ? 1 : 0, last = flags == 1 ? 1 : 2; + for (int s = first; s < last; s++) { + const int c = club[s]; + t.goals_for[c] = uint8_t(t.goals_for[c] + goals[s]); + t.goals_against[c] = uint8_t(t.goals_against[c] + goals[1 - s]); + t.rank_word[c]++; // games in bits 0-5 + int outcome = 0, bonus = 0; + if (goals[s] > goals[1 - s]) { + outcome = 2; + bonus = win_bonus; + t.wins[c]++; + } else if (goals[s] == goals[1 - s]) { + outcome = 1; + } else { + t.defeats[c]++; + } + t.points[c] = int8_t(t.points[c] + outcome + bonus); + t.form[c] = (t.form[c] << 3) | uint32_t(s * 4 + outcome + 1); + } +} + +// SortKey: sort key of a club; `parts` bits switch off points (1), goals scored +// (2) and goals conceded (4). +uint32_t sort_key(const LeagueTable& t, int c, int parts) { + uint32_t goals = 0; + int diff = 0x100, pts = 0, per_game = 0; + if (!(parts & 2)) { + diff = t.goals_for[c] + 0x100; + goals = t.goals_for[c]; + } + if (!(parts & 4)) diff -= t.goals_against[c]; + if (!(parts & 1)) { + pts = t.points[c] < 0 ? 0 : t.points[c]; + per_game = pts * 2 + 0x80 - (t.rank_word[c] & 0x3F) * 2; + } + return uint32_t(pts) << 25 | uint32_t(per_game) << 17 | uint32_t(diff) << 8 | goals; +} + +// AddResult2: sort (only if the keys are not already descending) and store the ranks; +// the old rank moves to bits 6-10. +void sort_table(LeagueTable& t, int parts) { + int16_t order[20]; + uint32_t keys[20]; + bool unsorted = false; + uint32_t previous = 0xFFFFFFFFu; + for (int c = 0; c < t.size; c++) { + order[c] = int16_t(c); + keys[c] = sort_key(t, c, parts); + if (previous < keys[c]) unsorted = true; + previous = keys[c]; + } + if (unsorted) quicksort_by_key(order, keys, t.size, false); + for (int i = 0; i < t.size; i++) { + uint16_t& w = t.rank_word[order[i]]; + w = uint16_t(((w >> 11) << 6) + i * 0x800 + (w & 0x3F)); + } +} + + +int league_matchdays(int league) { return kLeagueSizes[league] * 2 - 2; } + +LeagueTable compute_league_table(const GameState& g, int league, int from, int to, int flags, int points_mode) { + LeagueTable t; + t.league = league; + t.size = kLeagueSizes[league]; + int parts = 0; + if (points_mode & 0xE) { + parts = points_mode >> 1; + points_mode &= 1; + } + const int first_team = league_first_team(league); + if (flags & 4) { + // a human manager's point deduction (manager record +0x220: 3 << 5 | points) + for (int c = 0; c < t.size; c++) { + int manager = g.manager_of(first_team + c); + if (manager < 0) continue; + uint8_t d = g.manager_records.at(size_t(manager) * 0xB0C + 0x220); + if (d >> 5 == 3) t.points[c] = int8_t(t.points[c] - (d & 0x1F)); + } + flags &= ~4; + } + const int rounds_played = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0; + int last_round = uint8_t(rounds_played - 1); // local_1c + int before_last = 0x80; // local_10 + if (last_round > 1) before_last = uint8_t(rounds_played - 2); + if (last_round > 0x7F) last_round = 0; + const int matchdays = league_matchdays(league); + if (to > matchdays) to = matchdays; + if (to == 0) to = 1; + for (int r = from; r < to; r++) { + std::vector fx = generate_fixtures(league_table_teams(league), r + 1, matchdays / 2, first_team); + bool counted = false; + for (size_t i = 0; i < fx.size(); i++) { + uint8_t b = g.results.at(size_t(league) * 0x17C + size_t(r) * 10 + i); + int club[2] = {fx[i].home - first_team, fx[i].away - first_team}; + if ((b & 0xCC) == 0xCC) { + if (b == 0xCD) + for (int s = 0; s < 2; s++) t.form[club[s]] = t.form[club[s]] << 3 | 4; + continue; + } + const uint8_t goals[2] = {uint8_t(b >> 4), uint8_t(b & 0xF)}; + add_result(t, club, goals, flags, points_mode); + counted = true; + } + if (to <= r + 2 || r == before_last || r == last_round || (last_round < r && counted)) sort_table(t, parts); + } + for (int c = 0; c < t.size; c++) + if (t.points[c] < 0) t.points[c] = 0; + return t; +} + +} // namespace bmh diff --git a/src/game/table.hpp b/src/game/table.hpp new file mode 100644 index 0000000..47f1a5e --- /dev/null +++ b/src/game/table.hpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// League tables (BMH.exe V2.24). +// +// The original keeps no table: whenever one is needed (desk, table screen, season goals, +// position history) ComputeLeagueTable recomputes it from the result bytes of the season +// (block LeagueResults, see schedule.hpp) into a set of scratch arrays: +// TableRuntimeField goals for TableRuntimeField2 goals against +// TableRuntimeField3 points (signed) TableRuntimeField4 wins TableRuntimeField5 defeats +// TableRuntimeField6 u16: bits 0-5 games, 6-10 previous rank, 11-15 rank (0 = first) +// TableRuntimeField7 u32 form chain, 3 bits per game (newest lowest): +// venue << 2 | (0 defeat, 1 draw, 2 win) + 1; 4 = awarded/void +// all indexed by the club's draw position inside its league. +// +// AddResult3 adds one result, SortKey builds the sort key, AddResult2 sorts +// (descending, the quicksort Games) and stores the ranks. + +#include +#include + +#include "game/state.hpp" + +namespace bmh { + +struct LeagueTable { + int league = 0; + int size = 0; + std::array goals_for{}, goals_against{}; + std::array points{}; + std::array wins{}, defeats{}; + std::array rank_word{}; // TableRuntimeField6 + std::array form{}; + + int games(int club) const { return rank_word[club] & 0x3F; } + int rank(int club) const { return rank_word[club] >> 11; } + int previous_rank(int club) const { return rank_word[club] >> 6 & 0x1F; } +}; + +// The building blocks, also used for the cup group tables (AddResult): +// AddResult3 (flags 1 home side only, 2 away side only, 3 both), SortKey and +// AddResult2. +void add_result(LeagueTable& t, const int club[2], const uint8_t goals[2], int flags, int win_bonus); +uint32_t sort_key(const LeagueTable& t, int club, int parts); +void sort_table(LeagueTable& t, int parts); + +// Matchdays of a league per season (LeagueMatchdayCounts = clubs * 2 - 2). +int league_matchdays(int league); + +// ComputeLeagueTable(league, from, to, flags, points_mode): table over the matchdays +// from+1 .. to (clamped to the season). flags: 1 home games only, 2 away games only, +// 4 apply a human manager's point deduction (manager record +0x220). points_mode bit 0: +// three points for a win; bits 1-3 select the sort key parts (see sort_key). +// The ranks are recomputed after certain matchdays exactly as the original does, so the +// "previous rank" bits match its table screens. +LeagueTable compute_league_table(const GameState& g, int league, int from, int to, int flags, int points_mode); + +} // namespace bmh diff --git a/src/game/table_forecast.cpp b/src/game/table_forecast.cpp new file mode 100644 index 0000000..50761d3 --- /dev/null +++ b/src/game/table_forecast.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/table_forecast.hpp" + +#include +#include + +#include "game/schedule.hpp" +#include "game/source_tip.hpp" + +namespace bmh { + +LeagueTableForecast compute_league_table_forecast( + const GameState& game, int league, int source_param2, int matchdays, + int flags, int normal_mode, int sort_extra, + const std::array& gap, const GameRandom& game_random) { + if (league < 0 || league >= kLeagueCount) + throw std::invalid_argument("table forecast: invalid league"); + if (source_param2 != 0) + throw std::invalid_argument("table forecast: only Source param2 zero is reviewed"); + const int source_matchdays = league_matchdays(league); + if (matchdays != source_matchdays) + throw std::invalid_argument("table forecast: matchday count differs from Source league"); + if (flags < 0 || flags > 7) + throw std::invalid_argument("table forecast: unsupported Source aggregation flags"); + if (normal_mode < 0 || normal_mode > 1 || sort_extra < 0 || sort_extra > 14 || (sort_extra & 1)) + throw std::invalid_argument("table forecast: unsupported Source points/sort parameters"); + if (game.league_rounds.size() < size_t(kLeagueCount) || game.results.size() < kResultsSize) + throw std::invalid_argument("table forecast: Native round/results inputs unavailable"); + + const int points_mode = normal_mode + sort_extra; + LeagueTableForecast out; + out.table = compute_league_table(game, league, 0, matchdays, flags, points_mode); + out.game_after = game_random; + const int raw_round = int(game.league_rounds[size_t(league)]); + out.first_simulated_round = raw_round + (source_param2 != 0); + const int first_team = league_first_team(league); + const int teams = league_table_teams(league); + int32_t source_seed = 0; + if (out.first_simulated_round < matchdays) { + if (!game.memory.has(::bmh::layout::TableForecast_InvalidArgument_RuntimeField)) + throw std::invalid_argument("table forecast: Native Source seed unavailable for future rounds"); + source_seed = std::bit_cast(game.memory.u32(::bmh::layout::CurrentMatchday)); + if (source_seed < 0 || source_seed > 10000) + throw std::invalid_argument("table forecast: Native Source seed outside 0..10000"); + } + + for (int round = out.first_simulated_round; round < matchdays; ++round) { + const auto fixtures = generate_fixtures(teams, round + 1, matchdays / 2, first_team); + // ComputeLeagueTableForecast is invoked once per round and reseeds once at entry, + // before iterating that round's fixture pairs. + out.game_after.set_seed(source_seed); + for (const auto& fixture : fixtures) { + const int home_primary = team_average(game, fixture.home, 0x3f3).value; + const int home_secondary = team_average(game, fixture.home, 0x3fc).value; + const int away_primary = team_average(game, fixture.away, 0x3f3).value; + const int away_secondary = team_average(game, fixture.away, 0x3fc).value; + + // GameRandom::set_seed deliberately preserves the cumulative call count. + const uint8_t encoded = source_tip_result(out.game_after, gap, + home_primary, away_primary, home_secondary, away_secondary); + const int clubs[2] = {fixture.home - first_team, fixture.away - first_team}; + const uint8_t goals[2] = {uint8_t(encoded >> 4), uint8_t(encoded & 0x0f)}; + add_result(out.table, clubs, goals, flags & 3, normal_mode); + } + if (matchdays < round + 3) sort_table(out.table, sort_extra >> 1); + ++out.simulated_rounds; + } + return out; +} + +} // namespace bmh diff --git a/src/game/table_forecast.hpp b/src/game/table_forecast.hpp new file mode 100644 index 0000000..d233230 --- /dev/null +++ b/src/game/table_forecast.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include + +#include "game/random.hpp" +#include "game/table.hpp" + +namespace bmh { + +// Scratch result of the Table screen's one-shot KI projection. `game_after` +// contains Source G after all per-ComputeLeagueTableForecast reseeds/draws; callers commit it +// only with the accepted UI/session transition. Native results and CurrentMatchday are +// never changed here. +struct LeagueTableForecast { + LeagueTable table; + GameRandom game_after{0}; + int first_simulated_round = 0; + int simulated_rounds = 0; +}; + +// Only the reviewed E37 normal family entry (Source param2 == 0) is supported. +// All work is local: invalid input or a projection exception cannot mutate the +// caller's GameRandom or GameState. +LeagueTableForecast compute_league_table_forecast( + const GameState& game, int league, int source_param2, int matchdays, + int flags, int normal_mode, int sort_extra, + const std::array& gap, const GameRandom& game_random); + +} // namespace bmh diff --git a/src/game/top_scorers.cpp b/src/game/top_scorers.cpp new file mode 100644 index 0000000..22ffb47 --- /dev/null +++ b/src/game/top_scorers.cpp @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "game/top_scorers.hpp" + +#include +#include +#include + +#include "game/schedule.hpp" + +namespace bmh::game { +namespace { + +constexpr size_t kManagerRecordSize = 0xb0c; +constexpr size_t kNationalBackupManager = 4; +constexpr size_t kManagerTeamOffset = 0x290; + +[[noreturn]] void invalid(const std::string& reason) { + throw FormatError("top scorers: " + reason); +} + +bool source_manager_owns(const GameState& g, int team, size_t manager_count) { + // FindManagerForClub checks every active manager in order, then attributes the + // national coach's original club to Source manager slot 4 when slot 0 is + // temporarily assigned to 0x165. + for (size_t manager = 0; manager < manager_count; ++manager) { + if (manager < g.manager_teams.size() && g.manager_teams[manager] == team) return true; + } + if (!g.manager_teams.empty() && g.manager_teams[0] == kNoTeam) { + const size_t original_at = kNationalBackupManager * kManagerRecordSize + kManagerTeamOffset; + if (original_at + 2 > g.manager_records.size()) + invalid("truncated national-coach backup manager record"); + const uint16_t original = uint16_t(g.manager_records[original_at] | + uint16_t(g.manager_records[original_at + 1]) << 8); + if (original == team) return true; + } + return false; +} + +uint8_t metric_score(uint8_t goals, uint8_t assists, TopScorersMetric metric) { + switch (metric) { + case TopScorersMetric::goals: return goals; + case TopScorersMetric::assists: return assists; + case TopScorersMetric::scorer: return uint8_t(goals + assists); + } + invalid("unknown metric"); +} + +} // namespace + +TopScorersProjection top_scorers_from_game(const GameState& g, int manager_slot, + TopScorersMetric metric, + TopScorersScope scope) { + switch (metric) { + case TopScorersMetric::goals: + case TopScorersMetric::assists: + case TopScorersMetric::scorer: break; + default: invalid("unknown metric"); + } + switch (scope) { + case TopScorersScope::league: + case TopScorersScope::managers: break; + default: invalid("unknown scope"); + } + const size_t manager_count = g.manager_teams.size(); + if (manager_count == 0 || manager_count > 4 || manager_slot < 0 || + size_t(manager_slot) >= manager_count || size_t(manager_slot) >= g.manager_teams.size()) + invalid("manager slot is outside the active manager table"); + const int manager_team = g.manager_teams[size_t(manager_slot)]; + if (manager_team < 0) + invalid("manager has no supported domestic league"); + // TeamLeague2 deliberately maps team IDs above 0x164 (including the + // national team 0x165) to league zero; ordinary cup-only teams map to 9. + const int league = manager_team > 0x164 ? 0 : team_league(manager_team); + if (league < 0 || league >= kLeagueCount) + invalid("manager team is outside Source's nine domestic leagues"); + + const int first_team = league_first_team(league); + const int team_count = kLeagueSizes[league]; + if (first_team < 0 || first_team + team_count > 138 || + g.club_ids.size() < size_t(first_team + team_count) || g.club_names.empty()) + invalid("incomplete domestic club table"); + + TopScorersProjection result; + result.manager_slot = manager_slot; + result.league = league; + result.metric = metric; + result.scope = scope; + + std::array rows{}; + std::array scores{}; + size_t used = 0; + for (int team = first_team; team < first_team + team_count; ++team) { + if (scope == TopScorersScope::managers && !source_manager_owns(g, team, manager_count)) continue; + const SquadRange range = squad_range(team); + if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first) + invalid("incomplete squad slots for domestic club " + std::to_string(team)); + for (size_t offset = 0; offset < range.count; ++offset) { + const uint16_t slot = g.squad_slots[range.first + offset]; + // TopScorersFromGame skips an empty squad position and continues through the + // fixed-size roster; a gap does not terminate Source traversal. + if ((slot & 0x0fff) == kEmptySlot) continue; + const int player = int(slot & 0x0fff); + if (size_t(player) >= g.players.size()) + invalid("squad references missing player " + std::to_string(player)); + const Player& p = g.players[size_t(player)]; + const uint8_t goals = uint8_t((p.w364 >> 2) & 0x3f); + const uint8_t assists = uint8_t((p.w368 >> 18) & 0x3f); + const uint8_t score = metric_score(goals, assists, metric); + if (score == 0) continue; + + size_t position = 0; + while (position < used && !(scores[position] < score)) ++position; + if (position >= rows.size()) continue; + const size_t new_used = used < rows.size() ? used + 1 : used; + for (size_t move = new_used; move > position + 1; --move) { + rows[move - 1] = std::move(rows[move - 2]); + scores[move - 1] = scores[move - 2]; + } + const uint8_t source_goals = metric == TopScorersMetric::assists ? 0 : goals; + const uint8_t source_assists = metric == TopScorersMetric::goals ? 0 : assists; + rows[position] = TopScorersRow{0, player, team, int(range.first + offset), source_goals, source_assists, score, + g.player_name(player), g.club_name(team)}; + scores[position] = score; + used = new_used; + } + } + + result.rows.assign(rows.begin(), rows.begin() + used); + for (size_t i = 0; i < result.rows.size(); ++i) result.rows[i].rank = int(i + 1); + result.no_results = result.rows.empty(); + return result; +} + +} // namespace bmh::game diff --git a/src/game/top_scorers.hpp b/src/game/top_scorers.hpp new file mode 100644 index 0000000..a8fd951 --- /dev/null +++ b/src/game/top_scorers.hpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include + +#include "game/state.hpp" + +namespace bmh::game { + +enum class TopScorersMetric : uint8_t { goals, assists, scorer }; +enum class TopScorersScope : uint8_t { league, managers }; + +struct TopScorersRow { + int rank = 0; + int player = -1; + int team = -1; + int squad_slot = -1; + // Values written to Original's scratch row: unused individual counters + // are zero unless their corresponding flag is selected. + uint8_t goals = 0; + uint8_t assists = 0; + uint8_t score = 0; + std::string player_name; + std::string team_name; + bool operator==(const TopScorersRow&) const = default; +}; + +struct TopScorersProjection { + int manager_slot = -1; + int league = -1; + TopScorersMetric metric = TopScorersMetric::goals; + TopScorersScope scope = TopScorersScope::league; + std::vector rows; + bool no_results = true; + bool operator==(const TopScorersProjection&) const = default; +}; + +// Read-only port of Source TopScorersFromGame. It traverses the selected domestic +// league in runtime team order and each club in squad-slot order, inserting +// strictly ahead of lower scores (equal scores retain traversal order). +// It writes neither GameState nor the Source scratch result table and draws no RNG. +TopScorersProjection top_scorers_from_game(const GameState& game, int manager_slot, + TopScorersMetric metric, + TopScorersScope scope); + +} // namespace bmh::game diff --git a/src/game/trace.hpp b/src/game/trace.hpp new file mode 100644 index 0000000..e500330 --- /dev/null +++ b/src/game/trace.hpp @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The step of the turn the engine is in: the turn driver names it when an exception (such as +// std::out_of_range, which carries no location) ends a turn, and a watchdog can read it while +// a turn runs (tests/cli_soak.cpp). Set at the coarse steps only. + +#include + +namespace bmh { + +inline std::atomic turn_step{"start"}; + +} // namespace bmh diff --git a/src/game/transfer_allocator.hpp b/src/game/transfer_allocator.hpp new file mode 100644 index 0000000..6921cfb --- /dev/null +++ b/src/game/transfer_allocator.hpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +namespace bmh { + +// Unsaved EXE-owned context for PendingOfferAnswer's allocator behavior. Direct +// legacy/headless callers have no executable provenance and must stay unsupported. +enum class TransferAllocatorContext { unsupported, zero, blocked }; + +} // namespace bmh diff --git a/src/game/transfer_bid.hpp b/src/game/transfer_bid.hpp new file mode 100644 index 0000000..73bbb5f --- /dev/null +++ b/src/game/transfer_bid.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include + +#include "game/random.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/state.hpp" + +namespace bmh { +struct MinuteReport; + +// ProjectTransferOfferList rates an existing bid. source_slot is the actual absolute SquadSlots +// index supplied by its caller, not an inferred pool index or player ID. +// The caller owns list/source-slot correspondence and any career-mode decision. +struct TransferBidRatingRequest { + int source_slot = -1; + int list_entry = -1; + int bid_slot = -1; + int expected_bidder = -1; + int expected_player = -1; + // Only checked DispatchClubPlayerPendingOffers entries40..43 may rate parked native buyer4. + std::optional source_pending_owner = std::nullopt; +}; +struct TransferBidRating { + bool supported = false; + uint32_t fee_pct = 0; + uint32_t salary_pct = 0; +}; + +// Exact RateTransferBidSource -> ProjectTransferOfferList composition: Source32 products/unsigned division, +// proposed human board with all seven bonuses/rankFF/fitness, then one W90..100. +// Does not write bids, perform settlement, read GameMode or consume G. Any borrowed +// board is restored before returning or propagating a validation failure. +// Unsupported inputs require caller-owned staging/rollback; no zero-basis guess. +TransferBidRating rate_transfer_bid_source(GameState&, const TransferBidRatingRequest&, + WatcomRandom&, MinuteReport&); +} // namespace bmh diff --git a/src/game/turn.cpp b/src/game/turn.cpp new file mode 100644 index 0000000..56af58d --- /dev/null +++ b/src/game/turn.cpp @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/turn.hpp" +#include "game/trace.hpp" + +#include "game/month.hpp" +#include "game/national.hpp" +#include "game/week.hpp" +#include "game/weekly.hpp" + +namespace bmh { + +bool full_game(const GameState& g) { return g.memory.has(::bmh::layout::CompetitionSelection) && (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) != 0; } + +void event_end(GameState& g) { + if (g.memory.has(::bmh::layout::Savestate_Layout_ExecutableField8)) g.memory.set8(::bmh::layout::Turn_EventEnd_RuntimeField, 1); +} + +void day_stock_market(GameState& g, GameRandom& game) { + if (full_game(g)) stock_market(g, game); +} + +bool month_step(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + if (!full_game(g) || g.date == 0 || month_code(g.date - 1) == month_code(g.date)) return true; + month_change(g, rand, report, &game); // DayStepRest2 + return !report.unsupported; +} + +bool day_step_rest(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + uint16_t source_season_day, TransferAllocatorContext allocator) { + // DayStepRest tests CareerSession_PairingsRuntimeDraw_ExecutableField6 after DeskDate2(date - 1): the weekday of the + // previous day decides whether it is a training day + const int wd = weekday_code(g.date - 1); + const bool training = wd == 2 || wd == 6; + const bool month = full_game(g) && g.date > 0 && month_code(g.date - 1) != month_code(g.date); + // the Bundestrainer leaves the national team for the day's processing: on a training day + // the national squad trains first (FamiliarityDecay), then the slots are swapped back + // (NationalCoachHandBack); at the end he takes it over again (SwapManagerSlots2, ActiveManager left at + // the number of managers by the loop below) + const bool coach = (training || month) && national_coach_active(g); + if (coach) { + if (training) familiarity_decay(g, game, rand); + national_coach_hand_back(g); + } + if (training) { + if (full_game(g) && weekday_code(g.date) == 3) { + turn_step = "weekly_processing"; + weekly_processing(g, game, rand, report, allocator); // DayStepRest3 + if (report.unsupported) return false; + } + turn_step = "training"; + familiarity_decay(g, game, rand); + for (size_t m = 0; m < g.manager_teams.size(); m++) train_squad(g, int(m), game, rand); + } + turn_step = "month_step"; + const bool ok = month_step(g, game, rand, report); + if (coach) national_coach_take_over(g, int(g.manager_teams.size()), source_season_day); + return ok; +} + +} // namespace bmh + +#include "game/matchday_setup.hpp" +#include "game/season.hpp" + +namespace bmh { + +void plain_day(GameState& g, GameRandom& game, WatcomRandom& rand) { + day_stock_market(g, game); + g.date++; + daily_interest(g, rand); +} + +bool empty_event_day(GameState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + setup_matchday(g, 0, ctx, game, rand, report); + turn_step = "prepare_event: matchday number"; + draw_matchday_number(g, rand); // CurrentMatchday + shuffle_manager_order(g, game); + event_end(g); + g.date++; + daily_interest(g, rand); + return !report.unsupported; +} + +bool is_season_end(const GameState& g) { return g.date > 0 && month_code(g.date) == 7 && month_code(g.date - 1) != 7; } + +void season_end_day(GameState& g) { + if (national_coach_active(g)) national_coach_hand_back(g); // DailyInterest: NationalCoachHandBack first + if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 1); + season_awards(g); + if (g.memory.has(::bmh::layout::EventPasses)) g.memory.set8(::bmh::layout::EventPasses, 0); +} + +} // namespace bmh + +#include "game/desk.hpp" + +namespace bmh { + +std::vector prepare_event(GameState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game, + WatcomRandom& rand, MinuteReport& report) { + std::vector groups = setup_matchday(g, day_competitions(g, calendar_entry), ctx, game, rand, report); + draw_matchday_number(g, rand); // CurrentMatchday + turn_step = "prepare_event: manager order"; + const std::vector order = shuffle_manager_order(g, game); + for (size_t k = 0; k < order.size() && g.memory.has(::bmh::layout::NextDeskManager + uint32_t(k) * 2); k++) + g.memory.set16(::bmh::layout::NextDeskManager + uint32_t(k) * 2, uint16_t(order[k])); + return groups; +} + +bool enter_event_desk(GameState& g, int position, const std::vector& groups, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer, + const DeskAutosaveHook& autosave) { + const int manager = g.manager_teams.size() > 1 ? g.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2) : position; + if (g.memory.has(::bmh::layout::DeskPosition)) g.memory.set8(::bmh::layout::DeskPosition, uint8_t(position)); + if (g.memory.has(::bmh::layout::ActiveManager)) g.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager)); + // AdvanceTurn(param1 != 0) suppresses only PreMatchOffer on the remaining + // desks of a loaded manager loop. Coupon preparation and desk entry still run. + // (an out-of-range access below names its step: the error reaches the player as text) + const char* step = "pre_match_offer"; + try { + const bool offer = prepare_pre_match_offer + ? pre_match_offer(g, manager, game, rand, report) : false; + step = "build_pools_coupon"; + build_pools_coupon(g, groups, &rand); // BuildPoolsCoupon + step = "enter_desk"; + enter_desk(g, manager, game, rand, autosave); // DeskDate + return offer; + } catch (const std::out_of_range& e) { + throw std::out_of_range(std::string(e.what()) + " (" + step + ", manager " + std::to_string(manager) + ")"); + } +} + +} // namespace bmh + +#include "formats/binary.hpp" +#include "game/cup.hpp" +#include "game/matchday.hpp" + +namespace bmh { + +void finish_event(GameState& g, std::vector& groups, uint16_t calendar_entry, const std::vector& buttons, + const std::vector& saved_records, const std::vector& saved_options, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw, + const SportschauPresentationHooks* sportschau, const std::vector* show_events, + bool source_sportschau_replay, const SportschauRatingTables* ratings) { + if (report.unsupported) return; + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (int s = 0; s < 24; s++) + for (int k = 0; k < 2; k++) { + const size_t at = m * 0x840 + size_t(s) * 0x58 + 0x44 + size_t(k) * 2; + g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F; + } + auto show_intro = [&](int group_index) { + if (!sportschau || !sportschau->intro) return; + SportschauIntroView view; + view.group_index = group_index; + for (size_t i = 0; i < groups.size() && i <= 0xff; ++i) { + const MatchGroup& group = groups[i]; + view.groups.push_back({uint8_t(i), group.desc.at(0), le32(group.desc, 0xcc), + int16_t(sportschau_source_setting_index(g, group))}); + } + sportschau->intro(g, view); + }; + show_intro(-1); + for (size_t group_index = 0; group_index < groups.size(); ++group_index) { + MatchGroup& grp = groups[group_index]; + // FinishEvent sets DeskPosition to the current match-group index. Its final nonempty + // iteration leaves the last index visible to the following cup presentation. + if (g.memory.has(::bmh::layout::DeskPosition) && group_index <= 0xff) + g.memory.set8(::bmh::layout::DeskPosition, uint8_t(group_index)); + if (group_index <= 0xff) show_intro(int(group_index)); + if (ratings && !source_sportschau_replay) { + // FinishEvent/BuildSideRecords clear eleven scores outside the CareerSession_SportschauSourceOptions_ExecutableField gate. + // The loaded EXE owner still performs that reset when it skips + // MatchdayIntro entirely; old slot words remain untouched. + for (size_t i = 0; i < 11; ++i) { + grp.desc.at(0x70 + i) = 0; + const uint32_t address = ::bmh::layout::Turn_FinishEvent_ExecutableField + uint32_t(group_index) * 0xd0 + uint32_t(i); + if (group_index < 6 && g.memory.has(address)) g.memory.set8(address, 0); + } + } + process_group(g, grp, game, rand, report, int(group_index), + sportschau ? sportschau->fixture : SportschauFixtureHook{}, show_events, + source_sportschau_replay && sportschau ? &sportschau->replay : nullptr, + source_sportschau_replay ? ratings : nullptr); + if (report.unsupported) return; + if (source_sportschau_replay && ratings) { + const auto awards = finish_sportschau_awards(g, grp, int(group_index)); + if (awards && sportschau && sportschau->awards) sportschau->awards(g, *awards); + if (sportschau && sportschau->team_info) { + const auto info = sportschau_team_info_view(g, grp, int(group_index)); + if (info) sportschau->team_info(g, *info); + } + } + const uint32_t id = le32(grp.desc, 0xcc); + if (id < 0x15) { + if (league_screen_shown(buttons, 1, 90, int(id))) stir_random(game, rand); + const int round = g.league_rounds.at(id); + for (int m = 0; m < grp.matches(); m++) g.results.at(size_t(id) * 0x17C + size_t(round) * 10 + size_t(m)) = grp.results.at(size_t(m)); + } else { + store_cup_results(g, grp); + } + } + // FinishEvent/BuildSideRecords call EvaluatePoolsCoupon(1) after every group's processing, + // before returning to AdvanceTurn's calendar/round advancement. Result evaluation + // at the second half is separate; pools_open does not gate this settlement. + settle_pools_coupon(g, groups); + for (size_t m = 0; m < g.manager_teams.size() && !saved_records.empty(); m++) { + for (size_t k = 0; k < 8; k++) g.manager_records.at(m * 0xB0C + 0xd2 + k) = saved_records.at(m * 0xB0C + 0xd2 + k); + g.manager_options.at(m * 5 + 2) = saved_options.at(m * 5 + 2); + } + const uint32_t competitions = day_competitions(g, calendar_entry); + advance_league_rounds(g, competitions & 0x1F, rand, report, + sportschau ? sportschau->winner : CompetitionWinnerHook{}); + for (int bit = 5; bit < 0x13; bit++) + if ((competitions >> bit) & 1) advance_cup(g, bit - 5, rand, report, &game, cup_draw, + sportschau ? sportschau->winner : CompetitionWinnerHook{}); + event_end(g); +} + +} // namespace bmh diff --git a/src/game/turn.hpp b/src/game/turn.hpp new file mode 100644 index 0000000..7282c7d --- /dev/null +++ b/src/game/turn.hpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The "Weiter" loop of the original (DailyInterest) - everything between two desks of the +// human managers: the day steps, the weekly and monthly processing, the matchdays with +// their preparation, the cups, the season end and the season change. +// +// Built up step by step from the parts verified with tests/week_check (which uses these +// functions, so every regression run checks them against the recordings). + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/state.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh { + +// Whether the career plays the leagues (CompetitionSelection bit 0, "full game"); without them +// there is no weekly or monthly processing. +bool full_game(const GameState& g); +// DailyInterest: the daily share price run (DailyInterest3) only with the leagues on +// (CompetitionSelection bit 0) - the world game without leagues keeps its prices. +void day_stock_market(GameState& g, GameRandom& game); +// The end of AdvanceTurn: EventEnd(TurnRuntimeField), with the value layout field the program +// start leaves there, sets Turn_EventEnd_RuntimeField = 1. +void event_end(GameState& g); + +// The rest of the day step DayStepRest after the date moved on: on a training day (the +// previous day's weekday code 2 or 6) the weekly processing (DayStepRest3, full game, +// when the new day has weekday code 3), the decay of the familiarity and every human +// manager's training; then the month change (DayStepRest2) when the month moved on. +// Returns false on a reported state/context failure; see MinuteReport::reason. +bool day_step_rest(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + uint16_t source_season_day, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// The month change part alone (full game only, when the new day is in another month). +bool month_step(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +} // namespace bmh + +namespace bmh { + +struct MatchdayContext; + +// A day without an event (the "Weiter" loop): the shares move (DailyInterest3), then the +// date counts on and the daily interest is booked (the start of DayStepRest). The rest +// of the day step (day_step_rest) follows. +void plain_day(GameState& g, GameRandom& game, WatcomRandom& rand); + +// A calendar entry whose competitions are all switched off (e.g. 0x4006 without the +// option CompetitionSelection bit 1) is still an event for DailyInterest: AdvanceTurn prepares an +// empty matchday (DayCompetitions2, the matchday number, the manager order) without a desk; +// then the date counts on (with the daily interest) as after any event. +bool empty_event_day(GameState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// 1 July (DailyInterest: CareerSession_PairingsRuntimeDraw_ExecutableField4 == 1, CareerSession_PairingsRuntimeDraw_ExecutableField5 == 7): the season is over - +// CareerSession_RuntimeError_RuntimeField4 = 1, the prizes for top scorers and fair play (SeasonAwards); no event is +// due any more (EventPasses = 0). The managers' "Saisonende" desk follows. +bool is_season_end(const GameState& g); +void season_end_day(GameState& g); + +} // namespace bmh + +#include +#include "game/desk.hpp" + +namespace bmh { + +// AdvanceTurn up to its desk loop for the day's calendar entry: the match groups +// (DayCompetitions2), the matchday number (CurrentMatchday) and the shuffled order of the +// managers' desks (PrepareEvent, kept in NextDeskManager). +std::vector prepare_event(GameState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); + +// One pass of that desk loop for the manager at `position` of the order: ActiveManager / +// DeskPosition, a pre-match offer (PreMatchOffer; true = its message box comes first), the +// pools coupon (BuildPoolsCoupon) and entering the desk (DeskDate). +bool enter_event_desk(GameState& g, int position, const std::vector& groups, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer = true, + const DeskAutosaveHook& autosave = {}); + +} // namespace bmh + +namespace bmh { + +// The end of a matchday after its last phase (the part of FinishEvent / AdvanceTurn after +// the matches): the human boards' substitution marks are cleared, every group is processed +// (process_group; a league's result screen - when shown - stirs the numbers, its results go +// into the season table, a cup's into its rounds), the managers' match settings changed +// during the matches (record +0xd2..+0xd9, option byte 2) return to `saved_records` / +// `saved_options` (taken at the kick-off), the leagues count their round and the cups of the +// day move on. +void finish_event(GameState& g, std::vector& groups, uint16_t calendar_entry, const std::vector& buttons, + const std::vector& saved_records, const std::vector& saved_options, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw = {}, + const SportschauPresentationHooks* sportschau = nullptr, + const std::vector* show_events = nullptr, + bool source_sportschau_replay = false, + const SportschauRatingTables* ratings = nullptr); + +} // namespace bmh diff --git a/src/game/turn_driver.cpp b/src/game/turn_driver.cpp new file mode 100644 index 0000000..fb2d3f7 --- /dev/null +++ b/src/game/turn_driver.cpp @@ -0,0 +1,593 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/turn_driver.hpp" + +#include +#include +#include + +#include "game/desk.hpp" +#include "game/driver.hpp" +#include "game/matchday.hpp" +#include "game/matchday_setup.hpp" +#include "game/trace.hpp" +#include "game/national.hpp" +#include "game/season.hpp" +#include "game/turn.hpp" +#include "game/week.hpp" + +namespace bmh { +namespace { + +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; +// The calendar entry of a season day. The table has 366 days (0-365); a season that starts +// on 1 July and spans 29 February ends on day 366, where the original reads the next bytes +// of its data (the fixture pointer table at CareerSession_RuntimeError_ExecutableField) - no competition. OpenBMH deviates from +// the original here: such a day has no calendar entry (0) instead of whatever lies behind. +uint16_t calendar_day(const GameState& g, int day) { + const uint32_t at = kCalendar + uint32_t(day) * 2; + return day >= 0 && g.memory.has(at + 1) && at + 1 < ::bmh::layout::CareerSession_RuntimeError_ExecutableField ? g.memory.u16(at) : uint16_t(0); +} +constexpr uint32_t kDeskButtons = ::bmh::layout::LeaguePresentationOptions; +constexpr uint32_t kSavedCompetition = ::bmh::layout::SavedCompetition; +constexpr uint32_t kCoachActive = ::bmh::layout::CoachActive; +constexpr uint32_t kOriginalManagerCount = ::bmh::layout::OriginalManagerCount; +constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount; +constexpr uint32_t kManagerOrder = ::bmh::layout::NextDeskManager; +constexpr uint32_t kDeskPosition = ::bmh::layout::DeskPosition; +constexpr uint32_t kActiveManager = ::bmh::layout::ActiveManager; +constexpr uint32_t kEventPasses = ::bmh::layout::EventPasses; + +// DailyInterest sets the saved loop count once per calendar date: three Hall +// rounds on the first of two consecutive Hall days, two on the last day. +// Completing a round does not run another date/training/interest step. +void start_event_passes(GameState& g, uint16_t entry) { + if (!g.memory.has(kEventPasses)) return; + uint8_t passes = 1; + if (entry == 0x4002) { + const uint32_t next = kCalendar + uint32_t(g.season_day() + 1) * 2; + passes = g.memory.has(next + 1) && g.memory.u16(next) == 0x4002 ? 3 : 2; + } + g.memory.set8(kEventPasses, passes); +} + +bool consume_event_pass(TurnDriver& driver, GameState& g) { + if (!g.memory.has(kEventPasses)) return false; + // Only the Hall calendar cell has multiple passes. Old OpenBMH saves + // carried a stale Hall count into ordinary dates; do not repeat leagues. + const bool hall = driver.calendar_entry == 0x4002 && g.indoor; + const uint8_t count = hall ? g.memory.u8(kEventPasses) : 1; + const uint8_t remaining = count == 0 ? 0 : uint8_t(count - 1); + g.memory.set8(kEventPasses, remaining); + return hall && remaining != 0; +} + +std::vector read_buttons(const GameState& g) { + std::vector result; + if (!g.memory.has(kDeskButtons + 0xb3)) return result; + result.reserve(0xb4); + for (uint32_t i = 0; i < 0xb4; ++i) result.push_back(g.memory.u8(kDeskButtons + i)); + return result; +} + +MatchdayContext matchday_context(const GameState& g, std::vector& referees) { + MatchdayContext context; + context.month = month_code(g.date); + context.season_day = g.season_day(); + context.weekday = weekday_code(g.date); + context.referees = &referees; + return context; +} + +bool saved_national_nomination_desk(const GameState& g, const std::vector& groups, + uint16_t calendar_entry) { + const auto& mem = g.memory; + if (!groups.empty() || g.manager_teams.size() != 1 || g.manager_teams[0] != kNoTeam || + !mem.has(kCalendar + uint32_t(g.season_day()) * 2 + 1) || + !mem.has(kSavedCompetition + 3) || !mem.has(kCoachActive) || + !mem.has(kOriginalManagerCount) || !mem.has(kManagerCount) || + !mem.has(kManagerOrder + 1) || !mem.has(kDeskPosition) || !mem.has(kActiveManager)) + return false; + const uint16_t saved_entry = mem.u16(kCalendar + uint32_t(g.season_day()) * 2); + if (saved_entry != calendar_entry || day_competitions(g, saved_entry) != 0x800000 || + mem.u32(kSavedCompetition) != 0 || mem.u8(kCoachActive) == 0 || + mem.u8(kManagerCount) != 1 || mem.u8(kOriginalManagerCount) < 1 || + mem.u8(kOriginalManagerCount) > 4 || mem.u16(kManagerOrder) >= mem.u8(kOriginalManagerCount) || + mem.u8(kDeskPosition) != 0 || mem.u8(kActiveManager) != 0) + return false; + return true; +} + +TurnAdvanceResult fail(TurnDriver& driver, const GameState& g, const MinuteReport& report, + const char* fallback) { + driver.stage = TurnDriver::Stage::Failed; + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + out.date = g.date; + out.revision = driver.revision; + out.reason = report.reason.empty() ? fallback : report.reason; + return out; +} + +TurnAudioEvent audio_event(TurnDriver& driver, TurnAudioKind kind) { + // Cue mapping is deliberately absent until a concrete original call site is proven. + return {driver.session_id, driver.next_event_id++, kind, std::nullopt}; +} + +TurnAdvanceResult desk_result(TurnDriver& driver, const GameState& g, TurnDeskKind kind, + bool offer_pending = false) { + TurnAdvanceResult out; + out.kind = kind; + out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + out.date = g.date; + out.revision = driver.revision; + out.offer_pending = offer_pending; + return out; +} + +bool run_current_matchday(TurnDriver& driver, GameState& g, GameRandom& game, + WatcomRandom& rand, MinuteReport& report, + std::vector& events) { + const std::vector saved_records = g.manager_records; + const std::vector saved_options = g.manager_options; + MatchdayContext context = matchday_context(g, driver.referees); + + turn_step = "kick_off"; + kick_off(g, driver.groups, context, rand, game, report, + driver.sportschau_source.intro_after_matchday != 0, + driver.sportschau_source.rated_club_threshold); + if (report.unsupported) return false; + if (driver.sportschau_source.intro_after_matchday != 0 && driver.sportschau.kickoff) { + const auto intro = matchday_intro_view(g, driver.groups); + if (intro) driver.sportschau.kickoff(g, *intro); + } + bool manager_match_played = false; + for (const MatchGroup& group : driver.groups) + for (int m = 0; m < group.matches(); ++m) { + if (group.void_mask() >> m & 1) continue; + const size_t fixture = size_t(m * 2); + if (fixture + 1 < group.fixtures.size() && + (g.manager_of(group.fixtures[fixture]) >= 0 || + g.manager_of(group.fixtures[fixture + 1]) >= 0)) + manager_match_played = true; + } + // Matchday resolution is synchronous. Emit cues only for fixtures involving a + // human-managed club so background AI schedules do not flood the audio queue. + if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::kickoff_whistle)); + + MatchEngine engine{g, driver.groups, game, rand, driver.referees}; + if (driver.original_sound) { + engine.original_sound = [&driver, &g](uint8_t id) { driver.original_sound(id, g); }; + if (manager_match_played) engine.original_sound(3); // EndPhase / ReadButtons, crowd. + } + std::vector sportschau_show_events; + if (driver.sportschau.fixture) engine.show = &sportschau_show_events; + engine.month = context.month; + engine.buttons = read_buttons(g); + engine.reality_rules = driver.reality_rules; + engine.live_scene_visible = g.live_scene && driver.reality_rules; + engine.phase_results = driver.phase_results; + if (driver.live_reality) { + engine.live_reality = [&driver, &g](const LiveRealityEvent& event) { + return driver.live_reality(event, driver.groups, g); + }; + } + // LiveDeskDisabled is a saved settings byte. It also changes attitude, assistant + // substitutions and RNG consumption, so a background driver must preserve it. + engine.live_desk_disabled = g.memory.has(::bmh::layout::LiveDeskDisabled) && g.memory.u8(::bmh::layout::LiveDeskDisabled) != 0; + engine.alternate_event_roll = driver.alternate_match_event_roll; + engine.match_events_disabled = driver.disable_match_events; + engine.leave_screens = true; + if (driver.live_shootout) { + engine.live_shootout = [&driver, &g](const LiveShootoutEvent& event) { + driver.live_shootout(event, driver.groups, g); + }; + } + if (driver.live_booking) { + engine.live_booking = [&driver, &g](const LiveBookingEvent& event) { + driver.live_booking(event, driver.groups, g); + }; + } + if (driver.live_set_piece) { + engine.live_set_piece = [&driver, &g](const LiveSetPieceEvent& event) { + driver.live_set_piece(event, driver.groups, g); + }; + } + if (driver.live_shot) { + engine.live_shot = [&driver, &g](const LiveShotEvent& event) { + driver.live_shot(event, driver.groups, g); + }; + } + if (driver.live_chance) { + engine.live_chance = [&driver, &g](const LiveChanceEvent& event) { + driver.live_chance(event, driver.groups, g); + }; + } + if (driver.live_ball) { + engine.live_ball = [&driver, &g](const LiveBallEvent& event) { + driver.live_ball(event, driver.groups, g); + }; + } + if (driver.live_event) { + engine.live_event = [&driver, &engine](const LiveMatchEvent& event) { + driver.live_event(event, engine, driver.groups, engine.state); + }; + } + std::vector>> previous(driver.groups.size()); + for (size_t gi = 0; gi < driver.groups.size(); ++gi) { + const MatchGroup& group = driver.groups[gi]; + previous[gi].resize(size_t(group.matches())); + for (int m = 0; m < group.matches(); ++m) { + int home = 0, away = 0; + match_score(group, m, home, away); + previous[gi][size_t(m)] = {home, away}; + } + } + bool manager_match_scored = false; + auto collect_goals = [&](int) { + for (size_t gi = 0; gi < driver.groups.size(); ++gi) { + const MatchGroup& group = driver.groups[gi]; + for (int m = 0; m < group.matches(); ++m) { + const size_t fixture = size_t(m * 2); + if ((group.void_mask() >> m & 1) || fixture + 1 >= group.fixtures.size() || + (g.manager_of(group.fixtures[fixture]) < 0 && + g.manager_of(group.fixtures[fixture + 1]) < 0)) + continue; + int home = 0, away = 0; + if (!match_score(group, m, home, away)) continue; + auto& old = previous[gi][size_t(m)]; + const int goals = std::max(0, home - old[0]) + std::max(0, away - old[1]); + manager_match_scored = manager_match_scored || goals > 0; + old = {home, away}; + } + } + }; + auto after_minute = [&](int minute) { + collect_goals(minute); + if (driver.live_minute) driver.live_minute(minute, engine, driver.groups, g); + }; + turn_step = "play_matchday"; + play_matchday(engine, g, driver.groups, engine.buttons, game, rand, report, after_minute); + if (report.unsupported) return false; + // The app receives the whole synchronous turn at once. One summary goal cue + // per manager matchday is bounded and avoids replaying a stream of missed goals. + if (manager_match_scored) events.push_back(audio_event(driver, TurnAudioKind::goal)); + if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::full_time_whistle)); + + turn_step = "finish_event"; + store_group_descriptors(g, driver.groups, true); + finish_event(g, driver.groups, driver.calendar_entry, engine.buttons, + saved_records, saved_options, game, rand, report, driver.season_cup_draw, + &driver.sportschau, &sportschau_show_events, + driver.sportschau_source.intro_after_matchday != 0, + driver.sportschau_source.ratings ? &*driver.sportschau_source.ratings : nullptr); + return !report.unsupported; +} + +bool next_event(TurnDriver& driver, GameState& g, GameRandom& game, WatcomRandom& rand, + MinuteReport& report, bool& offer_pending, bool after_event, + bool first_day_preprocessed = false, bool repeat_event = false) { + for (int day = 0; day < 366 * 5; ++day) { + // DailyInterest enters AdvanceTurn on season day zero even when its + // calendar cell is empty. The prepared first Wednesday is a manager + // desk, not a day to skip while seeking the first scheduled fixture. + const bool opening_desk = first_day_preprocessed && g.season_day() == 0; + // DailyInterest advances DaysIntoSeason before DayStepRest on a quiet day, + // but after DayStepRest when completing an event. Preserve that Source-visible + // context for a nested Bundestrainer re-takeover; the typed date is already one + // day ahead in the latter case. + const uint16_t source_rest_day = uint16_t( + g.date - g.season_start - uint32_t(after_event ? 1 : 0)); + turn_step = "day_step_rest"; + if (!first_day_preprocessed && + !day_step_rest(g, game, rand, report, source_rest_day, + driver.transfer_allocator_context)) return false; + // DailyInterest tests for 1 July only after DayStepRest has advanced a day. The + // prepared first day of a new season is not such a step: when 1 July is itself the + // first Wednesday (2037), the season change leaves the date there, and testing it + // again started the season change over and over (endless loop after ten seasons). + const bool day_stepped = !first_day_preprocessed; + first_day_preprocessed = false; + if (day_stepped && is_season_end(g)) { + turn_step = "season_end_day"; + season_end_day(g); + // DailyInterest calls AdvanceTurn after the annual awards. DayCompetitions2's + // closing branch supplies FF opponents / competition32 without + // preparing teams, fixtures or cycling manager options. Its old + // descriptors remain available to BuildPoolsCoupon's coupon scan. + if (full_game(g)) { // DailyInterest calls this desk loop only with leagues. + driver.calendar_entry = calendar_day(g, g.season_day()); + const uint32_t closing_competitions = day_competitions(g, driver.calendar_entry); + g.memory.set32(kSavedCompetition, closing_competitions == 0x800000 ? 0 : closing_competitions); + draw_matchday_number(g, rand); + shuffle_manager_order(g, game); + driver.manager_position = 0; + driver.national_nomination_desk = false; + turn_step = "enter_closing_desk"; + offer_pending = enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + } + driver.stage = TurnDriver::Stage::SeasonEndDesk; + ++driver.revision; + return true; + } + + turn_step = "stock market"; + if (after_event) day_stock_market(g, game); + after_event = false; + const uint16_t entry = calendar_day(g, g.season_day()); + if (!(entry & 0x7fff) && !opening_desk) { + turn_step = "plain_day"; + plain_day(g, game, rand); + continue; + } + turn_step = "calendar day"; + const uint32_t competitions = day_competitions(g, entry); + driver.referees = driver.referee_source; // clear the per-day chosen flags + MatchdayContext context = matchday_context(g, driver.referees); + if (competitions == 0 && !opening_desk) { + turn_step = "empty_event_day"; + if (!empty_event_day(g, context, game, rand, report)) return false; + after_event = true; + continue; + } + if (competitions == 0x800000 && !opening_desk) { + // The return means that a human national-coach desk follows, not + // that the calendar step succeeded. The ordinary no-coach case + // still performs the Source national-team preparation and continues. + const bool has_national_coach = national_team_day(g, rand, report); + if (report.unsupported) return false; + const bool enter_national_desk = has_national_coach && driver.enable_national_nomination_desks; + // AdvanceTurn clears the transient competition result before its empty + // setup. Keep the legacy/no-coach behavior byte-identical; the opted-in + // coach path clears it before preparing the real national desk. + if (enter_national_desk) { + if (g.manager_teams.size() != 1 || g.manager_teams[0] != kNoTeam) { + report.fail("national nomination returned a coach without the one-manager national context"); + return false; + } + if (g.memory.has(kSavedCompetition + 3)) g.memory.set32(kSavedCompetition, 0); + context.national_team_day = true; + } + turn_step = "setup_matchday (national)"; + const std::vector none = setup_matchday(g, 0, context, game, rand, report); + if (report.unsupported) return false; + if (!none.empty()) { + report.fail("national team day unexpectedly prepared match groups"); + return false; + } + draw_matchday_number(g, rand); + shuffle_manager_order(g, game); + if (enter_national_desk) { + driver.calendar_entry = entry; + driver.groups = none; + driver.manager_position = 0; + turn_step = "enter_event_desk"; + offer_pending = enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + driver.national_nomination_desk = true; + driver.stage = TurnDriver::Stage::MatchdayDesks; + ++driver.revision; + return true; + } + event_end(g); + ++g.date; + daily_interest(g, rand); + after_event = true; + continue; + } + + driver.calendar_entry = entry; + if (!repeat_event) start_event_passes(g, entry); + repeat_event = false; + turn_step = "prepare_event"; + driver.groups = prepare_event(g, entry, context, game, rand, report); + if (report.unsupported) return false; + if (!matchday_needs_manager_desks(g, entry, driver.groups)) { + std::vector background_events; + if (!run_current_matchday(driver, g, game, rand, report, background_events)) return false; + if (consume_event_pass(driver, g)) { + first_day_preprocessed = true; + repeat_event = true; + continue; + } + ++g.date; + daily_interest(g, rand); + after_event = true; + continue; + } + driver.manager_position = 0; + turn_step = "enter_event_desk"; + offer_pending = enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave); + if (report.unsupported) return false; + driver.stage = TurnDriver::Stage::MatchdayDesks; + ++driver.revision; + return true; + } + report.fail("turn driver exceeded five seasons without a manager desk"); + return false; +} + +} // namespace + +bool begin_turn_driver(TurnDriver& driver, const GameState& g, std::vector groups, + uint16_t calendar_entry, std::vector referees, + uint64_t session_id, uint64_t revision, std::string& error) { + if (driver.stage != TurnDriver::Stage::Empty || revision == 0 || session_id == 0) { + error = "turn driver is already active or has invalid identity"; + return false; + } + if (g.manager_teams.empty()) { + error = "turn driver needs at least one human manager"; + return false; + } + driver.stage = TurnDriver::Stage::MatchdayDesks; + driver.calendar_entry = calendar_entry; + driver.manager_position = g.memory.has(::bmh::layout::DeskPosition) ? int(g.memory.u8(::bmh::layout::DeskPosition)) : 0; + driver.revision = revision; + driver.session_id = session_id; + driver.groups = std::move(groups); + driver.referee_source = std::move(referees); + driver.referees = driver.referee_source; + driver.national_nomination_desk = saved_national_nomination_desk( + g, driver.groups, calendar_entry); + return true; +} + +TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, GameState& g, + const TurnAdvanceRequest& request, + GameRandom& game, WatcomRandom& rand, + MinuteReport& report) { + const int active_manager = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + // AdvanceTurn restores the retained club-order owner after every temporary + // national desk, including desks with real fixtures. That owner can be1–3 + // although the visible/runtime national manager is0. Qualify the completed + // pending batch below without turning an actual match into a nomination day. + const bool national_handoff = driver.enable_national_nomination_desks && + (driver.national_nomination_desk || + (g.manager_teams.size() == 1 && g.manager_teams[0] == kNoTeam && + g.memory.has(kCoachActive) && g.memory.u8(kCoachActive) != 0)); + if (national_handoff) { + const int original_count = g.memory.has(kOriginalManagerCount) + ? int(g.memory.u8(kOriginalManagerCount)) : 0; + const int source_owner = g.memory.has(kManagerOrder + 1) + ? int(g.memory.u16(kManagerOrder)) : -1; + const bool completed_pending = g.memory.has(kDeskPosition) && + g.memory.u8(kDeskPosition) == 1 && active_manager == source_owner && + original_count >= 1 && original_count <= 4 && source_owner >= 0 && + source_owner < original_count; + if (!completed_pending) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "national_nomination_pending_not_completed"; + return out; + } + if (driver.stage != TurnDriver::Stage::MatchdayDesks || + request.manager_slot != 0 || driver.manager_position != 0 || + request.revision != driver.revision || g.manager_teams.size() != 1 || + g.manager_teams[0] != kNoTeam || !g.memory.has(kCoachActive) || + g.memory.u8(kCoachActive) == 0 || !g.memory.has(kManagerCount) || + g.memory.u8(kManagerCount) != 1) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "stale_national_coach_manager_or_revision"; + return out; + } + } else if ((driver.stage != TurnDriver::Stage::MatchdayDesks && driver.stage != TurnDriver::Stage::SeasonEndDesk) || + request.manager_slot != active_manager || request.revision != driver.revision) { + TurnAdvanceResult out; + out.kind = TurnDeskKind::Failed; + out.manager_slot = active_manager; + out.date = g.date; + out.revision = driver.revision; + out.reason = "stale_manager_or_revision"; + return out; + } + + // Claim the request before any RNG or state mutation. A failure is terminal for this + // cursor, so replaying the same request cannot repeat a partially completed turn. + const auto previous_stage = driver.stage; + driver.stage = TurnDriver::Stage::Failed; + std::vector events; + bool offer_pending = false; + try { + if (driver.manager_position + 1 < int(g.manager_teams.size())) { + ++driver.manager_position; + const bool prepare_pre_match_offer = + !(driver.loaded_matchday_resume && driver.suppress_remaining_pre_match_offers); + turn_step = "enter_event_desk"; + offer_pending = enter_event_desk(g, driver.manager_position, driver.groups, + game, rand, report, prepare_pre_match_offer, driver.desk_autosave); + if (report.unsupported) return fail(driver, g, report, "manager pre-match desk unsupported"); + driver.stage = previous_stage; + ++driver.revision; + return desk_result(driver, g, previous_stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + } + if (previous_stage == TurnDriver::Stage::SeasonEndDesk) { + // Every manager has now left the closing desk. Do not carry the + // loaded desk-resume policy into the annual transition or a new event. + driver.complete_loaded_manager_loop(); + // AdvanceTurn's completed manager-desk loop leaves DeskPosition == ManagerCount + // before DailyInterest enters the annual transition. This native byte is + // serialized at modal checkpoints; the next real desk resets it. + if (g.memory.has(::bmh::layout::DeskPosition)) + g.memory.set8(::bmh::layout::DeskPosition, g.memory.has(::bmh::layout::ManagerCount) + ? g.memory.u8(::bmh::layout::ManagerCount) : uint8_t(g.manager_teams.size())); + const auto outcome = season_transition(g, game, rand, report, driver.season_pause + ? std::function([&](const char* screen) { driver.season_pause(screen, g); }) + : std::function{}, driver.season_highscore, driver.season_tax, + driver.season_promotion, driver.season_cup_draw, driver.transfer_allocator_context); + if (report.unsupported || outcome == SeasonTransitionOutcome::Failed) + return fail(driver, g, report, "season transition unsupported"); + if (outcome == SeasonTransitionOutcome::CareerComplete) { + driver.stage = TurnDriver::Stage::CareerComplete; + ++driver.revision; + return desk_result(driver, g, TurnDeskKind::CareerComplete); + } + driver.stage = TurnDriver::Stage::MatchdayDesks; + // season_end_steps has already performed the calendar days up to the new + // season's first Wednesday; the next loop starts from that prepared date. + if (!next_event(driver, g, game, rand, report, offer_pending, false, true)) + return fail(driver, g, report, "season transition could not reach a desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } + + // The current manager desk loop is complete, so these flags have no further + // desk to govern. Consume them before match simulation and future event setup. + driver.complete_loaded_manager_loop(); + if (driver.enable_national_nomination_desks && driver.national_nomination_desk) { + // AdvanceTurn's national nomination event has an empty desk, not a + // matchday: Source skips kick_off/play/finish and advances the event + // calendar directly after the pending cleanup performed by App. + driver.national_nomination_desk = false; + event_end(g); + ++g.date; + daily_interest(g, rand); + if (!next_event(driver, g, game, rand, report, offer_pending, true)) + return fail(driver, g, report, "national nomination could not advance to next desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } + // A legacy caller can bind a genuine saved national desk, but it keeps the + // historic matchday path unless the App explicitly opted into this lifecycle. + driver.national_nomination_desk = false; + const auto result_tournament_name = g.tournament_name; + if (!run_current_matchday(driver, g, game, rand, report, events)) + return fail(driver, g, report, "matchday unsupported"); + driver.last_results.valid = true; + driver.last_results.date = g.date; + driver.last_results.calendar_entry = driver.calendar_entry; + driver.last_results.matchday = g.memory.has(::bmh::layout::CurrentMatchday) ? g.memory.u16(::bmh::layout::CurrentMatchday) : 0; + driver.last_results.groups = driver.groups; + driver.last_results.tournament_name = result_tournament_name; + const bool repeat = consume_event_pass(driver, g); + if (!repeat) { + ++g.date; + daily_interest(g, rand); + } + if (!next_event(driver, g, game, rand, report, offer_pending, !repeat, repeat, repeat)) + return fail(driver, g, report, "could not advance to next desk"); + auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk + ? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending); + out.audio_events = std::move(events); + return out; + } catch (const std::exception& ex) { + report.fail(std::string("turn driver exception: ") + ex.what() + " (in " + std::string(turn_step.load()) + ")"); + return fail(driver, g, report, "turn driver exception"); + } +} + +} // namespace bmh diff --git a/src/game/turn_driver.hpp b/src/game/turn_driver.hpp new file mode 100644 index 0000000..3723dc5 --- /dev/null +++ b/src/game/turn_driver.hpp @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "game/match_engine.hpp" +#include "game/desk.hpp" +#include "game/random.hpp" +#include "game/state.hpp" +#include "game/season.hpp" +#include "game/sportschau_presentation.hpp" +#include "game/transfer_allocator.hpp" + +namespace bmh { + +enum class TurnAudioKind { kickoff_whistle, goal, full_time_whistle }; + +// Controller-level sound events carry stable identities. An original cue is optional: +// only attach one when its concrete BMH call site is mapped to a cue by evidence. +struct TurnAudioEvent { + uint64_t session_id = 0; + uint64_t event_id = 0; + TurnAudioKind kind = TurnAudioKind::kickoff_whistle; + std::optional original_id; +}; + +// WaitingAtDesk has not claimed the driver: its original request may be retried. +enum class TurnDeskKind { NextDesk, SeasonEndDesk, CareerComplete, WaitingAtDesk, Failed }; +struct TurnAdvanceRequest { + int manager_slot = -1; + uint64_t revision = 0; +}; +struct TurnAdvanceResult { + TurnDeskKind kind = TurnDeskKind::Failed; + int manager_slot = -1; + uint32_t date = 0; + uint64_t revision = 0; + bool offer_pending = false; + std::string reason; + std::vector audio_events; +}; + +// Read-only-ready copy of the most recently completed human matchday. Kept apart +// from `groups`, which is replaced while seeking the next calendar event. +struct TurnResultSnapshot { + bool valid = false; + uint32_t date = 0; + uint16_t calendar_entry = 0; + uint16_t matchday = 0; + std::vector groups; + // Owned Original-encoded TEXTD slot TournamentName for the completed matchday. + // Cup advancement can rename the indoor tournament before the next desk. + std::vector tournament_name; +}; + +// Runtime state between a desk's kickoff request and the next desk. The group objects, +// referee table, presentation settings and random generators remain owned by the caller/ +// controller for each synchronous advance; only this cursor survives the desk handoff. +struct TurnDriver { + enum class Stage { Empty, MatchdayDesks, SeasonEndDesk, CareerComplete, Failed }; + + Stage stage = Stage::Empty; + uint16_t calendar_entry = 0; + int manager_position = 0; + uint64_t revision = 0; + uint64_t session_id = 0; + uint64_t next_event_id = 1; + // Unsaved program-image flags, supplied by the session's loaded EXE. + // These are independent of the saved indoor/live settings. + bool alternate_match_event_roll = false; // AlternateEventRoll + bool disable_match_events = false; // MatchEventsDisabled + // This unsaved EXE setting also governs the allocator used by weekly and + // season-end transfer-list expiry. + TransferAllocatorContext transfer_allocator_context = TransferAllocatorContext::unsupported; + // Set only when a Native FBM restores an already prepared matchday desk loop. + // It is provenance, not behavior: legacy/headless callers keep their old path. + bool loaded_matchday_resume = false; + // The normal-interactive App sets this after the loaded outgoing desk's staged + // Source batch completes. It suppresses only pre-match offers at later desks. + bool suppress_remaining_pre_match_offers = false; + // Policy is explicitly selected by the normal-interactive App. Legacy and + // headless drivers leave it false, preserving their previous calendar path. + bool enable_national_nomination_desks = false; + // Provenance for the one-manager Source national-only flag nomination desk. This is + // classified from the canonical saved checkpoint or set by fresh next_event; + // empty groups alone never imply a nomination desk. + bool national_nomination_desk = false; + // No further manager desk uses these flags. Consume them at the end of the + // manager-desk phase, before match simulation and annual/future-event processing. + void complete_loaded_manager_loop() noexcept { + loaded_matchday_resume = false; + suppress_remaining_pre_match_offers = false; + } + std::vector groups; + TurnResultSnapshot last_results; + std::vector referee_source; + std::vector referees; + // Optional: called after every minute of a matchday (play_matchday's after_minute) with + // the running engine, groups and state. The app uses it for a manager's intervention in + // his match (EndPhase: the line-up or tactics screen opened from the match, then + // BuildSideRecords3): change the state (e.g. manual_substitution), then + // engine.rerate_team(team, report). Empty = the matchday runs through. + std::function& groups, GameState& g)> live_minute; + std::function original_sound; + // Source PitchScreen pause, emitted synchronously from the event routine before + // the current side/minute resumes. The caller must preserve the size/order and + // MatchGroup object addresses in `groups` until this callback returns because the + // current event and minute iterators hold references into that vector. + std::function& groups, GameState& g)> live_event; + std::function&, + const GameState&)> live_ball; + std::function&, + const GameState&)> live_chance; + std::function&, + const GameState&)> live_shot; + std::function&, + const GameState&)> live_set_piece; + std::function&, + const GameState&)> live_booking; + std::function&, + const GameState&)> live_shootout; + // Legacy programmatic drivers have no executable provider. CareerSession + // supplies its loaded image for the actual Source Reality match path. + const LeImage* reality_rules = nullptr; + std::function&, + const GameState&)> live_reality; + // Exact league/cup half/full-time requests from the existing phase barrier. + std::function&, + const GameState&)> phase_results; + // Empty by default. These callbacks observe the Source intro/group/fixture + // presentation boundaries and receive immutable projections only. + SportschauPresentationHooks sportschau; + SportschauSourceOptions sportschau_source; + DeskAutosaveHook desk_autosave; + // Presentation pauses at the existing Source season-transition checkpoints. + // The callback borrows const state and cannot run desk actions while advancing. + std::function season_pause; + // GameEndAlternateScoreScreen update-only before duration decrement, then update/display on completion. + std::function season_highscore; + SeasonTaxHooks season_tax; + SeasonPromotionHook season_promotion; + SeasonCupDrawHook season_cup_draw; +}; + +// Bind an event already prepared by prepare_event and with its first human desk open. +// No generators are drawn here; the object becomes the only accepted continuation for it. +bool begin_turn_driver(TurnDriver& driver, const GameState& g, std::vector groups, + uint16_t calendar_entry, std::vector referees, + uint64_t session_id, uint64_t revision, std::string& error); + +// Accept the current desk's advance request, show the next manager desk when applicable, +// then play the event in the background and advance through calendar days to the next desk. +// Rejected/stale requests leave state and both random generators untouched. +TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, GameState& g, + const TurnAdvanceRequest& request, + GameRandom& game, WatcomRandom& rand, + MinuteReport& report); + +} // namespace bmh diff --git a/src/game/week.cpp b/src/game/week.cpp new file mode 100644 index 0000000..a76836b --- /dev/null +++ b/src/game/week.cpp @@ -0,0 +1,394 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/week.hpp" + +#include "game/matchday.hpp" +#include "game/lineup.hpp" +#include "game/schedule.hpp" + +#include + +namespace bmh { + +namespace { + +constexpr size_t kManagerRecord = 0xB0C; + +int32_t rd32(const std::vector& v, size_t o) { + return int32_t(uint32_t(v.at(o)) | uint32_t(v.at(o + 1)) << 8 | uint32_t(v.at(o + 2)) << 16 | uint32_t(v.at(o + 3)) << 24); +} +void wr32(std::vector& v, size_t o, int32_t x) { + for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(uint32_t(x) >> (8 * i)); +} + +} // namespace + +void daily_interest(GameState& g, WatcomRandom& rand) { + // (DailyInterest before the day step: the training camp visits of today are over) + for (size_t m = 0; m < g.manager_teams.size(); m++) g.manager_records.at(m * kManagerRecord + 0x21f) &= 0x7f; + for (int k = 0; k < 4; k++) { + const size_t rec = size_t(k) * kManagerRecord; + const int32_t balance = rd32(g.manager_records, rec + 0x314); + const int32_t deposit = rd32(g.manager_records, rec + 0x318); + const int32_t credit = rd32(g.manager_records, rec + 0x31c); + int32_t amount = 0; // positive = cost + if (balance < 0) { + if (balance + credit < 0) amount = ((balance + credit) * 18) / -36500; + int32_t used = -credit < balance ? balance : -credit; + amount += (used * 12) / -36500; + wr32(g.manager_records, rec + 0x89c, rd32(g.manager_records, rec + 0x89c) + amount); + book_money(g, k, amount, true); + amount = 0; + } else { + amount = balance / -36500; + } + amount += ((deposit / 10000) * 20000) / -36500; + wr32(g.manager_records, rec + 0x870, rd32(g.manager_records, rec + 0x870) - amount); + book_money(g, k, amount, true); + if (rd32(g.manager_records, rec + 0x314) > 100000000) { // read again after the bookings + int32_t extra = int32_t(rand.range(10000, 20000)) * 1000; + // BookMoney2 with the statistics flag set: counts as an expense (+0x8a0) + wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + extra); + book_money(g, k, extra, true); + } + } +} + +} // namespace bmh + +namespace bmh { + +namespace { + +uint16_t rd16w(const std::vector& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); } +void wr16w(std::vector& v, size_t o, uint16_t x) { + v.at(o) = uint8_t(x); + v.at(o + 1) = uint8_t(x >> 8); +} +int8_t clamp8(int v, int lo, int hi) { // Int8T on a signed char + int8_t c = int8_t(v); + int s = c < lo ? lo : c; + if (s > hi) s = hi; + return int8_t(s); +} + +// Training areas (WeekRuntimeField shift, WeekRuntimeField2 mask): 0 condition, 1 technique (w35c), +// 2-8 the seven skills (w368, 2 bits each). +constexpr uint8_t kAreaShift[9] = {14, 7, 12, 10, 8, 6, 4, 2, 0}; +constexpr uint8_t kAreaMask[9] = {127, 127, 3, 3, 3, 3, 3, 3, 3}; +constexpr uint8_t kIntensityValue[4] = {0, 80, 100, 120}; // WeekRuntimeField3 +constexpr int8_t kFamiliarityStep[4] = {0, -4, 0, 4}; // WeekRuntimeField4 + +// Attribute: read (write = false) or change an attribute by `delta` within 0..max. +int attribute(Player& p, int area, bool write, int delta, int max) { + uint32_t& word = area < 2 ? p.w35c : p.w368; + const int shift = kAreaShift[area], mask = kAreaMask[area]; + int v = int(int32_t(word) >> shift) & mask; + if (!write) return v; + int8_t n = clamp8(int8_t(delta + v), 0, max); + word = (word & ~(uint32_t(mask) << shift)) | uint32_t(int32_t(n)) << shift; + return 0; +} + +} // namespace + +int weekday_code(uint32_t date) { + int c = int(date % 7) + 2; + if (c > 6) c = int(date % 7) - 5; + return c; +} + +void familiarity_decay(GameState& g, GameRandom& game, WatcomRandom& rand) { + for (size_t k = 0; k < g.manager_teams.size(); k++) { + const int team = g.manager_teams[k]; + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const int player = g.squad_slots.at(s) & 0x0FFF; + if (player == 0xFFF) continue; + const Player& p = g.players.at(player); + uint8_t& used = g.tactics.at(k * 0x840 + (s - range.first) * 0x58 + 0xf); + int r = rand.range(0, 2); + uint8_t rate = uint8_t(r + 4); + if (p.condition() < p.technique()) rate = uint8_t(r + 6); + if (unsigned(rand.range(12, 16)) < ((p.w364 >> 21) & 0x1F)) rate = uint8_t(rate + 2); + int16_t cap = int16_t(8 - int16_t(rd16w(g.manager_records, k * 0xB0C + 0x8b0)) / 0x113); + if (team == kNoTeam) cap = 8; + if (cap < int16_t(rate)) rate = uint8_t(cap); + // the player pool of a manager without a club: a low value is drawn afresh + // (game generator) + if (team == kNoTeam && used < 0x1e) used = uint8_t(game.range(0x18, 0x30)); + used = uint8_t(used - used / rate); + } + } +} + +void train_squad(GameState& g, int manager, GameRandom& game, WatcomRandom& rand) { + const size_t rec = size_t(manager) * 0xB0C; + uint8_t table[4][9]; + for (int pos = 0; pos < 4; pos++) + for (int a = 0; a < 9; a++) + table[pos][a] = uint8_t(kIntensityValue[int8_t(g.manager_records.at(rec + 0xc5 + pos))] + + kIntensityValue[int8_t(g.manager_records.at(rec + 0xc9 + a))]); + const int team = int16_t(rd16w(g.manager_records, rec + 0x290)); + const SquadRange range = squad_range(team); + const int league = team_league(team); + const int16_t quality = int16_t(rd16w(g.manager_records, rec + 0x8ac)); + uint8_t max_value[9] = {99, 99, 3, 3, 3, 3, 3, 3, 3}; // WeekRuntimeField5 + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t entry = g.squad_slots.at(s); + if (entry == 0x0FFF) continue; + const int player = entry & 0x0FFF; + Player& p = g.players.at(player); + const size_t board = size_t(manager) * 0x840 + (s - range.first) * 0x58; + const uint32_t w364 = p.w364; + const int games = int32_t(w364) >> 26; + const int pos = int(w364 & 3); + int8_t used_delta = 0; // local_48 + int8_t trend = 0; // local_54 + const uint8_t used = g.tactics.at(board + 0xf); + const int intensity = g.tactics.at(board + 0xa) & 3; + int second = 10; // local_4c + int focus = (g.tactics.at(board + 0xa) >> 2) + 1; // local_58 + if (attribute(p, focus < 9 ? focus : 8, false, 0, 0) < 3) { + do { + second = game.range(2, 8); + } while (second == focus); + } else { + focus = 10; + } + for (int a = 0; a < 9; a++) { + // register EDI of the original: a value from an earlier branch may survive + uint32_t edi = uint32_t(pos * 9 + a); + int ebx = table[pos][a] + quality / 110 - 5; + if (rand.range(0, 4) == 0) used_delta = int8_t(used_delta + int8_t(g.manager_records.at(rec + 0xc5 + a)) * 2 - 4); + ebx = (int(uint16_t(ebx)) + kIntensityValue[intensity]) / 3; + uint8_t rest = uint8_t(0xa0 - used); + if (rest > 100) rest = 100; + ebx = (int(uint16_t(ebx)) + rest) / 2 - 0x50; + if (focus == a) ebx += 8; + if (second == a) ebx -= 8; + int sign; + if (uint16_t(ebx) < 20) { + sign = -1; + ebx = 20 - ebx; + } else { + sign = 1; + ebx -= 20; + } + // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// FocusAreaGetsAtLeastStrengthBelow (supported rule profile): the focus area gets at least strength 5 below + uint32_t reg = uint16_t(ebx); + if (focus == a) reg |= 0x10000; + if (sign == 1) { + edi = 3; + if (g.league_rounds.at(league) / 3 > games) { + reg = 0; // no match practice yet: no progress + } else { + edi = (w364 >> 21) & 0x1F; // age - 16 + if (rand.range(13, 40) < int(edi)) reg = 0; // older players progress less + } + } + if (a > 1) { + edi = uint32_t(a); + if (table[pos][a] < 0x6e && game.range(0, 50) == 0) max_value[a] = 2; + } + if (game.range(0, 8) == 0) { + // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// Int9 (supported rule profile) + uint32_t dx = reg & 0xFFFF; + if ((reg & 0x10000) && dx < 5) dx = 5; + edi = dx * 15; + reg &= 0xFFFF; + if (int(edi) > game.range(0, 0x96)) attribute(p, a, true, sign, int8_t(max_value[a])); + } + (void)edi; + if (a > 1) max_value[a] = 3; + if (reg & 0xFFFF) trend = int8_t(trend + sign); + } + used_delta = clamp8(used_delta, -15, 15); + g.tactics.at(board + 0xf) = uint8_t(g.tactics.at(board + 0xf) + kFamiliarityStep[intensity] + used_delta); + trend = int8_t(trend / int8_t(game.range(1, 4))); + trend = clamp8(trend, -1, 1); + g.tactics.at(board + 0xe) = uint8_t((g.tactics.at(board + 0xe) & 0x3F) + uint8_t((trend + 1) << 6)); + g.tactics.at(board + 0xf) = uint8_t(clamp8(int8_t(g.tactics.at(board + 0xf)), 0x18, 99)); + } + // the assistant's training plan (training automatic on) + if (g.manager_options.at(size_t(manager) * 5 + 4) & 1) auto_training(g, manager); +} + +void auto_training(GameState& g, int manager) { + uint8_t& option = g.manager_options.at(size_t(manager) * 5 + 4); // CareerSessionRuntimeField3 + if (!(option & 0x80)) option = 0x9f; + const uint8_t flags = (option & 1) ? option : 0; // local_14 + const size_t rec = size_t(manager) * 0xB0C; + const int team = int16_t(rd16w(g.manager_records, rec + 0x290)); + uint8_t plan[13]; + for (int i = 0; i < 13; i++) plan[i] = g.manager_records.at(rec + 0xc5 + size_t(i)); + // QuoteNationalFriendlyMatch for keepers, defence, midfield, attack and the whole team (WeekRuntimeField6) + static constexpr uint16_t kPositions[5] = {0x1f, 0x2f, 0x4f, 0x8f, 0xff}; + int value[5]; + for (int i = 0; i < 5; i++) value[i] = team_average(g, team, kPositions[i]).value; + int16_t order[7]; + uint32_t key[7]; + if (flags & 2) { + for (int i = 0; i < 4; i++) { + plan[i] = 2; + order[i] = int16_t(i); + key[i] = uint32_t((value[i] * 100) / value[4]); + } + quicksort_by_key(order, key, 4, true); // Games ascending + for (int i = 0; i < 2; i++) + if (key[i] < 0x62) plan[order[i]] = 3, plan[order[3 - i]] = 1; + } + const int condition = team_average(g, team, 0xf1).value, technique = team_average(g, team, 0xf2).value; + if (flags & 4) { + plan[4] = 2, plan[5] = 2; + if (condition - 1 > technique) plan[4] = 1, plan[5] = 3; + if (technique - 1 > condition) plan[4] = 3, plan[5] = 1; + } + for (int i = 0; i < 7; i++) { + if (flags & 4) plan[6 + i] = 2; + order[i] = int16_t(i); + key[i] = 0x32; + } + const SquadRange range = squad_range(team); + for (size_t s = range.first; s < range.first + range.count; s++) { + const uint16_t v = g.squad_slots.at(s); + if (v == kEmptySlot) continue; + const Player& p = g.players.at(v & 0x0FFF); + uint8_t* board = &g.tactics.at(size_t(manager) * 0x840 + (s - range.first) * 0x58); + if (flags & 8) { + uint8_t intensity = 2; + if (board[0xf] < 0x1f) intensity = 3; + if (board[0xf] > 0x3c) intensity = 1; + board[10] = uint8_t((board[10] & 0xfc) | intensity); + } + // the skills 6..0 (w368 bits 12..0, Attribute with WeekRuntimeField/WeekRuntimeField2, index 2..8): + // + 1 for a player at 0 (WeekRuntimeField7), - 1 at 3 (WeekRuntimeField8) + bool at_top[8] = {}; // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus. +// by index k = 7 - skill (the supported rule profile patch's bit pairs) + for (int i = 0; i < 7; i++) { + const int skill = 6 - i; + const int level = int(p.w368 >> (2 * skill) & 3); + at_top[i + 1] = level == 3; + if (level == 0) key[i]++; + if (level == 3) key[i]--; + } + if (flags & 0x10) { + // Position: the skill to train (+0x0a bits 2-4) is kept unless it is at 3; + // else the first of the position's order (nibbles of Week_AutoTraining_ExecutableField3, Week_AutoTraining_ExecutableField4, Week_AutoTraining_ExecutableField2, + // Week_AutoTraining_ExecutableField, low first, each 2 * k) that is not at 3 yet + static constexpr uint32_t kOrder[4] = {::bmh::layout::Week_AutoTraining_ExecutableField3, ::bmh::layout::Week_AutoTraining_ExecutableField4, ::bmh::layout::Week_AutoTraining_ExecutableField2, ::bmh::layout::Week_AutoTraining_ExecutableField}; + const int current = (board[10] >> 2) & 7; + if (current == 0 || at_top[current]) { + for (uint32_t list = kOrder[p.position()]; (list & 0xf) != 0; list >>= 4) { + const int k = int(list & 0xf) / 2; + if (!at_top[k]) { + board[10] = uint8_t((board[10] & 3) | (k << 2)); + break; + } + } + } + } + } + quicksort_by_key(order, key, 7); // Games descending + if (flags & 4) + for (int i = 0; i < 3; i++) + if (key[i] > 0x34) plan[6 + order[i]] = 3, plan[6 + order[6 - i]] = 1; + for (int i = 0; i < 13; i++) g.manager_records.at(rec + 0xc5 + size_t(i)) = plan[i]; +} + +void stock_market(GameState& g, GameRandom& game) { + auto u32 = [&](size_t o) { + return uint32_t(g.stocks.at(o) | g.stocks.at(o + 1) << 8 | g.stocks.at(o + 2) << 16 | uint32_t(g.stocks.at(o + 3)) << 24); + }; + auto w32 = [&](size_t o, uint32_t x) { + for (int i = 0; i < 4; i++) g.stocks.at(o + i) = uint8_t(x >> (8 * i)); + }; + for (int k = 0; k < 12; k++) w32(size_t(k) * 0x5c, u32(size_t(k) * 0x5c) + u32(size_t(k) * 0x5c) * 3 / 10000); + for (int k = 0; k < 12; k++) { + const size_t s = size_t(k) * 0x5c; + const uint32_t base = u32(s) / 300; + int v = rd16w(g.stocks, s + 0x4e) / 3 + (g.stocks.at(s + 0x58) - 1); + if (v < 10) v = 10; + uint8_t& trend = g.stocks.at(s + 0x58); + uint8_t& left = g.stocks.at(s + 0x59); + if (left != 0) left--; + if (left == 0) { + trend = uint8_t(game.range(0, 1) * 2); + left = uint8_t(game.range(2, (trend != 0) + 8)); + } + if (game.range(0, 400 - k * 25) == 0) { + int dir = game.range(0, 1); + v += game.range(v / 5, v / 2) * (dir * 2 - 1); + if (game.range(0, 3) != 0) { + int d2 = game.range(0, 1); + w32(s, uint32_t(v * 300 + (d2 * 2 - 1) * 3000)); + } + } + if (game.range(0, 0x16 - k) == 0) { + int dir = game.range(0, 1); + v += game.range(2, 10) * (dir * 2 - 1); + if (game.range(0, 3) == 0) { + int d2 = game.range(0, 1); + int m = game.range(2, 10); + w32(s, uint32_t(int32_t(u32(s)) + (d2 * 2 - 1) * m * 300)); + } + } + if (game.range(0, 0x5a) == 0 && (v + 0x14 < int(base) || int(base) < v - 0x14)) { + int dir = game.range(0, 1); + int m = game.range(2, 10); + v = (dir * 2 - 1) * m + int(base); + } + if (game.range(0, 1) != 0) v += game.range(0, 2) - 1; + if (int(base) < v) { + if (trend == 2) v--; + } else if (game.range(0, 1) != 0) { + if (trend == 2) v--; + } + if (v < int(base)) { + if (trend == 0) v++; + } else if (game.range(0, 1) != 0) { + if (trend == 0) v++; + } + std::copy(g.stocks.begin() + s + 0x16, g.stocks.begin() + s + 0x16 + 0x3a, g.stocks.begin() + s + 0x14); + if (v < 10) { + v = 10; + w32(s, 3000); + } + if (v > 2000) { + v = 1000; + w32(s, 300000); + for (int i = 0; i < 4; i++) wr16w(g.stocks, s + 0x50 + i * 2, uint16_t(rd16w(g.stocks, s + 0x50 + i * 2) << 1)); + } + wr16w(g.stocks, s + 0x4e, uint16_t(v * 3)); + } +} + +} // namespace bmh + +namespace bmh { + +int month_code(uint32_t date) { + // DeskState_DeskDate_RuntimeField: days per month (index 1-12; February 29 in leap years) + uint8_t days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + int leap = 3; // sVar4: 4 = the current year is a leap year + while (date > uint32_t((leap == 4 ? 1 : 0) + 0x16c)) { + if (leap == 4) { + leap = 0; + date--; + } + date -= 0x16d; + leap++; + } + days[2] = uint8_t((leap == 4 ? 1 : 0) + 0x1c); + int month = 7; + while (date > days[month]) { + date -= days[month]; + month = month == 12 ? 1 : month + 1; + } + if (date + 1 > days[month]) month = month == 12 ? 1 : month + 1; + return month; +} + +} // namespace bmh diff --git a/src/game/week.hpp b/src/game/week.hpp new file mode 100644 index 0000000..beb901d --- /dev/null +++ b/src/game/week.hpp @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum. +// Between the matchdays: the day processing (BMH.exe V2.24 + supported rule profile patch). +// +// "Weiter" (DailyInterest) handles the event of the current day (AdvanceTurn, e.g. a +// matchday) and then advances day by day (DaysIntoSeason = day of the season, CalendarDay = +// day counter) until the calendar (block CompetitionCalendar) has the next event. Every day runs +// DayStepRest: +// - date + 1, DailyInterest2(1): interest on every human manager's account +// - training and weekly processing on the Source weekday boundary +// - month_change and the national coach's temporary club handback +// day_step_rest in turn.cpp owns those steps; DailyInterest3 advances shares. + +#include + +#include "game/random.hpp" +#include "game/state.hpp" + +namespace bmh { + +// DailyInterest2(1): daily interest for the four manager slots. Balance (record +0x314) +// earns 1 % a year, the fixed deposit (+0x318) 2 %; an overdraft costs 12 % a year, beyond +// the credit line (+0x31c) 18 % (booked to +0x89c). Income goes to +0x870. A balance over +// 100 million triggers a random extra booking (WatcomRandom 10000-20000 thousand). +// Every day step starts with it, so it also does what DailyInterest does right before the day +// step: bit 7 of record +0x21f (a training camp visit booked today, BookTrainingCamp) is +// cleared for every manager. +void daily_interest(GameState& g, WatcomRandom& rand); + +} // namespace bmh + +namespace bmh { + +// DeskDate2 (weekday part): CareerSession_PairingsRuntimeDraw_ExecutableField6 of a day counter. +int weekday_code(uint32_t date); + +// FamiliarityDecay (training days): the players of human managers slowly forget their places +// on the tactics board (slot byte 0x0f), faster when condition < technique and when older. +void familiarity_decay(GameState& g, GameRandom& game, WatcomRandom& rand); + +// TrainSquad: training of one human manager's squad (on training days). At the end, with +// the training automatic on (option byte 4 bit 0, CareerSessionRuntimeField3), auto_training. +void train_squad(GameState& g, int manager, GameRandom& game, WatcomRandom& rand); + +// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum. +// Initialize (+ the supported rule profile patch Position / WeekOperation): the assistant's training +// plan. Option byte 4 (CareerSessionRuntimeField3) holds what he decides - without bit 7 it becomes 0x9f +// (everything), without bit 0 nothing. The plan (record +0xc5, 13 bytes, 1 light 2 normal +// 3 hard) starts from the manager's own: +// bit 1, bytes 0-3: the team value (QuoteNationalFriendlyMatch 0x1f/0x2f/0x4f/0x8f) of keepers, +// defence, midfield, attack in percent of the whole team (0xff); the two weakest +// below 98 % train hard, the two strongest then light - sorted ascending, +// bit 2, bytes 4-5: condition (0xf1) against technique (0xf2): the weaker one hard when +// they differ by more than one, +// bit 2, bytes 6-12: the skills 6..0 of w368: 50 + players at 0 - players at 3, sorted +// descending; the three most needed (over 52) hard, their opposite numbers light. +// Per player of the squad on the tactics board: +// bit 3, +0x0a bits 0-1: the intensity after the familiarity +0x0f (below 31 hard, above +// 60 light), +// bit 4, +0x0a bits 2-4: the skill to train (supported rule profile): kept unless it is at 3 already, +// else the first not yet at 3 in the order of the position (keeper 7,6,3,4,5; +// defence 3,6,4,7,5; midfield 4,6,5,7,3; attack 5,6,4,7,3 - index k = skill 7 - k). +void auto_training(GameState& g, int manager); + +// DailyInterest3: the daily moves of the 12 shares (block StockExchange). +void stock_market(GameState& g, GameRandom& game); + +} // namespace bmh + +namespace bmh { + +// DeskDate2 (month part): CareerSession_PairingsRuntimeDraw_ExecutableField5 (1-12) of a day counter. Day 0 is in July; the +// year has 365 days, every fourth one 366 (February 29). +int month_code(uint32_t date); + +} // namespace bmh diff --git a/src/game/weekly.cpp b/src/game/weekly.cpp new file mode 100644 index 0000000..e4671fa --- /dev/null +++ b/src/game/weekly.cpp @@ -0,0 +1,2985 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "game/weekly.hpp" +#include "game/pending_offer.hpp" +#include "game/human_buyer_sale.hpp" +#include "game/transfer_bid.hpp" + +#include +#include +#include +#include +#include + +#include "game/lineup.hpp" +#include "game/match.hpp" +#include "game/messages.hpp" +#include "game/month.hpp" +#include "game/prediction.hpp" +#include "game/matchday.hpp" +#include "game/matchday_setup.hpp" +#include "game/schedule.hpp" +#include "game/table.hpp" +#include "game/national.hpp" +#include "game/bank_credit.hpp" + +namespace bmh { + +namespace { + +constexpr size_t kRecord = 0xB0C; // manager record +constexpr size_t kBoard = 0x840; // tactics board of a manager +constexpr size_t kBoardSlot = 0x58; +constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 entries of 0x58 bytes, one per pool slot +constexpr uint32_t kListEntry = 0x58; +constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField: first squad slot of the transfer pool +constexpr int kLeagueClubs = 0x8a; // CareerSession_DispatchLineup_RuntimeField +constexpr int kBigSquadClubs = 90; // TeamsWithSquads + +// Offers and incidents (Bool): 1 in WeeklyRuntimeField[kind] is only possible while the +// league is not in its last rounds. +constexpr uint8_t kOfferLate[16] = {0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0}; // WeeklyRuntimeField +constexpr int kShareFactor[6] = {15, 18, 21, 24, 27, 30}; // MonthRuntimeField10 +// Facilities (30 entries of 5 bytes at layout field): [0] weight in the club rating, +// [2] / [3] the range of the months a renewed facility lasts (x 4 weeks). +constexpr uint8_t kFacility[152] = { + 0x02, 0x2d, 0x0f, 0x1e, 0x00, 0x03, 0x1e, 0x0f, 0x16, 0x00, 0x03, 0x1c, 0x0f, 0x16, 0x00, 0x07, 0x28, 0x16, 0x1e, + 0x00, 0x06, 0x1e, 0x0d, 0x13, 0x00, 0x02, 0x14, 0x0f, 0x16, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x06, 0x07, + 0x0c, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x06, 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x01, 0x05, + 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x01, 0x05, 0x07, 0x0c, 0x00, 0x02, 0x0f, 0x0c, 0x10, 0x00, 0x01, + 0x0c, 0x0c, 0x10, 0x00, 0x02, 0x19, 0x12, 0x16, 0x00, 0x01, 0x14, 0x12, 0x16, 0x00, 0x01, 0x04, 0x03, 0x06, 0x00, + 0x02, 0x07, 0x04, 0x07, 0x00, 0x02, 0x09, 0x04, 0x07, 0x00, 0x03, 0x05, 0x05, 0x07, 0x00, 0x00, 0x1e, 0x1e, 0x32, + 0x00, 0x00, 0x25, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, 0x32, 0x00, 0x00, 0x19, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, + 0x32, 0x00, 0x00, 0x25, 0x1e, 0x32, 0x00, 0x00, 0x1e, 0x1e, 0x32, 0x00, 0x00, 0x19, 0x1e, 0x32, 0x00, 0x02, 0x06}; +// Season ticket compensation per league (CareerSession_FormatError_RuntimeField5, int; leagues above 4 read on). +constexpr uint8_t kTicketRefund[36] = {0x14, 0, 0, 0, 0x12, 0, 0, 0, 0x10, 0, 0, 0, 0x10, 0, 0, 0, 0x0f, 0, 0, 0, + 0x02, 0x7d, 0xe0, 0xcd, 0x00, 0x8f, 0x00, 0x11, 0x01, 0xc9, 0x00, 0xf3, + 0x00, 0x6d, 0x00, 0x22}; +// Transfer interest: required strength per league (LeagueStrengthRanges, every second byte) and by +// table position (WeeklyRuntimeField2). +constexpr uint8_t kLeagueLevel[20] = {0x47, 0x5d, 0x31, 0x47, 0x1c, 0x31, 0x1c, 0x31, 0x0a, 0x1c, + 0x55, 0x5f, 0x5a, 0x5f, 0x4b, 0x5f, 0x50, 0x5f, 0x5a, 0x00}; +constexpr uint8_t kPositionLevel[24] = {0x17, 0x16, 0x15, 0x13, 0x12, 0x11, 0x10, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, + 0x09, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x00, 0xe6, 0xee, 0xf3, 0xf9}; +// Players a club wants per position (MonthRuntimeField4 big squads, MonthRuntimeField5 small squads). +constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4}; +// Advertising: European cup bonus by EuropeanClub (SeasonRuntimeField11) and cup winners +// (SeasonRuntimeField12 entries of the cup table, bonus SeasonRuntimeField13, premium SeasonRuntimeField14). +constexpr int8_t kEuropeBonus[4] = {0, 1, 3, 2}; +constexpr uint8_t kWinnerEntry[4] = {0x00, 0x0f, 0x13, 0x15}; +constexpr int8_t kWinnerBonus[4] = {0x14, 0x1e, 0x14, 0x0f}; +constexpr int32_t kWinnerPremium[4] = {500000, 1500000, 2500000, 1500000}; +// Statistics: value of the facilities (BalancePlanRuntimeField5, u16 per facility). +constexpr uint16_t kFacilityValue[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600, + 2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000}; + +struct Record { + std::vector& r; + size_t base; + uint8_t& b(size_t o) { return r.at(base + o); } + int16_t i16(size_t o) const { return int16_t(r.at(base + o) | r.at(base + o + 1) << 8); } + uint16_t u16(size_t o) const { return uint16_t(r.at(base + o) | r.at(base + o + 1) << 8); } + int32_t i32(size_t o) const { return int32_t(uint32_t(u16(o)) | uint32_t(u16(o + 2)) << 16); } + uint32_t u32(size_t o) const { return uint32_t(u16(o)) | uint32_t(u16(o + 2)) << 16; } + void set16(size_t o, uint16_t v) { r.at(base + o) = uint8_t(v), r.at(base + o + 1) = uint8_t(v >> 8); } + void set32(size_t o, uint32_t v) { set16(o, uint16_t(v)), set16(o + 2, uint16_t(v >> 16)); } +}; +Record record(GameState& g, int manager) { return Record{g.manager_records, size_t(manager) * kRecord}; } + +// The special post-desk adapter retains FindManagerForClub's active-count lookup: +// inactive original records1..3 are AI clubs, while the coach's parked club is +// recognized as native record4. Ordinary/legacy callers keep their old lookup. +int pending_native_manager_of(const GameState& g, int team, bool native_takeover) { + const int active = g.manager_of(team); + if (active >= 0 || !native_takeover || g.manager_teams.size() != 1 || + g.manager_teams[0] != kNoTeam || 4*kRecord+0x292 > g.manager_records.size()) + return active; + const size_t base = 4*kRecord+0x290; + const int parked = int(g.manager_records[base]) | (int(g.manager_records[base+1])<<8); + return parked == team ? 4 : -1; +} + +// Validate the opt-in against the actual AdvanceTurn/DispatchClubPlayerPendingOffers coordinates. It +// cannot turn an ordinary/day-step/poach request into a national pending sale. +bool source_pending_owner_valid(const GameState& g,const SourcePendingOwner& owner,int entry,size_t slot) { + const auto& mem=g.memory; + if(entry<40 || entry>=44 || slot!=kPoolSlots+size_t(entry) || slot>=g.squad_slots.size() || + g.manager_teams!=std::vector{kNoTeam} || g.manager_records.size()<5*kRecord || + g.tactics.size()<5*kBoard || !mem.has(::bmh::layout::CoachActive) || !mem.u8(::bmh::layout::CoachActive) || + !mem.has(::bmh::layout::OriginalManagerCount) || mem.u8(::bmh::layout::OriginalManagerCount)<1 || mem.u8(::bmh::layout::OriginalManagerCount)>4 || + !mem.has(::bmh::layout::ManagerCount) || mem.u8(::bmh::layout::ManagerCount)!=1 || !mem.has(::bmh::layout::PendingOffer_PendingOfferOwnerTeam_RuntimeField) || + !mem.has(::bmh::layout::DeskPosition) || mem.u8(::bmh::layout::DeskPosition)!=0 || !mem.has(::bmh::layout::ActiveManager) || + owner.manager<0 || owner.manager>=mem.u8(::bmh::layout::OriginalManagerCount) || + mem.u16(::bmh::layout::NextDeskManager)!=owner.manager || mem.u8(::bmh::layout::ActiveManager)!=owner.manager || + !mem.has(::bmh::layout::OfferSlots+uint32_t(entry-40)*4+3))return false; + const auto team=[&](int manager){const size_t at=size_t(manager)*kRecord+0x290; + return int(g.manager_records[at]) | int(g.manager_records[at+1])<<8;}; + if(team(0)!=kNoTeam || team(4)<0 || team(4)>=kLeagueClubs || + team(owner.manager)!=owner.team || + (owner.manager==0 ? owner.team!=kNoTeam : owner.team<0 || owner.team>=kLeagueClubs))return false; + const uint32_t list=kTransferList+uint32_t(entry)*kListEntry; + if(!mem.has(list+kListEntry-1) || mem.u16(list+2)!=0xffff || + mem.u16(list+4)!=0xffff || mem.u16(list+6)!=0xffff)return false; + const uint32_t word=mem.u32(::bmh::layout::OfferSlots+uint32_t(entry-40)*4); + return word!=0xffffffffu && int(word&31)==owner.manager && + int((word>>10)&0x0fff)==int(g.squad_slots[slot]&0x0fff); +} + +int league_of(int team) { return team > 0x164 ? 0 : team_league(team); } // TeamLeague2 + +} // namespace + +// Nationality: nationality of a player (w368 bits 27-31, +32 for the flag in *PlayerBonuses). +int nationality(const GameState& g, int player) { + player &= 0xFFF; + return int(g.players.at(size_t(player)).w368 >> 27) + ((g.player_bonus.at(size_t(player)) & 0x80) >> 2); +} + +// SquadCount(team, flags): players of a club (bit 1: the injured too) plus, with bit 0, +// the players it has bought for later (table Career_RemoveJoinLoans_RuntimeField, 200 entries). +int squad_count(const GameState& g, int team, int flags) { + const SquadRange range = squad_range(team); + int n = 0; + for (size_t i = 0; i < range.count; i++) { + const int p = g.squad_slots.at(range.first + i) & 0xFFF; + if (p != 0xFFF && ((flags & 2) || ((g.players.at(size_t(p)).w364 >> 16) & 0x1F) == 0)) n++; + } + if (flags & 1) + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && ((e >> 12) & 0x3FF) == uint32_t(team & 0xFFFF)) n++; + } + return n & 0xFF; +} + +// SlotTeam: club of an absolute squad slot (-1 for the pool). +int slot_team(int slot) { + if (slot < kBigSquadClubs * 24) return slot / 24; + if (slot < int(kPoolSlots)) return (slot - kBigSquadClubs * 24) / 16 + kBigSquadClubs; + return -1; +} + +// Add32 / FacilityRating2: the club's rating of its facilities. +int facility_rating(GameState& g, int manager, int* second, WatcomRandom* rand) { + Record rec = record(g, manager); + int sum = 0x14, first = 0, closed = 0; + *second = 0; + if (g.memory.u8(::bmh::layout::GameMode) == 1) { + int league = rec.b(0x210); + if (league > 2) league--; + return 0x50 - league * 0x14; + } + for (int i = 0; i < 0x16; i++) { + const uint8_t v = rec.b(size_t(i)); + if (v == 0) continue; + int level; + if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? (v - 1) / 0x55 + 1 : 1; + else level = rec.b(size_t(i) + 0x2e) & 7; + sum += (level & 0xFF) * kFacility[i * 5]; + } + for (int i = 0; i < 8; i++) { + if (rec.b(0x34 + size_t(i)) != 0) { + // a stand under construction costs 10-12 % (only drawn for the attendance) + if (rand) closed += rand->range(10, 12); + continue; + } + if (rec.b(0x44 + size_t(i)) & 1) first += rec.b(0x4c + size_t(i)); + if (rec.b(0x44 + size_t(i)) & 2) *second += rec.b(0x4c + size_t(i)); + } + const int seats = rec.b(0x5c); + if (seats == 0) { + *second = 0; + first = 0; + } else { + first = first * 100 / seats; + *second = *second * 100 / seats; + } + return (((100 - closed) * sum / 100 + first / 4 + (*second >> 4)) * 0x5a) / 0x72 + 0x18; +} + +void manager_offers(GameState& g, int manager, WatcomRandom& rand, MinuteReport& report) { + if (g.memory.u32(::bmh::layout::CompetitionSelection) == 2) return; + Record rec = record(g, manager); + const bool events_off = false; // OpenBMH deviates from the original: uses the supported weekly-event configuration, with its rule switch disabled. +// WeeklyEventsDisabled (0 in the supported rule profile) + const uint8_t weeks = g.memory.u8(::bmh::layout::CareerDuration); + for (int kind = 0; kind < 16; kind++) { + if ((kind == 11 || kind == 12) && weeks == 1) continue; + if (kind == 7) continue; + if (kind == 9) { + if (rand.range(0, 1) != 0 && !events_off) continue; + if (g.memory.u32(::bmh::layout::Loans + uint32_t(manager) * 0x78) == 0) continue; + } + if ((kind == 13 || kind == 15) && rand.range(0, 1) != 0 && !events_off) continue; + int sum = 0; // ESI (kind 14: dividends) + if (kind == 14) { + for (int k = 0; k < 6; k++) { + const uint32_t held = g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(k) * 0x1c); + const uint32_t value = uint32_t(g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareFactor[k])) / 10000; + sum += int(uint32_t(rand.range(10, 20)) * (held * value)); + } + if (sum == 0) continue; + } + if (kind <= 7 && rec.b(0x170 + size_t(kind)) != 0) continue; + if (!events_off && rand.range(0, (0x39 - g.level) * 0xd - kOfferLate[kind] * 0x16c) != 0) continue; + if (kOfferLate[kind] != 0 && g.league_rounds.at(rec.b(0x210)) >= 0x14) continue; + int league = rec.b(0x210); + if (league > 2) league--; + uint8_t value = 0; // local_18 + // the message: the offer's text (pointer table Weekly_ManagerOffers_TextPointer6) plus details + std::string msg = kind < 15 ? message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer6 + uint32_t(kind) * 4) : std::string(); + switch (kind) { + case 0: { + // the main sponsor pays a part of a transfer: text + position + amount limits + const int text = rand.range(0, 3); + msg += message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer) + message_text(g, ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer2 + uint32_t(text) * 4) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer2); + const int a = rand.range(1, 7), b = rand.range(1, 7); + value = uint8_t(text + uint8_t(a << 2) + uint8_t(b << 5)); + break; + } + case 1: + case 2: { + const int a = rand.range(1, 7), b = rand.range(1, 7); + value = uint8_t(uint8_t(a << 2) + uint8_t(b << 5)); + break; + } + case 3: + value = uint8_t(rand.range(10, 20)); + msg += format_number(g, value * (4 - league) * 1000, 0x101) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer3); + break; + case 4: + value = uint8_t(rand.range(4, 20)); + msg += format_number(g, value * 1000, 0x101) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer4); + break; + case 5: { + const int seats = rec.b(0x5c) * 1000; + const int r = rand.range(0x46, 100); + sum = ((0x14 - league * 2) * (seats * r / 100)) / 10000 * 10000; + value = uint8_t(sum / 10000); + break; + } + case 6: + sum = (4 - league) * 50000; + value = uint8_t(rand.range(5, 10)); + msg += format_number(g, sum, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) + format_number(g, value, 1) + message_text(g, ::bmh::layout::Weekly_ManagerOffers_TextPointer5); + break; + case 8: + value = uint8_t(rand.range(5, (4 - league) * 5 + 10)); + rec.b(0x170 + 8) = value; + break; + case 9: + value = uint8_t(rand.range(1, 3) * 10); + if (!change_bank_credit_interest(g, manager, value)) { + report.fail("weekly offer: unavailable credit factors (ChangeBankCreditInterest)"); + return; + } + break; + default: break; + } + if (kind < 10 && kind != 5 && kind != 8) { + rec.b(0x170 + size_t(kind)) = value; + post_composed(g, manager, msg); // PostMessage + continue; + } + // The other offers ask the manager (PresentManagerDialog with JA/NEIN, a message box only). + // GameState::offer_answer decides (the replays decline unless told otherwise). + if (!g.offer_answer) { + if (kind == 14) { + // declined dividends: with 1 in 2 the payment comes anyway, twice (WeeklyRuntimeField3), + // else WeeklyRuntimeField4 - both message boxes only + if (rand.range(0, 1) == 0) book_money(g, manager, sum * 2, true); + } + continue; + } + switch (kind) { + case 5: rec.b(0x170 + 5) = value; break; + case 8: + rec.b(0x170 + 8) = 0; + book_money(g, manager, int32_t(value) * 10000, true); + break; + case 10: + // insurance for every tactics board slot without one (slot byte 0x43) + for (size_t s = 0; s < 0x18; s++) { + uint8_t& cover = g.tactics.at(size_t(manager) * 0x840 + s * 0x58 + 0x43); + if (cover == 0) cover = 0x4c; + } + break; + case 11: + // the advertising contracts (record +0xa34, 18 of 12 bytes: amount, +5 months + // left) are extended by a year, up to 36 months + for (size_t c = 0; c < 0x12; c++) { + const size_t at = 0xa34 + c * 0xc; + if (rec.i32(at) != 0 && int8_t(rec.b(at + 5)) < 0x24) rec.b(at + 5) = uint8_t(rec.b(at + 5) + 0xc); + } + break; + case 12: + // the advertising contracts are renegotiated: W(50, 150) % each + for (size_t c = 0; c < 0x12; c++) { + const size_t at = 0xa34 + c * 0xc; + if (rec.i32(at) != 0) rec.set32(at, uint32_t(rec.i32(at) * rand.range(0x32, 0x96) / 100)); + } + break; + case 13: book_money(g, manager, 4, true); break; // (4 EU, as in the original) + case 14: book_money(g, manager, sum, true); break; + default: break; + } + } +} + +void season_ticket_compensation_source(GameState& g, int manager, + const SeasonTicketCompensationNoticeHook& notice) { + Record rec = record(g, manager); + rec.b(0x5c) = 0; + for (int i = 0; i < 8; i++) + if (rec.b(0x34 + size_t(i)) == 0) rec.b(0x5c) = uint8_t(rec.b(0x5c) + rec.b(0x4c + size_t(i))); + int missing = int(rec.u16(0x2ac)) - rec.b(0x5c) * 1000; + if (missing <= 0) return; + const int league = league_of(int16_t(rec.u16(0x290))); + int weeks = 0x11 - g.league_rounds.at(size_t(league)); + if (weeks > 0xf) weeks = 0xf; + const int32_t per = int32_t(kTicketRefund[league * 4] | kTicketRefund[league * 4 + 1] << 8 | + kTicketRefund[league * 4 + 2] << 16 | uint32_t(kTicketRefund[league * 4 + 3]) << 24); + // Source uses 32-bit IMULs, then passes the signed dword to BookMoney2. + // Unsigned intermediates make the wrap explicit without C++ signed UB. + const uint32_t week_rate = uint32_t(weeks) * uint32_t(per); + const int32_t amount = std::bit_cast(uint32_t(missing) * week_rate); + if (notice) notice(g, {manager, missing, int(rec.b(0x5c)) * 1000, weeks, amount}); + book_money(g, manager, amount, true, true); + rec.set16(0x2ac, uint16_t(rec.b(0x5c) * 1000)); +} + +void season_ticket_compensation(GameState& g, int manager) { + season_ticket_compensation_source(g, manager); +} + +void facility_ageing(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + (void)report; + Record rec = record(g, manager); + uint8_t& weeks = g.memory.at(::bmh::layout::Savestate_Layout_ExecutableField); + if (manager == 0) weeks++; + if (weeks == 0xc) weeks = 0; + if (weeks % (rand.range(0, 1) + 3) == 0) g.memory.set32(::bmh::layout::CareerSession_Invalid_RuntimeField2, uint32_t(game.seed())); // the game generator seed is saved + // "Ihr Sparkurs laesst Ihr Stadion langsam verfallen ... BETROFFEN: " for a + // facility that decays (local_c is set once per call and never cleared: after the first + // message every further decay of the call is reported, even one that would not be) + bool message = false; + for (int i = 0; i < 0x1e; i++) { + if (weeks == 0 && rec.b(size_t(i)) != 0 && rec.b(0x1e + size_t(i)) == 0) { + uint8_t& v = rec.b(size_t(i)); + v--; + if ((i == 0 && v % 0x55 == 0) || rec.b(0x1e + size_t(i)) + v == 0) { + if (i < 0xe) { + message = true; + } else if (i < 0x16) { + uint8_t& n = rec.b(0x2e + size_t(i)); + if (n > 1) { + message = true; + if (--n != 0) v = uint8_t(kFacility[i * 5 + 2] << 2); + } + } else { + const size_t k = 0x4c + size_t(i - 0x16); + if (rec.b(0x5c) != 0 && rec.b(k) != 0) { + message = true; + rec.b(k) = uint8_t(rec.b(k) / 3); + if (rec.b(k) != 0) v = uint8_t(kFacility[i * 5 + 2] << 2); + } + } + if (message) post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_FacilityAgeing_TextPointer) + message_text(g, ::bmh::layout::Stadium_RenderPanorama_TextPointer + uint32_t(i) * 4)); + } + } + uint8_t& build = rec.b(0x1e + size_t(i)); + if (build != 0 && --build == 0) { + uint8_t& v = rec.b(size_t(i)); + if (i == 0) v = uint8_t((v == 0 ? 1 : (v - 1) / 0x55 + 2) * 0x55); + else v = uint8_t(rand.range(kFacility[i * 5 + 2], kFacility[i * 5 + 3]) << 2); + if (i > 0xd) { + rec.b(0x2e + size_t(i)) = uint8_t((rec.b(0x2e + size_t(i)) >> 4) & 7); + if (i > 0x15) { + rec.b(0x36 + size_t(i)) = rec.b(0x3e + size_t(i)); + rec.b(0x3e + size_t(i)) = 0; + } + } + } + } + season_ticket_compensation(g, manager); +} + +void facility_damage(GameState& g, int manager, GameRandom& game, WatcomRandom& rand) { + Record rec = record(g, manager); + bool forced = false; // BH: an announced damage (record +0x178) + const int level = g.level; + if (rec.b(0x178) != 0 && rand.range(0, 0x34) == 0) forced = true; + if (!forced) { + if (!(level > rand.range(0, 0xaf))) return season_ticket_compensation(g, manager); + const int league = rec.b(0x210); + if (!(rand.range(1, 3) > league)) return season_ticket_compensation(g, manager); + } + // The message is composed from pointer tables of TEXTD.BLK: articles Weekly_FacilityDamage_TextPointer2 (the + // index tables WeeklyRuntimeField5/WeeklyRuntimeField6/WeeklyRuntimeField7 pick the right one), facility names Stadium_RenderPanorama_TextPointer, + // causes Weekly_FacilityDamage_TextPointer (0-4 at random, 5 for an announced damage). + static constexpr uint8_t kCauseArticle[6] = {0, 1, 7, 3, 1, 0}; // WeeklyRuntimeField5 + static constexpr uint8_t kCauseArticleBy[6] = {6, 2, 8, 3, 9, 6}; // WeeklyRuntimeField6 + static constexpr uint8_t kFacilityArticle[0x1e] = {0, 5, 4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 5, // WeeklyRuntimeField7 + 5, 5, 5, 4, 4, 4, 5, 5, 5, 5, 4, 5, 5, 5, 4}; + auto article = [&](int k) { return message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer2 + uint32_t(k) * 4); }; + auto facility = [&](int k) { return message_text(g, ::bmh::layout::Stadium_RenderPanorama_TextPointer + uint32_t(k) * 4); }; + auto cause = [&](int k) { return message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer + uint32_t(k) * 4); }; + std::string text; + int which = game.range(0, 0x1d); + if (forced) which = game.range(1, 0x1d); + if (which == 0) { + for (int k = 0; k < 6; k++) { + const int i = rand.range(8, 0xf); + if (rec.b(0x3c + size_t(i)) & 2) { + rec.b(0x3c + size_t(i)) &= 0xFD; + post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer4) + message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer3 + uint32_t(i) * 4) + message_text(g, ::bmh::layout::Weekly_FacilityDamage_TextPointer5)); + break; + } + } + return season_ticket_compensation(g, manager); + } + const size_t i = size_t(which); + if (rec.b(i) == 0 || rec.b(0x1e + i) != 0) return season_ticket_compensation(g, manager); + int half = rand.range(0, (which < 0xe) + 1); + if (rec.b(i) < 2) half = 0; + if (forced) rec.b(0x178) = 0; + if (half == 0) { + rec.b(i) = 0; + if (which < 0xe) { + const int c = forced ? 5 : rand.range(0, 4); + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer) + article(kCauseArticle[c]) + cause(c) + + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer2); + } else if (which < 0x16) { + uint8_t& lvl = rec.b(0x2e + i); + if (lvl > 1 || (lvl == 2 && (which == 0x10 || which == 0x11))) { + if (rand.range(0, 2) == 0) lvl = 1; + else lvl--; + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer3); + } + } else if (rec.b(0x5c) != 0 && int(rec.b(0x42)) < rand.range(1, 3)) { + int k; + do { + k = rand.range(0, 7); + } while (rec.b(0x4c + size_t(k)) == 0); + text = message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer4) + facility(k + 0x16) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer5); + rec.b(0x4c + size_t(k)) = 0; + } + } else { + rec.b(i) = uint8_t(rec.b(i) >> 1); + const int c = forced ? 5 : rand.range(0, 4); + text = article(kFacilityArticle[i]) + facility(which) + message_text(g, ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer6) + article(kCauseArticleBy[c]) + cause(c) + + message_text(g, which > 0x11 && which < 0x16 ? ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer7 : ::bmh::layout::Weekly_SeasonTicketCompensation_TextPointer8); + } + if (!text.empty()) post_composed(g, manager, text); // PostMessage + season_ticket_compensation(g, manager); +} + +// ClubAttraction(team, 0): the attraction of a club for advertisers (0-100). +int club_attraction(const GameState& g, int team) { + // EuropeanClub: which European cup the club still plays in + int europe = 0; + const struct { uint32_t list, count; } cups[3] = {{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}}; + for (int c = 0; c < 3 && europe == 0; c++) + for (int k = 0; k < int(int8_t(g.memory.u8(cups[c].count))); k++) + if (g.memory.u16(cups[c].list + uint32_t(k) * 2) == uint16_t(team)) { + europe = c + 1; + break; + } + int8_t bonus = int8_t(kEuropeBonus[europe] * 10 + 10); + if (team == int(g.memory.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6))) bonus = int8_t(bonus + 10); + for (int k = 0; k < 4; k++) + if (g.memory.u16(::bmh::layout::Season_CareerSeasonSetup_RuntimeField + uint32_t(kWinnerEntry[k]) * 0x28) == uint16_t(team)) bonus = int8_t(bonus + kWinnerBonus[k]); + const int strength = uint16_t(team_average(g, team, 0xff).value); + int position = int8_t(table_position(g, team)); + if (position == -1) position = 10; + int league = int8_t(league_of(team)); + if (league > 2) league--; + const int place = uint16_t((4 - league) * 0x16 + (0x14 - position)); + int v = int16_t(place * 40 / 108 + strength * 2 / 10 + bonus * 4 / 5); + return std::clamp(v, 0, 100); +} + +void advertising_offers(GameState& g, int manager, WatcomRandom& rand, MinuteReport& report) { + (void)report; + if (g.memory.u8(::bmh::layout::CareerDuration) == 1) return; + Record rec = record(g, manager); + if (manager == 0) { + // "Es gibt neue Werbeangebote!" to every manager with a free advertising slot + uint32_t mask = 0x80000000u; + for (size_t m = 0; m < g.manager_teams.size(); m++) + for (int k = 0; k < 0x10; k++) + if (g.manager_records.at(m * kRecord + 0xa39 + size_t(k) * 0xc) == 0) mask |= 1u << m; + if (mask != 0x80000000u) post_text(g, int64_t(mask), text_id(::bmh::layout::Weekly_AdvertisingOffers_TextPointer)); + } + int score = int16_t(int8_t(club_attraction(g, int16_t(rec.u16(0x290))))); + if (g.memory.u8(::bmh::layout::GameMode) == 3 && g.league_rounds.at(size_t(league_of(int16_t(rec.u16(0x290))))) > 0x11) { + int t = rec.i32(0x320) / 100000; + t = std::clamp(t, -10, 10); + score = std::clamp(int(int16_t(score + t)), 0, 100); + } + const int fans = rec.i16(0x8b4) * 100 / 0x226 - 100; + score = int16_t(score) + fans / 5; + if (int16_t(score) < 0) score = 0; + score = int16_t(score) * 100 / 0x78; + int base = (int16_t(score) * 60000 + 1000000) / 0xc; + base = ((0xb4 - g.level * 5) * base) / 100; + for (int kind = 0; kind < 3; kind++) + for (int k = 0; k < 10; k++) { + const size_t o = 0x8cc + size_t(kind) * 0x78 + size_t(k) * 0xc; + rec.b(o + 7) = uint8_t(k); + const int r = rand.range(0, (k * 2) / 3 + 5 - rec.i16(0x8b4) / 0x14); + if (int16_t(r) != 0) continue; + if ((k >= 5 && kind == 2) || rand.range(0, 0xb) <= k) { + rec.set32(o, 0); + continue; + } + int part, percent = 0; + if (kind == 0) { + part = (base / 2) / 8; + percent = k * 6 + 0x46; + } else { + part = base >> 2; + percent = kind == 1 ? k * 4 + 0x50 : k * 4 + 0x5a; + } + const int v = percent * part / 100; + rec.set32(o, uint32_t(rand.range(v - (v >> 2), v + (v >> 2)))); + if (kind == 0 && rand.range(0, 5) == 0) rec.b(o + 4) = uint8_t(rand.range(2, 3)); + else rec.b(o + 4) = 1; + rec.b(o + 5) = uint8_t(rand.range(1, 2)); + if (rand.range(0, 5) != 0) rec.b(o + 6) = 0; + else rec.b(o + 6) = uint8_t(rand.range(1, 3 - int8_t(rec.b(o + 5))) * 0xc); + rec.b(o + 5) = uint8_t(rec.b(o + 5) * 0xc); + rec.set16(o + 8, uint16_t(score)); + } +} + +void transfer_bid(GameState& g, int slot, uint32_t list, bool high, int months, GameRandom& game, WatcomRandom& rand, + MinuteReport& report) { + StaticMemory& mem = g.memory; + const int own = slot_team(slot); + int free_bid = 0; // local_14 + if (list != 0) { + while (free_bid < 4 && int16_t(mem.u16(list + uint32_t(free_bid) * 2)) != -1) free_bid++; + if (free_bid == 4) return; + } + const int player = g.squad_slots.at(size_t(slot)) & 0xFFF; + const int nat = nationality(g, player) & 0xFF; + const uint32_t w35c = g.players.at(size_t(player)).w35c; + const int position = g.players.at(size_t(player)).w364 & 3; + const int half = int(((w35c >> 14) & 0x7F) + ((w35c >> 7) & 0x7F)) >> 1; // local_5c + bool first_pass = true; // local_34 + uint8_t foreign_skip = 0; // local_1c + int bonus_need = 0; // local_4c: the value of the last club rated (not of the chosen one) + for (;;) { + std::vector teams; + std::vector keys; + std::vector needs; + int region = 0; // local_20 (not reset between the clubs) + for (int team = 0; team < kLeagueClubs; team++) { + if (team == own || g.manager_of(team) >= 0) continue; + if (team >= kBigSquadClubs) region = team_region(team) & 0xFF; + if (own >= 0 && g.manager_of(own) >= 0 && list != 0 && (w35c >> 27) != 0 && game.range(0, 0xf) != 0) continue; + if (first_pass && nat < 5 && nat != region && foreign_skip++ % 10 == 0) continue; + const int players = squad_count(g, team, 3); + if (region == 0 && players > 0x15) continue; + if (region != 0 && players > 0xf) continue; + int avg[4]; + int count[4]; + for (int p = 0; p < 4; p++) { + const TeamAverage a = team_average(g, team, uint16_t((1 << (p + 4)) + 3)); + avg[p] = int16_t(a.value); + count[p] = a.players; + } + int score = (region == nat || nat > 4) ? 0x46 : 0; + int16_t strength = 0; + for (int p = 0; p < 4; p++) strength = int16_t(strength + avg[p]); + strength = int16_t(strength >> 2); + const int league = league_of(team); + int need = 0; // local_4c + if (g.league_rounds.at(size_t(league)) > 10) { + const int pos = int8_t(table_position(g, team)); + const int16_t wanted = int16_t(kLeagueLevel[league * 2] + kPositionLevel[pos]); + if (strength < wanted && strength < int16_t(half)) need = wanted - strength; + } + const int diff = std::abs(half - strength); // Abs2 + const int r = rand.range(int16_t(need) + 3, int16_t(need) + 0xd); + if (int16_t(diff) < r) score += int(int16_t(need + 0xe - diff)) * 16 + 100; + else score -= int16_t(diff) * 8; + const int8_t* wanted = team < kBigSquadClubs ? kWantedBig : kWantedSmall; + int16_t d = int16_t(wanted[position] - int8_t(count[position])); + if (d < 0) { + score += int(d) << 8; + } else { + d = int16_t(d + 1); + if (position == 0 && int8_t(count[0]) < 2) d = int16_t(d + (2 - int8_t(count[0])) * 4); + score += int(d) << 6; + if (score > 1) { + if (strength > rand.range(0x5a, 0x62) && int16_t(diff) < rand.range(0, 0x14)) score += rand.range(10, 0x28); + score += ((g.team_flags.at(size_t(team)) >> 14) & 3) << 4; + } + } + int16_t limit = int16_t((region == 0 ? 3 : 0) + 0xe); + int cnt = players; + if (int16_t(cnt) < limit) { + // (a bug of the original: it counts the club among the bidders of entry 40) + int8_t twice = 0; + for (int b = 0; b < 4; b++) + if (mem.u16(kTransferList + 40 * kListEntry + uint32_t(b) * 2) == uint16_t(team)) twice++; + cnt = uint8_t(cnt + twice / 2); + limit = int16_t(limit - cnt); + if (limit > 0 && int16_t(diff) < limit * 5 + 10) score += int(limit) << 7; + } + keys.push_back(uint32_t(score + 100000)); + teams.push_back(int16_t(team)); + needs.push_back(need); + bonus_need = need; + } + int chosen = -1, index = -1; + const int n = int(teams.size()); + if (n != 0) { + // Games sorts both lists; the need of the chosen club is kept separately + std::vector order(static_cast(n)); + for (int i = 0; i < n; i++) order[size_t(i)] = int16_t(i); + std::vector sorted = keys; + quicksort_by_key(order.data(), sorted.data(), n); + for (index = 0; index < n; index++) { + const int team = teams[size_t(order[size_t(index)])]; + int slots = int(squad_range(team).count); + if (list != 0) + for (int b = 0; b < 4; b++) + if (mem.u16(list + uint32_t(b) * 2) == uint16_t(team)) { + slots = 0; + break; + } + const bool reject = g.manager_of(team) >= 0 || (list != 0 && team == (mem.u16(list + 8) & 0x7FFF)) || slots == 0; + if (!reject) { + chosen = team; + break; + } + } + // The key of the chosen club is read with the club id as index (a bug: MOV EAX, + // [ESP + club * 4] at 00017ecd, the key array holds 138 entries). Beyond the + // candidates of this call the slot keeps whatever an earlier call left on the stack; + // it only matters through clamp(key / 0x50, 0, 4) below, and any bid key of an + // earlier call (score + 100000) gives the top level 4. The number of draws is the + // same either way, only the size of the bid could differ. + // (Known gap: the stale slot lies 0x1cc-0x218 bytes below the caller's stack + // pointer and holds whatever the functions DayStepRest3 called before left there. + // Level 4 matches WEEK21->22; in the summer of WEEK42->43 the original had level 0 + // for a bid of day 337, so only the amounts of such bids may differ. Season 2 shows + // level 0 as well (WEEK57, WEEK65: the salary factor gives r = W(90, 95)), so the + // slot then holds no bid key at all - a key would always give level 4 - but data + // of another function at that stack depth; WEEK42/44/59/63 fit neither 0 nor 4. + // A different amount can change which bid wins later (WEEK149, day 1275: another + // club got the player, the line-ups and then the injury rolls went apart).) + if (chosen >= 0) keys[0] = chosen < n ? sorted[size_t(chosen)] : 4 * 0x50; + } + if (chosen < 0) { + if (list != 0) return; + if (first_pass) { + first_pass = false; + continue; + } + report.fail("transfer: no club found (internal error 0x2a)"); + return; + } + if (list == 0) { + // no list entry: the player moves straight to the club (its first empty squad + // slot, FirstFreeSlotSquad), which gets a new line-up (Int2(club, 100)) + const SquadRange r = squad_range(chosen); + int free = -1; + for (size_t s = r.first; s < r.first + r.count && free < 0; s++) + if (g.squad_slots.at(s) == 0x0FFF) free = int(s); + if (free < 0) { + report.fail("transfer: no room in the club's squad (internal error 0x2c)"); + return; + } + g.squad_slots.at(size_t(free)) = uint16_t(player); + try { + auto_lineup(g, chosen, 100); + } catch (const std::exception& ex) { + report.fail(std::string("line-up after a transfer: ") + ex.what()); + } + return; + } + mem.set16(list + uint32_t(free_bid) * 2, uint16_t(chosen)); + if (mem.u16(list + 8) == 0xffe) { + mem.set8(list + 0x34 + uint32_t(free_bid), uint8_t(uint8_t(months) * 0xc)); + } else { + bool loan = rand.range(0, 6) == 4; + if (mem.u16(list + 8) == 0xfff) loan = false; + const int m = rand.range(1, 4 - (loan ? 3 : 0)); + mem.set8(list + 0x34 + uint32_t(free_bid), uint8_t(uint8_t(m * 0xc) | (loan ? 0x80 : 0))); + if (loan && rand.range(0, 10) > 7) mem.set8(list + 0x34 + uint32_t(free_bid), 0x98); + } + // RateTransferBidSource: fee and salary bases of the offer + const uint8_t term = mem.u8(list + 0x34 + uint32_t(free_bid)); + uint32_t fee_base = (mem.u32(list + 0x2c) / 10000) * 0x30d4; + if (term & 0x80) fee_base >>= 2; + const int years = ((term & 0x7F) - 1) / 0xc; + const uint32_t salary_base = ((uint32_t(years * 0x14 + 100) * mem.u32(list + 0x30)) / 10000) * 100; + uint32_t k = keys[0] / 0x50; + int16_t level = int16_t(std::clamp(int(int16_t(k)), 0, 4)); + level = int16_t(level + ((g.team_flags.at(size_t(chosen)) >> 14) & 3)); + const uint32_t r = uint32_t(rand.range(0x5a, level * 5 + 0x5f)); + uint32_t factor = (r * uint32_t(int16_t(bonus_need) + 100)) / 100; + if (high) factor = uint32_t(rand.range(0x78, 0x96)); + mem.set32(list + 0x1c + uint32_t(free_bid) * 4, ((factor * fee_base) / 1000000) * 10000); + mem.set32(list + 0x0c + uint32_t(free_bid) * 4, ((salary_base * r) / 10000) * 100); + for (int i = 0; i < 7; i++) mem.set8(list + 0x38 + uint32_t(free_bid) * 7 + uint32_t(i), 0); + return; + } +} + +namespace { + +// RateTransferBidSource: fee and salary bases of bid `bid` of a list entry (-1: none, a one-year +// term): the fee base is the market value / 10000 * 12500 (a quarter for a loan), the +// salary base the salary * (100 + 20 per extra contract year) / 100. +void offer_bases(const StaticMemory& mem, uint32_t list, int bid, uint32_t& fee_base, uint32_t& salary_base) { + bool loan = false; + uint8_t years = 1; + if (bid != -1) { + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + loan = (term & 0x80) != 0; + years = uint8_t(((term & 0x7F) - 1) / 0xc); + } + fee_base = (mem.u32(list + 0x2c) / 10000) * 0x30d4; + if (loan) fee_base >>= 2; + salary_base = ((uint32_t(years * 0x14 + 100) * mem.u32(list + 0x30)) / 10000) * 100; +} + +// ProjectTransferOfferList: how good bid `bid` is, as percentages of the bases (fee, salary); a fee +// below W(90, 100) % or a salary below the player's demand (entry +0x55) counts 0. +bool evaluate_bid(GameState& g, uint32_t list, int bid, uint32_t& fee_pct, uint32_t& salary_pct, WatcomRandom& rand, + MinuteReport& report) { + StaticMemory& mem = g.memory; + uint32_t fee_base = 0, salary_base = 0; + offer_bases(mem, list, bid, fee_base, salary_base); + if (fee_base == 0 || salary_base == 0) { + report.fail("transfer list: bid bases 0 (the original divides by zero)"); + return false; + } + fee_pct = uint32_t(int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)) * 100) / fee_base; + const int32_t salary = int32_t(mem.u32(list + 0x0c + uint32_t(bid) * 4)); + uint64_t expected_salary = uint32_t(salary); + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const int manager = g.manager_of(bidder); + if (manager >= 0) { + const int position = int(g.players.at(size_t(g.squad_slots.at(kPoolSlots + size_t(list - kTransferList) / kListEntry) & 0xfff)).w364 & 3); + static constexpr uint8_t goals[4] = {0, 2, 4, 8}; + const uint64_t annual = uint32_t(salary); + expected_salary += annual * mem.u8(list + 0x38 + uint32_t(bid) * 7) * goals[position] / 100 / 12; + expected_salary += annual * mem.u8(list + 0x39 + uint32_t(bid) * 7) * 34 / 100 / 12; + expected_salary += annual * mem.u8(list + 0x3a + uint32_t(bid) * 7) * 25 / 100 / 12; + } + salary_pct = uint32_t(expected_salary * 100 / salary_base); + if (fee_pct < uint32_t(rand.range(0x5a, 100))) fee_pct = 0; + if (salary_pct < mem.u8(list + 0x55)) salary_pct = 0; + return true; +} + +// Pending callers supply their explicit ordinary/special-list-derived Source +// pool index. The shared ProjectTransferOfferList primitive never performs this mapping itself. +bool evaluate_pending_human_bid(GameState& g, uint32_t list, int bid, + uint32_t& fee_pct, uint32_t& salary_pct, + WatcomRandom& rand, MinuteReport& report, + const SourcePendingOwner* owner = nullptr) { + if (list < kTransferList || (list - kTransferList) % kListEntry != 0 || + (list - kTransferList) / kListEntry >= 44 || bid < 0 || bid >= 4 || + !g.memory.has(list + kListEntry - 1)) { + report.fail("ProjectTransferOfferList: invalid pending caller list/bid coordinates"); + return false; + } + const int entry = int((list - kTransferList) / kListEntry); + const size_t slot = kPoolSlots + size_t(entry); + if (slot >= g.squad_slots.size()) { + report.fail("ProjectTransferOfferList: pending caller source slot outside native storage"); + return false; + } + TransferBidRatingRequest request{int(slot), entry, bid, + int(int16_t(g.memory.u16(list + uint32_t(bid) * 2))), + int(g.squad_slots.at(slot) & 0x0fff)}; + if(owner)request.source_pending_owner=*owner; + const auto rating = rate_transfer_bid_source(g, request, rand, report); + fee_pct = rating.fee_pct; + salary_pct = rating.salary_pct; + return rating.supported; +} + +// Foreigners2: players of a club (squad slots start..start+count, plus the ones bought +// for later, table Career_RemoveJoinLoans_RuntimeField) whose nationality differs from `nation`. +int foreigners(const GameState& g, int team, size_t start, size_t count, int nation) { + int n = 0; + for (size_t s = start; s < start + count; s++) { + const int p = g.squad_slots.at(s) & 0xFFF; + if (p != 0xFFF && (nationality(g, p) & 0xFFFF) != nation) n++; + } + for (int k = 0; k < 200; k++) { + const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && ((e >> 12) & 0x3FF) == uint32_t(team) && (nationality(g, int(e & 0xFFF)) & 0xFFFF) != nation) n++; + } + return int8_t(n); +} + +// InterestedManagers(seller, buyer): human managers interested in a transfer: those in the league +// of the seller or the buyer whose club is within 5 table places of one of them (only with +// the option Weekly_InterestedManagers_RuntimeField off and a real seller). +uint32_t interested_managers(const GameState& g, int seller, int buyer) { + uint32_t mask = 0; + if (g.memory.has(::bmh::layout::Weekly_InterestedManagers_RuntimeField) && g.memory.u8(::bmh::layout::Weekly_InterestedManagers_RuntimeField) != 0) return 0; + for (size_t m = 0; m < g.manager_teams.size(); m++) { + if (seller == 0xFFF) continue; + const int league = g.manager_records.at(m * kRecord + 0x210); + if (league_of(seller) != league && league_of(buyer) != league) continue; + const int own = int8_t(table_position(g, g.manager_teams[m])); + if (std::abs(own - int16_t(table_position(g, seller))) > 5 && std::abs(own - int16_t(table_position(g, buyer))) > 5) + continue; + mask |= 1u << m; + } + return mask; +} + +} // namespace + +TransferBidRating rate_transfer_bid_source(GameState& g, const TransferBidRatingRequest& request, + WatcomRandom& rand, MinuteReport& report) { + if (report.unsupported) return {}; + const auto fail = [&](const std::string& why) { + report.fail("ProjectTransferOfferList: " + why); + return TransferBidRating{}; + }; + if (request.list_entry < 0 || request.list_entry >= 44 || + request.bid_slot < 0 || request.bid_slot >= 4 || request.source_slot < 0 || + size_t(request.source_slot) >= g.squad_slots.size()) + return fail("invalid explicit source/list/bid coordinates"); + const uint32_t list = kTransferList + uint32_t(request.list_entry) * kListEntry; + if (!g.memory.has(list + kListEntry - 1)) + return fail("missing native transfer list storage"); + const int player = int(g.squad_slots.at(size_t(request.source_slot)) & 0x0fff); + const int bidder = int(int16_t(g.memory.u16(list + uint32_t(request.bid_slot) * 2))); + if (player == 0x0fff || size_t(player) >= g.players.size() || + player != request.expected_player || bidder != request.expected_bidder || + bidder < 0 || bidder >= kLeagueClubs) + return fail("source player/bidder identity mismatch"); + uint32_t fee_base = 0, salary_base = 0; + offer_bases(g.memory, list, request.bid_slot, fee_base, salary_base); + if (fee_base == 0 || salary_base == 0) + return fail("zero Source denominator (original divide-by-zero boundary)"); + const bool native_takeover=request.source_pending_owner.has_value(); + if(native_takeover && (request.bid_slot!=0 || + !source_pending_owner_valid(g,*request.source_pending_owner,request.list_entry,size_t(request.source_slot)))) + return fail("invalid DispatchClubPlayerPendingOffers native pending owner context"); + const int manager = pending_native_manager_of(g,bidder,native_takeover); + if (manager >= 0) { + const bool parked=manager==4 && native_takeover; + if ((!parked && (manager >= 4 || size_t(manager) >= g.manager_teams.size() || + std::count(g.manager_teams.begin(), g.manager_teams.end(), bidder) != 1)) || + size_t(manager) * kRecord + 0x292 > g.manager_records.size() || + size_t(manager) * kBoard + kBoardSlot > g.tactics.size()) + return fail("unsupported native human bidder record/board"); + const size_t rec = size_t(manager) * kRecord; + const int record_team = int(g.manager_records.at(rec + 0x290)) | + (int(g.manager_records.at(rec + 0x291)) << 8); + if (record_team != bidder) + return fail("bidder manager record and runtime team disagree"); + const auto range = squad_range(bidder); + if (range.count == 0 || range.first + range.count > g.squad_slots.size()) + return fail("bidder fitness squad outside native storage"); + for (size_t slot = range.first; slot < range.first + range.count; ++slot) { + const uint16_t word = g.squad_slots.at(slot); + if (word != 0x0fff && (word & kSlotInLineup) && + size_t(word & 0x0fff) >= g.players.size()) + return fail("bidder lineup references an unavailable fitness player"); + } + } + try { + // Void5 mode4 has real divisions by each recent table's games. + // Keep that native error boundary instead of accepting per_game's + // generic zero fallback on an incomplete controlled/malformed season. + if (manager >= 0) { + const int league = team_league(bidder); + if (league >= kLeagueCount || size_t(league) >= g.league_rounds.size()) + return fail("missing bidder prediction league"); + const int rounds = int(int8_t(g.league_rounds.at(size_t(league)))); + if (rounds >= 2 && rounds < league_matchdays(league)) { + const auto recent = compute_league_table(g, league, std::max(0, rounds - 5), rounds, 3, 0); + for (int club = 0; club < recent.size; ++club) + if (recent.games(club) == 0) + return fail("zero recent games in Source rank prediction"); + } + } + TransferBidRating rating; + rating.fee_pct = (g.memory.u32(list + 0x1c + uint32_t(request.bid_slot) * 4) * 100u) / fee_base; + uint32_t total_salary = g.memory.u32(list + 0x0c + uint32_t(request.bid_slot) * 4); + if (manager >= 0) { + const size_t board = size_t(manager) * kBoard; + std::array saved{}; + std::copy_n(g.tactics.begin() + std::ptrdiff_t(board), kBoardSlot, saved.begin()); + struct RestoreBoard { + GameState& state; size_t offset; + const std::array& saved; + ~RestoreBoard() { + std::copy(saved.begin(), saved.end(), state.tactics.begin() + std::ptrdiff_t(offset)); + } + } restore{g, board, saved}; + // ProjectTransferOfferList's stack board reads only salary+50 and seven bonuses + // +12. No seller board, actual bidder row, mood or 80% weighting. + for (int b = 0; b < 4; ++b) + g.tactics.at(board + 0x50 + size_t(b)) = uint8_t(total_salary >> (8 * b)); + for (int b = 0; b < 7; ++b) + g.tactics.at(board + 0x12 + size_t(b)) = + g.memory.u8(list + 0x38 + uint32_t(request.bid_slot) * 7 + uint32_t(b)); + total_salary += manager==4 + ? expected_bonus_parked_club_source(g,0xff,0,player,true) + : expected_bonus(g, manager, 0xff, 0, player, true); + } // Restore the full borrowed board before threshold W or any caller. + rating.salary_pct = (total_salary * 100u) / salary_base; + if (rating.fee_pct < uint32_t(rand.range(90, 100))) rating.fee_pct = 0; + if (rating.salary_pct < g.memory.u8(list + 0x55)) rating.salary_pct = 0; + rating.supported = true; + return rating; + } catch (const std::exception& e) { + return fail(e.what()); + } +} + +// Int2(team, 100) for the clubs of a transfer (only clubs with a squad). +static void lineup_after_transfer_impl(GameState& g, int team, bool native_takeover) { + if (pending_native_manager_of(g,team,native_takeover)==4) + auto_lineup_parked_club_source(g,team,100); + else if (team < kLeagueClubs || team == kNoTeam) auto_lineup(g, team, 100); +} + +void lineup_after_transfer(GameState& g, int team) { lineup_after_transfer_impl(g,team,false); } + +// ReleasePlayer closes the seller's squad and native human board gap. +static bool remove_from_seller_impl(GameState& g, int seller, int player, MinuteReport& report, + bool native_takeover) { + player &= 0xFFF; + if (seller == 0xFFF || seller == 0xFFFF) { + for (size_t s = kPoolSlots; s < 3072; s++) // CareerRuntimeField .. LargeSquadClubCount + if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF; + return true; + } + const SquadRange range = squad_range(seller); + size_t at = range.first; + while (at < range.first + range.count && (g.squad_slots[at] & 0xFFF) != player) at++; + if (at == range.first + range.count) { + report.fail("transfer: the player is not in the seller's squad (internal error 0x21)"); + return false; + } + for (size_t s = kPoolSlots; s < 2972; s++) // CareerRuntimeField .. CareerRuntimeField2 + if ((g.squad_slots[s] & 0xFFF) == player) g.squad_slots[s] = 0xFFF; + for (size_t s = at; s + 1 < range.first + range.count; s++) g.squad_slots[s] = g.squad_slots[s + 1]; + g.squad_slots[range.first + range.count - 1] = 0xFFF; + // a human club's tactics board rows (0x58 bytes each) move up with the squad; the last + // row keeps its old content (a copy of the row above), as in the original + const int manager = pending_native_manager_of(g, seller, native_takeover); + const size_t row = at - range.first; + if (manager >= 0 && row != 0x17) { + const size_t base = size_t(manager) * 0x840; + std::copy(g.tactics.begin() + long(base + (row + 1) * 0x58), g.tactics.begin() + long(base + 0x18 * 0x58), + g.tactics.begin() + long(base + row * 0x58)); + } + lineup_after_transfer_impl(g, seller, native_takeover); + return true; +} + +bool remove_from_seller(GameState& g, int seller, int player, MinuteReport& report) { + return remove_from_seller_impl(g,seller,player,report,false); +} + +namespace { + +// Fail(seller, pool slot, buyer, list entry, bid): the player moves to a computer +// club (first free squad slot); a loan is recorded in Career_RemoveJoinLoans_RuntimeField / ClubPlayerDetail_InvalidArgument_RuntimeField. +void move_player(GameState& g, int seller, size_t pool_slot, int buyer, uint32_t list, int bid, WatcomRandom& rand, + MinuteReport& report, TransferAllocatorContext allocator, bool native_takeover = false) { + // The ordinary accepted human-buyer loan route is settled by the shared helper in + // execute_transfer. Keep this fallback guarded for legacy callers without that owner. + (void)allocator; + StaticMemory& mem = g.memory; + const int player = g.squad_slots.at(pool_slot) & 0xFFF; + for (int k = 0; k < 200; k++) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xFFF) == player) { + report.fail("transfer: the player is already bought for later (internal error 0x30)"); + return; + } + } + if (player == 0xFFF) { + report.fail("transfer: no player (internal error 0x31)"); + return; + } + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + const bool loan = term > 0x7F; + const int buyer_manager = pending_native_manager_of(g, buyer, native_takeover); + const int seller_manager = pending_native_manager_of(g, seller, native_takeover); + // Deliberate Original bug fix (#105): record4 parks club manager0 only. + // Fail uses DeskActions_Unsupported_RuntimeField[4], corrupting graphics pointer bbccc, and saves + // snapshot owner4 which cannot match the club after NationalCoachHandBack handback. + // Preserve the actual board4 below, but persist its real club owner0 in + // the existing four-byte counter/snapshot format. Never invent counter4. + const int loan_owner_manager = native_takeover && seller_manager == 4 ? 0 : seller_manager; + int loan_slot = -1; + int owner_snapshot_slot = -1; + int owner_squad_row = -1; + std::array owner_board_snapshot{}; + if (loan) { + if (buyer_manager >= 0) { + report.fail("transfer: loans to a human manager are not supported yet"); + return; + } + // EntryLoanLedgerMustHaveSlotBefore's 200-entry loan ledger must have a slot before any squad/account + // mutation. Keep the existing AI-only path's layout and draw order unchanged. + for (int k = 0; k < 200; ++k) { + if (mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4) == 0) { loan_slot = k; break; } + } + if (loan_slot < 0) { + report.fail("transfer: loan table full (internal error 0x36)"); + return; + } + if (seller_manager >= 0) { + // Fail allows a human owner to lend to a computer club only while + // below the three-loan limit and with a free Source snapshot record. + if (loan_owner_manager >= 4 || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) >= 3 || + !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)) { + report.fail("transfer: no available human-owner loan record"); + return; + } + for (int k = 0; k < 12; ++k) { + if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(k) * 2) == uint16_t(player)) { + report.fail("transfer: player already has a human-owner loan record"); + return; + } + if (owner_snapshot_slot < 0 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(k) * 2) == 0x0fff) + owner_snapshot_slot = k; + } + if (owner_snapshot_slot < 0) { + report.fail("transfer: human-owner loan snapshots full (internal error 0x34)"); + return; + } + const SquadRange owner_range = squad_range(seller); + for (size_t row = 0; row < owner_range.count; ++row) { + if ((g.squad_slots.at(owner_range.first + row) & 0x0fff) == player) { + owner_squad_row = int(row); + break; + } + } + const size_t board = size_t(seller_manager) * 0x840 + + size_t(std::max(owner_squad_row, 0)) * 0x58; + if (owner_squad_row < 0 || board + owner_board_snapshot.size() > g.tactics.size()) { + report.fail("transfer: human-owner loan player has no board row"); + return; + } + std::copy_n(g.tactics.begin() + std::ptrdiff_t(board), owner_board_snapshot.size(), + owner_board_snapshot.begin()); + } + } + // FirstFreeSlotSquad: first free slot of the buyer's squad + const SquadRange range = squad_range(buyer); + size_t slot = range.first; + while (slot < range.first + range.count && g.squad_slots[slot] != 0xFFF) slot++; + if (slot == range.first + range.count) return; // squad full (message box PendingOffer_FormatError_ExecutableField) + g.squad_slots[slot] = uint16_t(player); + if (buyer_manager >= 0) { + const size_t row = slot - range.first; + new_board_entry(g, buyer_manager, int(row), int(slot), rand); + const size_t board = size_t(buyer_manager) * 0x840 + row * 0x58; + const uint32_t salary = mem.u32(list + 0x0c + uint32_t(bid) * 4); + for (int b = 0; b < 4; ++b) g.tactics.at(board + 0x50 + size_t(b)) = uint8_t(salary >> (b * 8)); + g.tactics.at(board + 0x0c) = uint8_t((term & 0x7f) == 0 ? 0x18 : (term & 0x7f)); + // Fail (human buyer): the market salary for the term (AddToSquad at 100 %, + // the term in months as its year count, as the original passes it) ... + uint32_t reference_fee = 0, reference_salary = 0; + market_value(g, int(pool_slot), 0, 100, reference_fee, reference_salary, int(term & 0x7f), 0, rand); + for (int b = 0; b < 7; ++b) g.tactics.at(board + 0x12 + size_t(b)) = mem.u8(list + 0x38 + uint32_t(bid) * 7 + uint32_t(b)); + // ... and his mood (+0x0d): what the contract is worth against it, salary plus 80 % of + // the expected bonus (ContractOffer), 0-255 (ClampInteger). The port left it out, so a + // player bought this way kept the 0 of the new board row and asked for nothing at his + // renewal (#40: HENDERSON 60.900 -> 0, later 8.580). +0x54 is the price paid. + const uint32_t bonus = expected_bonus(g, buyer_manager, 0xff, int(row), player, true); + const int32_t worth = int32_t(salary) + int32_t(bonus * 0x50u) / 100; + const int32_t ratio = reference_salary == 0 ? 0xff : int32_t(uint32_t(worth) * 100u / reference_salary); + g.tactics.at(board + 0x0d) = uint8_t(std::clamp(ratio, 0, 0xff)); + const uint32_t price = mem.u32(list + 0x1c + uint32_t(bid) * 4); + for (int b = 0; b < 4; ++b) g.tactics.at(board + 0x54 + size_t(b)) = uint8_t(price >> (b * 8)); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[move_player mood player %d: salary %u bonus %u reference %u -> %d]\n", player, salary, bonus, + reference_salary, int(g.tactics.at(board + 0x0d))); + book_money(g, buyer_manager, int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), true, true); + } + if (!remove_from_seller_impl(g, seller, player, report, native_takeover)) return; + lineup_after_transfer_impl(g, seller, native_takeover); + lineup_after_transfer_impl(g, buyer, native_takeover); + if (loan) { + // Fail stores the owner's original manager-board row before loaning + // a human-owned player to an AI club. Snapshot bytes and manager mapping stay + // intact after return; Source only frees the player-ID slot and decrements count. + if (seller_manager >= 0) { + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(owner_snapshot_slot) * 0x58; + for (size_t b = 0; b < owner_board_snapshot.size(); ++b) + mem.set8(snapshot + uint32_t(b), owner_board_snapshot[b]); + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(owner_snapshot_slot) * 2, uint16_t(player)); + mem.set8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(owner_snapshot_slot), uint8_t(loan_owner_manager)); + mem.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager), uint8_t(mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) + 1)); + } + // EntryLoanLedgerMustHaveSlotBefore: the player returns to the seller after `term & 0x7f` months. + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan_slot), uint8_t(term & 0x7F)); + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan_slot) * 4, uint32_t(player + seller * 0x1000 + buyer * 0x400000)); + } +} + +// Validate the extra state needed by Fail before execute_transfer emits news or +// books the human owner's fee. move_player repeats the checks immediately before its +// mutations; the caller invokes this first so an unavailable Source loan record cannot +// produce a half-completed transfer. +bool preflight_human_owner_loan(const GameState& g, int seller, size_t pool_slot, int buyer, + MinuteReport& report, bool require_squad_room = true, bool native_takeover = false) { + const int owner_manager = pending_native_manager_of(g, seller, native_takeover); + // Match move_player's explicit #105 correction: board4 belongs to the + // persistent club manager0; bbccc is a graphics pointer, never a counter. + const int loan_owner_manager = native_takeover && owner_manager == 4 ? 0 : owner_manager; + const auto& mem = g.memory; + const int player = g.squad_slots.at(pool_slot) & 0x0fff; + if (seller == 0x0fff) { + report.fail("transfer: Source free-agent loan return destination is not represented"); + return false; + } + if (buyer < 0 || buyer >= kLeagueClubs) { + report.fail("transfer: loan buyer has no squad"); + return false; + } + if (!mem.has(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + 199u * 4u + 3u)) { + report.fail("transfer: loan ledger storage is truncated"); + return false; + } + if (owner_manager >= (native_takeover ? 5 : 4) || (owner_manager >= 0 && (!mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(loan_owner_manager)) >= 3 || !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || + !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)))) { + report.fail("transfer: no available human-owner loan record"); + return false; + } + int snapshot_slot = -1; + int loan_slot = -1; + for (int i = 0; i < 200; ++i) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(i) * 4); + if (e == 0 && loan_slot < 0) loan_slot = i; + else if (e != 0 && int(e & 0x0fff) == player) { + report.fail("transfer: the player is already bought for later (internal error 0x30)"); + return false; + } + } + if (loan_slot < 0) { + report.fail("transfer: loan table full (internal error 0x36)"); + return false; + } + if (owner_manager >= 0) for (int i = 0; i < 12; ++i) { + const uint16_t id = mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2); + if (id == uint16_t(player)) { + report.fail("transfer: player already has a human-owner loan record"); + return false; + } + if (snapshot_slot < 0 && id == 0x0fff) snapshot_slot = i; + } + if (owner_manager >= 0 && snapshot_slot < 0) { + report.fail("transfer: human-owner loan snapshots full (internal error 0x34)"); + return false; + } + const SquadRange seller_range = squad_range(seller); + bool owner_has_player = false; + for (size_t i = 0; i < seller_range.count; ++i) + if ((g.squad_slots.at(seller_range.first + i) & 0x0fff) == player) owner_has_player = true; + if (!owner_has_player) { + report.fail("transfer: the player is not in the seller's squad (internal error 0x21)"); + return false; + } + const size_t board = owner_manager >= 0 ? size_t(owner_manager) * 0x840 : 0; + if (owner_manager >= 0 && (g.tactics.size() < board + 0x18 * 0x58 || !seller_range.count)) { + report.fail("transfer: human-owner loan player has no board row"); + return false; + } + const SquadRange buyer_range = squad_range(buyer); + bool room = false; + for (size_t i = 0; i < buyer_range.count; ++i) + if (g.squad_slots.at(buyer_range.first + i) == 0x0fff) { room = true; break; } + if (require_squad_room && !room) { + report.fail("transfer: buyer squad is full"); + return false; + } + return true; +} + +// The weekly transfer itself (Void2): news for the interested human +// managers (all of them with the option Weekly_ExecuteTransfer_RuntimeField off), then the move. +void execute_transfer(GameState& g, int k, uint32_t list, int bid, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + const int seller = mem.u16(list + 8) & 0x7FFF; // Canonical free-player seller is 0x0fff; FFFF is not its alias. + const int buyer = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const uint8_t term = mem.u8(list + 0x34 + uint32_t(bid)); + const int buyer_manager = g.manager_of(buyer); + // SettleHumanBuyerSale books fees for human managers through the shared settlement. + uint32_t mask = 0x80000000u; + if (!(mem.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && mem.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) mask = 0xFFFFFFFFu; + const uint32_t interested = interested_managers(g, seller, buyer); + const size_t pool_slot = kPoolSlots + size_t(k); + if (term > 0x7f && + !preflight_human_owner_loan(g, seller, pool_slot, buyer, report, buyer_manager < 0)) return; + // SettleHumanBuyerSale/Fail owns ordinary purchases and loans for human 24-slot buyers. + // Require the explicit runtime allocator observation for either contract; + // AI buyers retain the original legacy path. + if (buyer_manager >= 0) { + HumanBuyerSaleHooks hooks; + switch (allocator) { + case TransferAllocatorContext::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case TransferAllocatorContext::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: + report.fail("PendingOfferAnswer: general weekly human-buyer sale has no observed allocator gate"); + return; + } + hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase; + hooks.notice = [&](const GameState&, const HumanBuyerSaleNotice& notice) { + post_composed(g, notice.manager, notice.original_message); + }; + hooks.after_paid_accounts = [&](GameState& state, const HumanBuyerSalePaid& paid) { + uint32_t message_mask = 0x80000000u; + if (paid.seller_manager >= 0) message_mask |= 1u << paid.seller_manager; + if (!(state.memory.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && state.memory.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) + message_mask = 0xffffffffu; + else + message_mask |= 1u << paid.buyer_manager; + const uint32_t interested = interested_managers(state, paid.seller, paid.buyer); + if ((message_mask | interested) == 0x80000000u) return; + const std::string message = message_text(state, ::bmh::layout::Month_SearchProfileNews_TextPointer) + state.player_name(paid.player) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + state.club_name(paid.seller) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + format_number(state, int32_t(paid.raw_fee), 0x101) + + message_text(state, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + state.club_name(paid.buyer) + + message_text(state, (paid.term & 0x80) ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(state, int64_t(message_mask | interested), message); + }; + HumanBuyerSaleRequest request; + request.list_entry = k; + request.bid_slot = bid; + request.list_address = list; + request.source_pool_slot = pool_slot; + request.expected_seller = seller; + request.expected_buyer = buyer; + request.expected_active_manager = mem.has(::bmh::layout::ActiveManager) ? int(mem.u8(::bmh::layout::ActiveManager)) : -1; + request.day_step = true; // (a bid of manager 1 may be decided on manager 2's turn) + const auto settled = settle_human_buyer_sale(g, request, hooks, rand, report); + (void)settled; // Void2 clears the completed list for refused/blocked outcomes too. + return; + } + if ((mask | interested) != 0x80000000u) { + const int32_t fee = int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)); + std::string msg = message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(g.squad_slots.at(pool_slot)) + message_text(g, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + + g.club_name(seller) + message_text(g, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + format_number(g, fee, 0x101) + + message_text(g, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + g.club_name(buyer) + + message_text(g, term > 0x7F ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(g, int64_t(mask | interested), msg); + } + move_player(g, seller, pool_slot, buyer, list, bid, rand, report, allocator); + const int seller_manager = g.manager_of(seller); + if (seller_manager >= 0) + book_money(g, seller_manager, -int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), true, true); +} + +// The bids of an expiring list entry (TransferListCountdown when the countdown reaches 0): every bid +// is rated (fee and salary percentages plus G(0, 10) each, the salary also by the bidder's +// table position), the best one the buyer can afford and has room for gets the player if +// W(90, 110) is below its rating. Returns false when a path is not ported. +bool decide_bids(GameState& g, int k, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + bool preserve_entry = false; + const uint32_t list = kTransferList + uint32_t(k) * kListEntry; + const int player = g.squad_slots.at(kPoolSlots + size_t(k)) & 0xFFF; // local_34 + const int seller = mem.u16(list + 8) & 0x7FFF; + const int seller_manager = g.manager_of(seller); // local_24 / local_1c + int16_t order[4]; + uint32_t score[4]; + int n = 0; + for (; n < 4; n++) { + order[n] = int16_t(n); + if (int16_t(mem.u16(list + uint32_t(n) * 2)) == -1) break; + uint32_t fee = 0, salary = 0; + if (!evaluate_bid(g, list, n, fee, salary, rand, report)) return false; + if (fee == 0 || salary == 0) { + score[n] = 0; + } else { + const int position = int8_t(table_position(g, int16_t(mem.u16(list + uint32_t(n) * 2)))); + salary += uint32_t(game.range(0, 10) + (0x14 - position) / 2); + fee += uint32_t(game.range(0, 10)); + if (fee > 5) fee -= 5; + if (salary > 5) salary -= 5; + score[n] = fee + salary; + } + } + quicksort_by_key(order, score, n); + int c = 0; + for (; c < n; c++) { + const int bid = order[c]; + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const int bidder_manager = g.manager_of(bidder); + if (bidder_manager >= 0) { + const int32_t fee = int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)); + const size_t rec = size_t(bidder_manager) * 0xb0c; + const int32_t balance = int32_t(uint32_t(g.manager_records.at(rec + 0x314)) | + uint32_t(g.manager_records.at(rec + 0x315)) << 8 | uint32_t(g.manager_records.at(rec + 0x316)) << 16 | + uint32_t(g.manager_records.at(rec + 0x317)) << 24); + const int32_t credit = int32_t(uint32_t(g.manager_records.at(rec + 0x31c)) | + uint32_t(g.manager_records.at(rec + 0x31d)) << 8 | uint32_t(g.manager_records.at(rec + 0x31e)) << 16 | + uint32_t(g.manager_records.at(rec + 0x31f)) << 24); + if (int64_t(balance) + credit < fee) { + // the board forbids further talks for financial reasons (Weekly_DecideBids_TextPointer / Weekly_DecideBids_TextPointer2) + post_composed(g, bidder_manager, message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer2)); + continue; + } + } + const SquadRange range = squad_range(bidder); + const int nation = team_region(bidder) & 0xFF; // Foreigners + const int others = foreigners(g, bidder, range.first, range.count, nation); + // The foreigner limit of a computer seller's list (more than three foreigners in the + // bidder's squad, a player of another nation) only stops computer bidders: a human + // bidder goes on to the squad check (TransferListCountdown, `local_28 != 0xff`). + if (seller_manager < 0 && others > 3 && (nationality(g, player) & 0xFFFF) != nation && bidder_manager < 0) continue; + if (squad_count(g, bidder, 3) < int(range.count) - 1) break; // room in the squad + // a full squad: a human bidder hears that the board approves no more transfers (DeskActions_Unsupported_ExecutableField) + if (bidder_manager >= 0) post_text(g, bidder_manager, text_id(::bmh::layout::DeskActions_Unsupported_ExecutableField)); + } + if (c == n) { + // TransferListCountdown sends the expiry notice to the seller and every human bidder. + uint32_t audience = 0x80000000u; + if (seller_manager >= 0) audience |= 1u << seller_manager; + for (int i = 0; i < n; ++i) { + const int manager = g.manager_of(int16_t(mem.u16(list + uint32_t(i) * 2))); + if (manager >= 0) audience |= 1u << manager; + } + if (audience != 0x80000000u) { + const std::string msg = message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_DecideBids_TextPointer3); + post_composed(g, int64_t(audience), msg); + } + } else { + const int bid = order[c]; + const int bidder = int16_t(mem.u16(list + uint32_t(bid) * 2)); + const uint32_t r = uint32_t(rand.range(0x5a, 0x6e)); + bool accept = r < score[c]; + if (seller_manager >= 0) { + if (g.transfer_offer_selector) { + TransferOfferListView view = project_transfer_offer_list(g, k); + if (allocator == TransferAllocatorContext::zero || allocator == TransferAllocatorContext::blocked) + for (auto& offer : view.offers) + if (offer.present && offer.loan && offer.buyer_manager >= 0) + offer.transaction_supported = true; + view.preferred_bid_index = bid; + view.preferred_bid_passed_random_check = accept; + auto refresh_quote = [&]() { + const SquadRange seller_range = squad_range(seller); + size_t seller_slot = seller_range.first; + while (seller_slot < seller_range.first + seller_range.count && + (g.squad_slots.at(seller_slot) & 0x0fff) != player) ++seller_slot; + if (seller_slot >= seller_range.first + seller_range.count || seller_manager < 0 || + size_t(seller_manager) * kBoard + (seller_slot - seller_range.first) * kBoardSlot + 0x0c >= + g.tactics.size()) return false; + const size_t board = size_t(seller_manager) * kBoard + + (seller_slot - seller_range.first) * kBoardSlot; + const int months = g.tactics[board + 0x0c]; + int years = months > 0 ? (months - 1) / 12 + 1 : 1; + if (years > 4) years = 4; + view.quoted_years = uint8_t(years); + const int percent = game.range(0x5c, 0x6c); // OpenTransferEditor: GameRandom + view.quoted_fee = 0; + view.quoted_monthly_salary = 0; + market_value(g, int(kPoolSlots + size_t(k)), 0, percent, + view.quoted_fee, view.quoted_monthly_salary, years, 0, rand); + // OpenTransferEditor passes the seller's own bid slot to RateTransferBidSource + // when one exists, otherwise -1 for the generic asking reference. + int own_bid = -1; + for (int row = 0; row < 4; ++row) { + const int buyer_id = int16_t(mem.u16(list + uint32_t(row) * 2)); + if (buyer_id == -1) break; + if (buyer_id == seller) { own_bid = row; break; } + } + offer_bases(mem, list, own_bid, view.asking_fee, view.asking_monthly_salary); + return true; + }; + if (!refresh_quote()) { + report.fail("transfer offer: seller player has no source quote row"); + return false; + } + int malformed_responses = 0; + while (view.offer_count > 0) { + const int selected = g.transfer_offer_selector(g, view); + if (selected == -1) { + accept = false; + if (g.transfer_decision_observer && !g.transfer_notice_suppressed) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = view; + event.selected_bid_index = -1; + event.accepted = false; + event.viewer_manager = seller_manager; + event.result_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField; // IncomingTransferScreen explicit right-click decline + g.transfer_decision_observer(event); + } + break; + } + if (selected < 0 || selected >= 4 || !view.offers[size_t(selected)].present) { + // The original mouse loop rejects an empty row without a game + // action. The current port cannot complete a human-involved loan + // lifecycle; keep that row unavailable rather than enter a known + // failing transfer/return path. Bound only malformed replies. + view.notice_text_address = 0; + if (++malformed_responses >= 8) { + preserve_entry = true; + break; + } + continue; + } + const TransferOfferCandidateView& chosen = view.offers[size_t(selected)]; + if (chosen.loan && !chosen.loan_permitted) { + // IncomingTransferScreen refuses a loan when DeskActions_Unsupported_RuntimeField[seller] is >= 3, + // displays PendingOffer_PendingOfferNoticeDialog_ExecutableField2, and returns to the same choice screen. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2; + if (!refresh_quote()) return false; + continue; + } + if (chosen.loan && chosen.buyer_manager >= 0 && + (allocator == TransferAllocatorContext::zero || + allocator == TransferAllocatorContext::blocked)) + view.offers[size_t(selected)].transaction_supported = true; + if (!view.offers[size_t(selected)].transaction_supported) { + // A human-involved loan passes the original DeskActions_Unsupported_RuntimeField limit check, + // but this port lacks the board-snapshot/return path. Refuse it + // inertly instead of reaching move_player's known report.fail. + if (++malformed_responses >= 8) { + preserve_entry = true; + break; + } + continue; + } + if (!chosen.affordable) { + // OpenTransferEditor shows DeskActions_SubmitTransferOfferEditorSource_RuntimeField and lets the seller choose again. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::DeskActions_SubmitTransferOfferEditorSource_RuntimeField; + if (!refresh_quote()) return false; + continue; + } + if (!chosen.has_squad_room || !chosen.passes_foreign_limit) { + // Fail reports PendingOffer_FormatError_ExecutableField when the buyer has no free + // place. The foreign-player guard is only reached for a free-agent + // seller; retain it as a defensive boundary here. + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField; + if (!refresh_quote()) return false; + continue; + } + const uint32_t salary_at = list + 0x0c + uint32_t(selected) * 4; + const uint32_t salary_before = mem.u32(salary_at); + mem.set32(salary_at, (salary_before * 10u) >> 3); // temporary 125% for ProjectTransferOfferList + uint32_t fee_pct = 0, salary_pct = 0; + const bool rated = evaluate_bid(g, list, selected, fee_pct, salary_pct, rand, report); + mem.set32(salary_at, salary_before); // Source restores +0x0c before any outcome + if (!rated || report.unsupported) return false; + if ((seller_manager >= 0 && salary_pct != 0) || + (seller_manager < 0 && fee_pct != 0 && salary_pct != 0)) { + const bool moved = accept_transfer_bid_immediately(g, k, selected, rand, report, allocator); + if (!moved && !report.unsupported) + report.fail("transfer offer: selected bid could not be completed"); + if (report.unsupported) return false; + if (moved && seller_manager >= 0 && g.transfer_decision_observer) { + bool buyer_has_player = false; + const SquadRange buyer_range = squad_range(chosen.buyer); + for (size_t row = buyer_range.first; row < buyer_range.first + buyer_range.count; ++row) { + if ((g.squad_slots.at(row) & 0x0fff) == player) { + buyer_has_player = true; + break; + } + } + if (buyer_has_player) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = view; // owned snapshot before helper clears the offer rows + event.selected_bid_index = selected; + event.accepted = true; + event.viewer_manager = seller_manager; + event.result_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField2; // Void2 prefers the human seller + g.transfer_decision_observer(event); + } + } + accept = false; // immediate helper has already settled the list/player + break; + } + // IncomingTransferScreen clears just the rejected bidder slot and retries the + // same selector while other rows remain. + mem.set16(list + uint32_t(selected) * 2, 0xffff); + view.offers[size_t(selected)].present = false; + view.offers[size_t(selected)].eligible = false; + if (view.preferred_bid_index == selected) { + view.preferred_bid_index = -1; + view.preferred_bid_passed_random_check = false; + } + --view.offer_count; + view.rejected_bid_index = selected; + view.notice_text_address = ::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField3; + if (view.offer_count <= 0) { + // IncomingTransferScreen displays the final refusal, then returns when + // param_9 reaches zero. It does not redraw OpenTransferEditor. + view.preferred_bid_index = -1; + view.preferred_bid_passed_random_check = false; + (void)g.transfer_offer_selector(g, view); // terminal notice; response ignored + accept = false; + break; + } + if (!refresh_quote()) return false; + } + if (view.offer_count <= 0 || malformed_responses >= 8) accept = false; + // A successful selected-bid transfer was finalized above; prevent the + // legacy top-bid path from executing a second transfer. + if (accept) execute_transfer(g, k, list, bid, rand, report, allocator); + } else { + accept = g.transfer_decision && g.transfer_decision(g, seller_manager, player, bidder, + int32_t(mem.u32(list + 0x1c + uint32_t(bid) * 4)), + int32_t(mem.u32(list + 0x0c + uint32_t(bid) * 4))); + if (accept) execute_transfer(g, k, list, order[c], rand, report, allocator); + } + } else { + // Original IncomingTransferScreen enters the incoming-offer presentation when + // at least one raw bidder is human, even though the seller is AI. + // OpenTransferEditor computes its one-year reference quote before the + // accept/reject animation. Compute it on both observed and silent + // runs so installing a read-only observer does not alter RNG order. + TransferOfferListView decision_view; + int viewer_manager = -1; + bool human_bidder_present = false; + for (int raw = 0; raw < 4; ++raw) { + const int raw_buyer = int16_t(mem.u16(list + uint32_t(raw) * 2)); + if (raw_buyer == -1) break; + const int manager = g.manager_of(raw_buyer); + if (manager >= 0) { + human_bidder_present = true; + if (viewer_manager < 0) viewer_manager = manager; + } + } + if (human_bidder_present) { + decision_view = project_transfer_offer_list(g, k); + decision_view.preferred_bid_index = bid; + decision_view.preferred_bid_passed_random_check = accept; + decision_view.quoted_years = 1; // OpenTransferEditor uses one year for a computer seller + const int quote_percent = game.range(0x5c, 0x6c); // GameRandom in OpenTransferEditor + market_value(g, int(kPoolSlots + size_t(k)), 0, quote_percent, + decision_view.quoted_fee, decision_view.quoted_monthly_salary, 1, 0, rand); + offer_bases(mem, list, -1, decision_view.asking_fee, + decision_view.asking_monthly_salary); // RateTransferBidSource(..., -1) + if (mem.has(::bmh::layout::ActiveManager)) viewer_manager = int(mem.u8(::bmh::layout::ActiveManager)); // ActiveManager + if (g.transfer_decision_observer) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::evaluation; + event.offers = decision_view; + event.selected_bid_index = bid; + event.accepted = accept; + event.viewer_manager = viewer_manager; + event.result_text_address = accept ? ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer3 : ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer4; + g.transfer_decision_observer(event); + } + } + if (accept) { + execute_transfer(g, k, list, order[c], rand, report, allocator); + if (human_bidder_present && !report.unsupported && + g.manager_of(bidder) >= 0 && g.transfer_decision_observer) { + bool buyer_has_player = false; + const SquadRange buyer_range = squad_range(bidder); + for (size_t row = buyer_range.first; row < buyer_range.first + buyer_range.count; ++row) { + if ((g.squad_slots.at(row) & 0x0fff) == player) { + buyer_has_player = true; + break; + } + } + if (buyer_has_player) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::confirmation; + event.offers = decision_view; + event.selected_bid_index = bid; + event.accepted = true; + event.viewer_manager = g.manager_of(bidder); + event.result_text_address = ::bmh::layout::PendingOffer_FormatError_ExecutableField2; // Void2 + g.transfer_decision_observer(event); + } + } + } + } + if (report.unsupported) return false; + } + if (preserve_entry) return true; + for (int b = 0; b < 4; b++) mem.set16(list + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(kPoolSlots + size_t(k)) = 0x0FFF; + return true; +} + +} // namespace + +static TransferOfferListView project_transfer_offer_list_impl(const GameState& g, int entry, bool pending) { + TransferOfferListView view; + if (entry < 0 || entry >= (pending ? 44 : 40) || (pending && entry < 40)) return view; + const uint32_t list = kTransferList + uint32_t(entry) * kListEntry; + if (!g.memory.has(list + kListEntry - 1) || + kPoolSlots + size_t(entry) >= g.squad_slots.size()) return view; + const int player = g.squad_slots[kPoolSlots + size_t(entry)] & 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size()) return view; + + view.valid = true; + view.list_entry = entry; + view.player = player; + view.seller = g.memory.u16(list + 8) & 0x7fff; + view.seller_manager = g.manager_of(view.seller); + for (int bid = 0; bid < 4; ++bid) view.offers[size_t(bid)].bid_index = bid; + if (view.seller_manager >= 0 && g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(view.seller_manager))) + view.seller_loan_count = g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(view.seller_manager)); + for (int bid = 0; bid < 4; ++bid) { + const int buyer = int16_t(g.memory.u16(list + uint32_t(bid) * 2)); + // TransferListCountdown stops at the first empty slot; later bytes are not offers. + if (buyer == -1) break; + TransferOfferCandidateView& offer = view.offers[size_t(bid)]; + offer.present = true; + offer.buyer = buyer; + offer.buyer_manager = g.manager_of(buyer); + offer.fee = g.memory.u32(list + 0x1c + uint32_t(bid) * 4); + offer.monthly_salary = g.memory.u32(list + 0x0c + uint32_t(bid) * 4); + const uint8_t term = g.memory.u8(list + 0x34 + uint32_t(bid)); + offer.contract_months = term & 0x7f; + offer.loan = (term & 0x80) != 0; + offer_bases(g.memory, list, bid, offer.fee_reference, offer.salary_reference); + for (int bonus = 0; bonus < 7; ++bonus) + offer.bonuses[size_t(bonus)] = g.memory.u8(list + 0x38 + uint32_t(bid) * 7 + uint32_t(bonus)); + + // These are the non-random preselection guards in TransferListCountdown. The + // projection deliberately leaves ranking and the later ProjectTransferOfferList + // salary/fee recheck to the eventual synchronous selector. + offer.affordable = true; + if (offer.buyer_manager >= 0) { + const size_t rec = size_t(offer.buyer_manager) * kRecord; + if (rec + 0x31f >= g.manager_records.size()) { + offer.affordable = false; + } else { + const auto i32 = [&](size_t at) { + return int32_t(uint32_t(g.manager_records[at]) | + uint32_t(g.manager_records[at + 1]) << 8 | + uint32_t(g.manager_records[at + 2]) << 16 | + uint32_t(g.manager_records[at + 3]) << 24); + }; + offer.affordable = int64_t(i32(rec + 0x314)) + i32(rec + 0x31c) >= offer.fee; + } + } + // Only club IDs have a squad range in the source transfer path. Keep + // malformed IDs visible for diagnosis but never use them as indexes. + const SquadRange range = buyer >= 0 && buyer < kLeagueClubs ? squad_range(buyer) : SquadRange{}; + offer.has_squad_room = range.count != 0 && squad_count(g, buyer, 3) < int(range.count) - 1; + offer.passes_foreign_limit = range.count != 0; + if (view.seller_manager < 0 && range.count != 0) { + const int nation = team_region(buyer) & 0xff; + const int others = foreigners(g, buyer, range.first, range.count, nation); + if (others > 3 && (nationality(g, player) & 0xffff) != nation) + offer.passes_foreign_limit = false; + } + if (offer.loan) offer.loan_permitted = view.seller_loan_count >= 0 && view.seller_loan_count < 3; + // The human-owner -> AI-borrower route has its Source snapshot and return path; + // loans to a human borrower still require the separate Source consent flow. + // The generic weekly expiry/selector path has no owner for the explicit + // PendingOfferAnswer runtime allocator observation. The special DispatchClubPlayerPendingOffers pending + // caller opts in below, where its typed hooks own that observation. + offer.transaction_supported = !(offer.loan && offer.buyer_manager >= 0); + offer.eligible = offer.affordable && offer.has_squad_room && offer.passes_foreign_limit; + ++view.offer_count; + } + return view; +} + +TransferOfferListView project_transfer_offer_list(const GameState& g, int entry) { + return project_transfer_offer_list_impl(g, entry, false); +} + +namespace { + +void pending_notice(const GameState& g, const PendingOfferHooks& hooks, int manager, + int raw, uint32_t address, const std::string& composed = {}) { + if (hooks.notice) hooks.notice(g, {manager, raw, address, + composed.empty() ? message_text(g, address) : composed}); +} + +// Only the DispatchClubPlayerPendingOffers adapter admits entries40..43; legacy entry bounds stay40. +struct PendingOwnerContext { + int manager = -1; + int team = -1; // AdvanceTurn reads the raw record, including retained records1..3. + bool native_takeover = false; +}; + +TransferOfferListView pending_view(const GameState& g, int raw, int player, MinuteReport& report, + const PendingOwnerContext* owner) { + auto view = project_transfer_offer_list_impl(g, raw + 40, true); + if (owner && view.valid) { + // IncomingTransferScreen receives param8 directly from the offer owner. FindManagerForClub + // is only used for the buyer and later movement, not this seller context. + view.seller_manager = owner->manager; + if (g.memory.has(::bmh::layout::DeskActions_Unsupported_RuntimeField+uint32_t(owner->manager))) + view.seller_loan_count = g.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField+uint32_t(owner->manager)); + for (auto& offer : view.offers) if (offer.present) { + if (offer.loan) offer.loan_permitted = view.seller_loan_count >= 0 && view.seller_loan_count < 3; + if (pending_native_manager_of(g,offer.buyer,owner->native_takeover)==4) { + offer.buyer_manager=4; + const size_t rec=4*kRecord; + const auto i32=[&](size_t at) { + uint32_t n=0; + for(int i=0;i<4;++i)n|=uint32_t(g.manager_records.at(at+size_t(i)))<<(8*i); + return int32_t(n); + }; + offer.affordable=int64_t(i32(rec+0x314))+i32(rec+0x31c)>=offer.fee; + offer.eligible=offer.affordable && offer.has_squad_room && offer.passes_foreign_limit; + } + } + } + if (!view.valid || view.player != player || !view.offers[0].present || + view.seller_manager < 0 || view.offer_count != 1 || + g.memory.u16(kTransferList+uint32_t(raw+40)*kListEntry+4)!=0xffff || + g.memory.u16(kTransferList+uint32_t(raw+40)*kListEntry+6)!=0xffff) { + report.fail("DispatchClubPlayerPendingOffers: malformed special transfer entry (expected one actual bid)"); + return {}; + } + // DispatchClubPlayerPendingOffers is the only caller whose staged human-buyer settlement owns + // the observed allocator gate and payer notices for this loan route. + if (view.offers[0].loan && view.offers[0].buyer_manager >= 0) + view.offers[0].transaction_supported = true; + return view; +} + +void record_transfer_history_source(GameState& g, int manager, int other_team, int player, + uint32_t fee, bool loan, bool buyer_direction = false) { + // PoolString is explicitly inert for parked owner4, even when Fail + // recognizes that owner and calls it. Only ordinary owners0..3 have history. + if(manager<0 || manager>=4)return; + // The manager's two30-entry transfer-history blocks, newest first. + auto rec = record(g, manager); + for (int i = 29; i > 0; --i) { + rec.set32(0x760 + size_t(i)*4, uint32_t(rec.i32(0x760 + size_t(i-1)*4))); + rec.set32(0x7d8 + size_t(i)*4, uint32_t(rec.i32(0x7d8 + size_t(i-1)*4))); + } + rec.set32(0x760, uint32_t(loan)*2 + g.date*4 + uint32_t(buyer_direction) + (fee/10000)*0x80000); + const uint32_t other_club = other_team == 0x0fff ? 0xffffu + : uint32_t(g.club_ids.at(size_t(other_team))); + rec.set32(0x7d8, uint32_t(g.player_name_offsets.at(size_t(player))) + other_club*0x10000); + if (rec.b(0x21d) < 25) ++rec.b(0x21d); +} + +enum class PendingSettleOutcome { + not_moved, + buyer_funds_refused, + buyer_allocator_blocked, + buyer_no_room, + moved, + unsupported +}; + +PendingSettleOutcome pending_settle_human_buyer(GameState& g, int raw, int bid, + bool force, const PendingOfferHooks& hooks, WatcomRandom& rand, + MinuteReport& report, int seller, int buyer, uint32_t severance, + const PendingOwnerContext* owner) { + HumanBuyerSaleHooks shared; + switch (hooks.human_buyer_allocator_gate) { + case PendingOfferAllocatorGate::zero: shared.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break; + case PendingOfferAllocatorGate::blocked: shared.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break; + default: shared.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break; + } + if (hooks.notice) shared.notice = [&](const GameState& state, const HumanBuyerSaleNotice& notice) { + if (hooks.notice) hooks.notice(state, {notice.manager, notice.raw_offer_slot, + notice.source_text_address, notice.original_message}); + }; + shared.after_paid_accounts = [&](GameState& state, const HumanBuyerSalePaid& paid) { + auto& mem = state.memory; + // Void2 caller-only work remains between SettleHumanBuyerSale and Fail. + if (severance != 0) { + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + book_money(state, paid.seller_manager, int32_t(severance), true, true); + if (state.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + } + if (!force && hooks.notice) + hooks.notice(state, {paid.buyer_manager, paid.raw_offer_slot, ::bmh::layout::PendingOffer_FormatError_ExecutableField2, + message_text(state, ::bmh::layout::PendingOffer_FormatError_ExecutableField2)}); + state.transfer_notice_suppressed = false; + if (mem.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2)) mem.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2, 0); + uint32_t mask = 0x80000000u | (1u << paid.seller_manager); + if (!(mem.has(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) && mem.u8(::bmh::layout::Weekly_ExecuteTransfer_RuntimeField) != 0)) mask = 0xffffffffu; + else mask |= 1u << paid.buyer_manager; + const uint32_t interested = interested_managers(state, paid.seller, paid.buyer); + if ((mask | interested) != 0x80000000u) { + const std::string message = message_text(state, ::bmh::layout::Month_SearchProfileNews_TextPointer) + state.player_name(paid.player) + + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer) + state.club_name(paid.seller) + message_text(state, ::bmh::layout::Weekly_ExecuteTransfer_TextPointer2) + + format_amount(state, int32_t(paid.raw_fee)) + message_text(state, ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7) + + state.club_name(paid.buyer) + message_text(state, (paid.term & 0x80) ? ::bmh::layout::Weekly_ExecuteTransfer_TextPointer3 : ::bmh::layout::Weekly_ExecuteTransfer_TextPointer4); + post_composed(state, int64_t(mask | interested), message); + } + }; + + HumanBuyerSaleRequest request; + request.list_entry = raw + 40; + request.bid_slot = bid; + request.list_address = kTransferList + uint32_t(request.list_entry) * kListEntry; + request.source_pool_slot = kPoolSlots + size_t(request.list_entry); + request.expected_seller = seller; + request.expected_buyer = buyer; + request.expected_active_manager = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1; + request.raw_offer_slot = raw; + if(owner && owner->native_takeover) + request.source_pending_owner=SourcePendingOwner{owner->manager,owner->team}; + const auto settled = settle_human_buyer_sale(g, request, shared, rand, report); + switch (settled.status) { + case HumanBuyerSaleStatus::funds_refused: + return PendingSettleOutcome::buyer_funds_refused; + case HumanBuyerSaleStatus::allocator_blocked: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::buyer_allocator_blocked; + case HumanBuyerSaleStatus::no_room: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::buyer_no_room; + case HumanBuyerSaleStatus::moved: + if (g.memory.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField)) g.memory.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField, 1); + return PendingSettleOutcome::moved; + case HumanBuyerSaleStatus::unsupported: + default: + return PendingSettleOutcome::unsupported; + } +} + +PendingSettleOutcome pending_settle(GameState& g, int raw, int player, int bid, int clicked_player, + int clicked_slot, bool force, const PendingOfferHooks& hooks, + WatcomRandom& rand, MinuteReport& report, const PendingOwnerContext* owner) { + auto& mem = g.memory; + const uint32_t list = kTransferList + uint32_t(raw+40)*kListEntry; + const int seller = mem.u16(list+8)&0x7fff; + const int seller_manager = owner ? owner->manager : g.manager_of(seller); + const bool native_takeover = owner && owner->native_takeover; + const int movement_seller = pending_native_manager_of(g, seller, native_takeover); + const int buyer = int16_t(mem.u16(list+uint32_t(bid)*2)); + const int buyer_manager = pending_native_manager_of(g, buyer, native_takeover); + if (seller_manager < 0 || seller_manager >= 4 || buyer < 0 || buyer >= kLeagueClubs) { + report.fail("DispatchClubPlayerPendingOffers: invalid seller/buyer for Void2"); return PendingSettleOutcome::unsupported; + } + const uint8_t term = mem.u8(list+0x34+uint32_t(bid)); + const bool loan = term > 0x7f; + if (buyer_manager >= 0 && (buyer_manager >= (native_takeover?5:4) || buyer == seller || + (hooks.human_buyer_allocator_gate != PendingOfferAllocatorGate::zero && + hooks.human_buyer_allocator_gate != PendingOfferAllocatorGate::blocked))) { + report.fail("DispatchClubPlayerPendingOffers: human-buyer loan/same-club/unknown allocator route is unsupported"); + return PendingSettleOutcome::unsupported; + } + if (buyer_manager >= 0) { + const auto buyer_range = buyer >= 0 && buyer < kLeagueClubs ? squad_range(buyer) : SquadRange{}; + if (buyer_range.count != 24) { + report.fail("DispatchClubPlayerPendingOffers: human buyer uses unsupported non-24-slot squad layout"); + return PendingSettleOutcome::unsupported; + } + for (int k = 0; k < 200; ++k) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e != 0 && int(e & 0xfff) == player) { + report.fail("Fail: existing return-loan record (error30) is unsupported for human buyer"); + return PendingSettleOutcome::unsupported; + } + } + } + // Fail reports a full AI squad only after settlement accounting/news, + // including loans. Keep the legacy preflight's earlier room guard unchanged. + if (loan && !preflight_human_owner_loan(g,seller,kPoolSlots+size_t(raw+40),buyer,report,false,native_takeover)) + return PendingSettleOutcome::unsupported; + const auto range = squad_range(seller); + size_t owner_slot = range.first; + while (owner_slot < range.first+range.count && (g.squad_slots.at(owner_slot)&0xfff) != player) + ++owner_slot; + if (owner_slot == range.first+range.count) { + report.fail("DispatchClubPlayerPendingOffers: IncomingTransferScreen seller player missing (internal error0x1e)"); return PendingSettleOutcome::unsupported; + } + const size_t board = size_t(seller_manager)*kBoard+(owner_slot-range.first)*kBoardSlot; + if (board+kBoardSlot > g.tactics.size()) { + report.fail("DispatchClubPlayerPendingOffers: missing seller salary board"); return PendingSettleOutcome::unsupported; + } + uint32_t old_salary = 0; + for (int i=0;i<4;++i) old_salary |= uint32_t(g.tactics[board+0x50+size_t(i)])<<(8*i); + const uint32_t months = loan ? term&0x7f : g.tactics[board+0x0c]; + const uint32_t old_total = old_salary*months; + const uint32_t new_total = mem.u32(list+0x0c+uint32_t(bid)*4)*months; + // Void2 draws this W even if no salary decrease follows. + const uint32_t threshold = old_total*uint32_t(rand.range(90,100)); + uint32_t severance = 0; + if (new_total*100u < threshold) { + severance = std::max(((old_total-new_total)/1000)*1000,1000u); + PendingOfferQuestion question; + question.kind=PendingOfferQuestionKind::severance; + question.manager=seller_manager;question.raw_offer_slot=raw;question.offered_player=player; + question.clicked_player=clicked_player;question.clicked_source_slot=clicked_slot; + question.current_clicked_name=g.player_name(g.squad_slots.at(size_t(clicked_slot))&0xfff); + question.amount=severance;question.source_flags=0x305; + question.original_message=message_text(g,::bmh::layout::Weekly_PendingSettle_TextPointer)+format_amount(g,int32_t(severance))+"."; + if (!hooks.answer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual severance answer"); return PendingSettleOutcome::unsupported; + } + const auto answer=hooks.answer(g,question); + if(answer==PendingOfferAnswer::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual severance answer"); return PendingSettleOutcome::unsupported; + } + if(answer==PendingOfferAnswer::no) { + mem.set8(::bmh::layout::ActiveManager,uint8_t(seller_manager)); + pending_notice(g,hooks,seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField4); + return PendingSettleOutcome::not_moved; + } + } + const uint32_t fee=mem.u32(list+0x1c+uint32_t(bid)*4); + if (buyer_manager >= 0) + return pending_settle_human_buyer(g,raw,bid,force,hooks,rand,report,seller,buyer,severance,owner); + // SettleHumanBuyerSale: this scoped adapter has an AI buyer (no buyer debit/subsidy). + // BookMoney2(...,-fee,1), transfer ledger, then severance debit. + if(mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,1); + book_money(g,seller_manager,-int32_t(fee),true,true); + if(g.level!=0 && mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,0); + auto rec=record(g,seller_manager); + rec.set32(0x330,uint32_t(rec.i32(0x330))-fee); + if(severance) { + if(mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,1); + book_money(g,seller_manager,int32_t(severance),true,true); + if(g.level!=0 && mem.has(::bmh::layout::FinanceStatisticsEnabled))mem.set8(::bmh::layout::FinanceStatisticsEnabled,0); + } + if(!force)pending_notice(g,hooks,seller_manager,raw,::bmh::layout::PendingOffer_FormatError_ExecutableField2); // Source param10 suppresses forced-sale ACK + g.transfer_notice_suppressed=false; + if(mem.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2))mem.set8(::bmh::layout::DeskActions_EditorFail_RuntimeField2,0); + uint32_t mask=0x80000000u|(1u<=0) record_transfer_history_source(g,movement_seller,buyer,player,fee,loan); + move_player(g,seller,kPoolSlots+size_t(raw+40),buyer,list,bid,rand,report, + TransferAllocatorContext::unsupported,native_takeover); + if(mem.has(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField))mem.set8(::bmh::layout::Weekly_PendingSettleHumanBuyer_RuntimeField,1); + return report.unsupported ? PendingSettleOutcome::unsupported : PendingSettleOutcome::moved; +} + +PendingSettleOutcome pending_negotiate(GameState& g, int raw, int player, bool force, int clicked_player, + int clicked_slot, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report, const PendingOwnerContext* owner) { + auto view=pending_view(g,raw,player,report,owner); + if(report.unsupported)return PendingSettleOutcome::unsupported; + if(force) return pending_settle(g,raw,player,0,clicked_player,clicked_slot,true,hooks,rand,report,owner); + if(!hooks.select_transfer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual transfer-row chooser"); return PendingSettleOutcome::unsupported; + } + const uint32_t list=kTransferList+uint32_t(raw+40)*kListEntry; + const auto range=squad_range(view.seller); + size_t owner_slot=range.first; + while(owner_slot PlayerCardMarketValue -> 422f4, distinct from salary-JA's raw42307. + view.quoted_fee=((view.quoted_fee+(view.quoted_fee>>2))/10000)*10000; + view.quoted_monthly_salary=(view.quoted_monthly_salary/100)*100; + // OpenTransferEditor prepares its first empty offer row even in presentation mode. + g.memory.set32(list+0x0c+4,0);g.memory.set32(list+0x1c+4,0); + g.memory.set8(list+0x34+1,24); + offer_bases(g.memory,list,1,view.asking_fee,view.asking_monthly_salary); + const auto choice=hooks.select_transfer(g,view); + if(choice.kind==PendingOfferTransferChoiceKind::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual transfer choice");return PendingSettleOutcome::unsupported; + } + if(choice.kind==PendingOfferTransferChoiceKind::decline) { + if(!g.transfer_notice_suppressed && + !(g.memory.has(::bmh::layout::DeskActions_EditorFail_RuntimeField2) && g.memory.u8(::bmh::layout::DeskActions_EditorFail_RuntimeField2)!=0)) + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField); + return PendingSettleOutcome::not_moved; + } + if(choice.raw_bid_slot!=0) { + report.fail("DispatchClubPlayerPendingOffers: invalid special-entry raw bid slot");return PendingSettleOutcome::unsupported; + } + if(view.offers[0].loan && !view.offers[0].loan_permitted) { + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2); + view.rejected_bid_index=0;view.notice_text_address=::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField2; + continue; + } + const uint32_t before=g.memory.u32(list+0x0c); + g.memory.set32(list+0x0c,(before*10u)>>3); + uint32_t fee_pct=0,salary_pct=0; + const bool native_takeover=owner && owner->native_takeover; + const SourcePendingOwner native_owner{owner?owner->manager:-1,owner?owner->team:-1}; + const bool human_buyer = pending_native_manager_of(g,view.offers[0].buyer,native_takeover)>=0; + const bool rated = human_buyer + ? evaluate_pending_human_bid(g,list,0,fee_pct,salary_pct,rand,report,native_takeover?&native_owner:nullptr) + : evaluate_bid(g,list,0,fee_pct,salary_pct,rand,report); + g.memory.set32(list+0x0c,before); + if(!rated||report.unsupported)return PendingSettleOutcome::unsupported; + if(salary_pct!=0) + return pending_settle(g,raw,player,0,clicked_player,clicked_slot,false,hooks,rand,report,owner); + pending_notice(g,hooks,view.seller_manager,raw,::bmh::layout::PendingOffer_PendingOfferNoticeDialog_ExecutableField3); + g.memory.set16(list,0xffff); // param9==1: final rejection, no extra redraw. + return PendingSettleOutcome::not_moved; + } +} + +} // namespace + +HumanBuyerSaleResult settle_human_buyer_sale(GameState& g, const HumanBuyerSaleRequest& request, + const HumanBuyerSaleHooks& hooks, WatcomRandom& rand, MinuteReport& report) { + HumanBuyerSaleResult result; + if (report.unsupported) return result; + auto& mem = g.memory; + const auto fail = [&](const char* why) { + report.fail(why); + result.status = HumanBuyerSaleStatus::unsupported; + return result; + }; + + // Validate the exact caller-owned source coordinates. Ordinary and pending + // offers share the transaction but never share or synthesize their indices. + if (request.list_entry < 0 || request.list_entry >= 44 || request.bid_slot < 0 || request.bid_slot >= 4 || + request.list_address != kTransferList + uint32_t(request.list_entry) * kListEntry || + request.source_pool_slot != kPoolSlots + size_t(request.list_entry) || + !mem.has(request.list_address + kListEntry - 1) || + request.source_pool_slot >= g.squad_slots.size()) + return fail("SettleHumanBuyerSale/Fail: invalid explicit source list/pool/bid coordinates"); + if (request.raw_offer_slot == -1) { + const bool return_entry = request.loan_return_entry && !request.poach && + request.list_entry >= 40 && request.list_entry < 44 && + mem.has(::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4 + 3) && + mem.u32(::bmh::layout::OfferSlots + uint32_t(request.list_entry - 40) * 4) == + uint32_t(request.source_pool_slot < g.squad_slots.size() + ? (g.squad_slots[request.source_pool_slot] & 0x0fff) : 0x0fff) * 0x400u + + uint32_t(request.expected_active_manager); + if ((request.list_entry >= 40 && !request.poach && !return_entry) || + (request.loan_return_entry && !return_entry) || + (request.list_entry < 40 && (request.poach || request.loan_return_entry))) + return fail("SettleHumanBuyerSale/Fail: ordinary sale requires list entry 0..39"); + } else if (request.raw_offer_slot < 0 || request.raw_offer_slot >= 4 || + request.list_entry != 40 + request.raw_offer_slot || request.loan_return_entry) { + return fail("SettleHumanBuyerSale/Fail: pending raw slot does not identify its explicit list entry"); + } + const bool native_takeover=request.source_pending_owner.has_value(); + if(native_takeover && (request.raw_offer_slot<0 || request.bid_slot!=0 || request.day_step || request.poach || request.loan_return_entry || + !source_pending_owner_valid(g,*request.source_pending_owner,request.list_entry,request.source_pool_slot))) + return fail("SettleHumanBuyerSale/Fail: invalid DispatchClubPlayerPendingOffers native pending owner context"); + if (!request.day_step && (!mem.has(::bmh::layout::ActiveManager) || request.expected_active_manager < 0 || + (!native_takeover && size_t(request.expected_active_manager) >= g.manager_teams.size()) || + mem.u8(::bmh::layout::ActiveManager) != request.expected_active_manager)) + return fail("SettleHumanBuyerSale/Fail: active manager does not match caller context"); + if (hooks.allocator_gate != HumanBuyerSaleAllocatorGate::zero && + hooks.allocator_gate != HumanBuyerSaleAllocatorGate::blocked) + return fail("PendingOfferAnswer: human-buyer allocator gate was not observed by the runtime owner"); + if (!hooks.notice) + return fail("SettleHumanBuyerSale/Fail: Source notice presenter is unavailable"); + + const uint32_t list = request.list_address; + const int player = int(g.squad_slots.at(request.source_pool_slot) & 0x0fff); + const int seller = int(mem.u16(list + 8) & 0x7fff); + const int buyer = int16_t(mem.u16(list + uint32_t(request.bid_slot) * 2)); + const bool free_agent = seller == 0x0fff; + if (player == 0x0fff || size_t(player) >= g.players.size() || + seller != request.expected_seller || buyer != request.expected_buyer || + (!free_agent && (seller < 0 || seller >= kLeagueClubs)) || + buyer < 0 || buyer >= kLeagueClubs || seller == buyer) + return fail("SettleHumanBuyerSale/Fail: source player/seller/buyer identity mismatch"); + // SettleHumanBuyerSale uses param8 for the seller's accounts; Fail separately + // resolves actual movement ownership through FindManagerForClub. + const int seller_manager=pending_native_manager_of(g,seller,native_takeover); + const int account_seller=native_takeover?request.source_pending_owner->manager:seller_manager; + const int buyer_manager=pending_native_manager_of(g,buyer,native_takeover); + const bool parked_buyer=native_takeover && buyer_manager==4; + if (buyer_manager < 0 || buyer_manager >= (native_takeover?5:4) || + (!parked_buyer && (size_t(buyer_manager)>=g.manager_teams.size() || g.manager_teams[size_t(buyer_manager)]!=buyer)) || + (free_agent && seller_manager >= 0) || + (seller_manager >= 0 && (seller_manager >= (native_takeover?5:4) || seller_manager == buyer_manager))) + return fail("SettleHumanBuyerSale/Fail: unsupported buyer/seller manager identity"); + if(native_takeover) { + const int expected=request.source_pending_owner->team==kNoTeam + ? int(g.manager_records[4*kRecord+0x290]) | int(g.manager_records[4*kRecord+0x291])<<8 + : request.source_pending_owner->team; + if(seller!=expected)return fail("SettleHumanBuyerSale/Fail: invalid native pending seller provenance"); + } + if (!request.day_step && request.expected_active_manager != buyer_manager && request.expected_active_manager != account_seller) + return fail("SettleHumanBuyerSale/Fail: active manager is neither the direct buyer nor pending seller context"); + + const uint8_t term = mem.u8(list + 0x34 + uint32_t(request.bid_slot)); + const bool loan = term > 0x7f; + if (loan && free_agent) + return fail("Fail/DayStepRest2: free-agent loan return destination is not represented"); + const auto buyer_range = squad_range(buyer); + if (buyer_range.count != 24) + return fail("PendingOfferAnswer: human buyer uses unsupported non-24-slot squad layout"); + if (!mem.has(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + 199 * 4 + 3)) + return fail("Fail: missing return-loan storage (error30/31 boundary)"); + int loan_slot = -1; + for (int k = 0; k < 200; ++k) { + const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4); + if (e == 0 && loan_slot < 0) loan_slot = k; + else if (e != 0 && int(e & 0x0fff) == player) + return fail("Fail: existing return-loan record (error30) is unsupported for human buyer"); + } + if (loan && loan_slot < 0) + return fail("Fail: return-loan ledger full (error36)"); + + size_t seller_board = 0; + if (free_agent) { + // ReleasePlayer's canonical 0FFF seller scans the entire free-player pool, + // not a fictitious seller squad. FFFF is not an alias for this seller. + if (g.squad_slots.size() < 3072) + return fail("ReleasePlayer: free-agent pool is outside native squad storage"); + } else { + const auto seller_range = squad_range(seller); + if (seller_range.count == 0 || seller_range.first + seller_range.count > g.squad_slots.size()) + return fail("Fail: seller squad (error32) is outside native squad storage"); + size_t seller_slot = seller_range.first; + while (seller_slot < seller_range.first + seller_range.count && + (g.squad_slots.at(seller_slot) & 0x0fff) != player) ++seller_slot; + if (seller_slot == seller_range.first + seller_range.count || seller_slot >= g.squad_slots.size()) + return fail("Fail: seller does not own source player (error32)"); + if (seller_manager >= 0) + seller_board = size_t(seller_manager) * kBoard + (seller_slot - seller_range.first) * kBoardSlot; + } + if (seller_manager >= 0 && seller_board + kBoardSlot > g.tactics.size()) + return fail("Fail: seller board row (error32) is outside native tactics storage"); + if (buyer_range.first + buyer_range.count > g.squad_slots.size() || + size_t(buyer_manager) * kBoard + 24 * kBoardSlot > g.tactics.size()) + return fail("Fail: unsupported human buyer squad/board layout"); + + int owner_snapshot_slot = -1; + std::array owner_board_snapshot{}; + if (loan && seller_manager >= 0) { + if (seller_manager >= (native_takeover?5:4) || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) || + mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) >= 3 || + !mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b)) + return fail("Fail: human owner loan count/snapshot storage unavailable"); + for (int i = 0; i < 12; ++i) { + const uint16_t id = mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2); + if (id == uint16_t(player)) + return fail("Fail: duplicate human-owner loan snapshot"); + if (owner_snapshot_slot < 0 && id == 0x0fff) owner_snapshot_slot = i; + } + if (owner_snapshot_slot < 0) + return fail("Fail: human-owner loan snapshots full (error34)"); + std::copy_n(g.tactics.begin() + std::ptrdiff_t(seller_board), kBoardSlot, + owner_board_snapshot.begin()); + } + + const uint32_t fee = mem.u32(list + 0x1c + uint32_t(request.bid_slot) * 4); + const uint32_t salary = mem.u32(list + 0x0c + uint32_t(request.bid_slot) * 4); + if (hooks.before_accounts) hooks.before_accounts(g, request); + auto buyer_record = record(g, buyer_manager); + const uint8_t subsidy = buyer_record.b(0x170); + uint32_t adjusted_fee = fee; + const int position = int(g.players.at(size_t(player)).w364 & 3); + if (fee <= buyer_record.u32(0x314) && subsidy != 0 && (subsidy & 3) == position) { + int league = buyer_record.b(0x210); + if (league > 2) --league; + const uint32_t threshold = (((uint32_t(subsidy) >> 2) & 7u) * 50000u + 150000u) * + uint32_t(4 - league); + if (fee < threshold) { + const uint32_t discount = (((uint32_t(subsidy) >> 5) + 3u) * fee * 10u) / 100u; + const std::string message = message_text(g, ::bmh::layout::PendingOffer_ConstructionNoticeDialog_TextPointer) + + format_amount(g, int32_t(discount)) + message_text(g, ::bmh::layout::Weekly_Fail_TextPointer) + + format_amount(g, int32_t(fee)) + ")."; // EXE literal at a12ca, not a TEXTD pointer. + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_ConstructionNoticeDialog_TextPointer, message}); + adjusted_fee = fee - discount; + } else { + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_FormatError_ExecutableField3, message_text(g, ::bmh::layout::PendingOffer_FormatError_ExecutableField3)}); + } + // Both qualifying Source branches consume the subsidy even if payment fails. + record(g, buyer_manager).b(0x170) = 0; + } + + const uint8_t old_active = mem.u8(::bmh::layout::ActiveManager); + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + const bool buyer_paid = book_money(g, buyer_manager, int32_t(adjusted_fee), false, true); + if (!buyer_paid) { + mem.set8(::bmh::layout::ActiveManager, uint8_t(buyer_manager)); + hooks.notice(g, {buyer_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::Advertising_FormatError_TextPointer18, message_text(g, ::bmh::layout::Advertising_FormatError_TextPointer18)}); + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + mem.set8(::bmh::layout::ActiveManager, old_active); + result.status = HumanBuyerSaleStatus::funds_refused; + result.player = player; result.seller = seller; result.buyer = buyer; + result.seller_manager = account_seller; result.buyer_manager = buyer_manager; + result.raw_fee = fee; result.adjusted_fee = adjusted_fee; + return result; + } + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + record(g, buyer_manager).set32(0x330, uint32_t(record(g, buyer_manager).i32(0x330)) + adjusted_fee); + if (account_seller >= 0) { + if (mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 1); + book_money(g, account_seller, int32_t(0u - adjusted_fee), true, true); + if (g.level != 0 && mem.has(::bmh::layout::FinanceStatisticsEnabled)) mem.set8(::bmh::layout::FinanceStatisticsEnabled, 0); + auto seller_record = record(g, account_seller); + seller_record.set32(0x330, uint32_t(seller_record.i32(0x330)) - adjusted_fee); + } + + HumanBuyerSalePaid paid; + paid.list_entry = request.list_entry; paid.bid_slot = request.bid_slot; + paid.raw_offer_slot = request.raw_offer_slot; paid.player = player; + paid.seller = seller; paid.buyer = buyer; + paid.seller_manager = account_seller; paid.buyer_manager = buyer_manager; + paid.raw_fee = fee; paid.adjusted_fee = adjusted_fee; paid.salary = salary; paid.term = term; + if (hooks.after_paid_accounts) hooks.after_paid_accounts(g, paid); + + result.player = player; result.seller = seller; result.buyer = buyer; + result.seller_manager = account_seller; result.buyer_manager = buyer_manager; + result.raw_fee = fee; result.adjusted_fee = adjusted_fee; + if (hooks.allocator_gate == HumanBuyerSaleAllocatorGate::blocked) { + result.status = HumanBuyerSaleStatus::allocator_blocked; + return result; + } + + size_t buyer_slot = buyer_range.first; + while (buyer_slot < buyer_range.first + buyer_range.count && + g.squad_slots.at(buyer_slot) != 0x0fff) ++buyer_slot; + if (buyer_slot == buyer_range.first + buyer_range.count) { + const int current_manager = int(mem.u8(::bmh::layout::ActiveManager)); + hooks.notice(g, {current_manager, request.list_entry, request.raw_offer_slot, + ::bmh::layout::PendingOffer_FormatError_ExecutableField, message_text(g, ::bmh::layout::PendingOffer_FormatError_ExecutableField)}); + result.status = HumanBuyerSaleStatus::no_room; + return result; + } + + const uint16_t source_word = g.squad_slots.at(request.source_pool_slot); + g.squad_slots.at(buyer_slot) = source_word; + const size_t buyer_board = size_t(buyer_manager) * kBoard + + (buyer_slot - buyer_range.first) * kBoardSlot; + new_board_entry(g, buyer_manager, int(buyer_slot - buyer_range.first), int(buyer_slot), rand); + if (seller_manager >= 0) + std::copy_n(g.tactics.begin() + std::ptrdiff_t(seller_board), kBoardSlot, + g.tactics.begin() + std::ptrdiff_t(buyer_board)); + for (int b = 0; b < 4; ++b) + g.tactics.at(buyer_board + 0x50 + size_t(b)) = uint8_t(salary >> (b * 8)); + uint32_t reference_fee = 0, reference_salary = 0; + market_value(g, int(request.source_pool_slot), 0, 100, reference_fee, reference_salary, + int(term & 0x7f), 0, rand); + if (reference_salary == 0) + return fail("Fail: zero reference salary is an unsupported divide-by-zero boundary"); + for (int b = 0; b < 7; ++b) + g.tactics.at(buyer_board + 0x12 + size_t(b)) = + mem.u8(list + 0x38 + uint32_t(request.bid_slot) * 7 + uint32_t(b)); + const uint32_t bonus = parked_buyer + ? expected_bonus_parked_club_source(g,0xff,int(buyer_slot-buyer_range.first),player,true) + : expected_bonus(g,buyer_manager,0xff,int(buyer_slot-buyer_range.first),player,true); + const uint32_t bonus_product = bonus * 0x50u; + const int32_t signed_bonus_product = int32_t(bonus_product); + const int32_t expected_bonus_component = signed_bonus_product / 100; + const uint32_t source_total = salary + uint32_t(expected_bonus_component); + const uint32_t source_numerator = source_total * 100u; + const uint32_t unsigned_ratio = source_numerator / reference_salary; + const int32_t signed_ratio = int32_t(unsigned_ratio); + const uint32_t ratio = uint32_t(std::clamp(signed_ratio, 0, 0xff)); + g.tactics.at(buyer_board + 0x0d) = uint8_t(ratio); + if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1') + std::fprintf(stderr, "[purchase mood player %d: salary %u bonus %u (x0.8 = %d) reference %u (term %d) -> ratio %u]\n", player, + salary, bonus, expected_bonus_component, reference_salary, int(term & 0x7f), ratio); + for (int b = 0; b < 4; ++b) + g.tactics.at(buyer_board + 0x54 + size_t(b)) = uint8_t(fee >> (b * 8)); + g.tactics.at(buyer_board + 0x0c) = loan ? uint8_t(0xff) : term; + + if (loan) { + if (seller_manager >= 0) { + const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(owner_snapshot_slot) * uint32_t(kBoardSlot); + for (size_t b = 0; b < kBoardSlot; ++b) + mem.set8(snapshot + uint32_t(b), owner_board_snapshot[b]); + mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(owner_snapshot_slot) * 2, uint16_t(player)); + mem.set8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(owner_snapshot_slot), uint8_t(seller_manager)); + mem.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager), uint8_t(mem.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(seller_manager)) + 1)); + } + mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan_slot), uint8_t(term & 0x7f)); + mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan_slot) * 4, + uint32_t(player + seller * 0x1000 + buyer * 0x400000)); + } + + if (seller_manager >= 0) + record_transfer_history_source(g, seller_manager, buyer, player, fee, loan, false); + record_transfer_history_source(g, buyer_manager, seller, player, fee, loan, true); + if (!remove_from_seller_impl(g,seller,player,report,native_takeover)) { + result.status = HumanBuyerSaleStatus::unsupported; + return result; + } + lineup_after_transfer_impl(g,seller,native_takeover); + lineup_after_transfer_impl(g,buyer,native_takeover); + result.status = HumanBuyerSaleStatus::moved; + return result; +} + +namespace { +PendingOfferResult process_pending_batch(GameState& g, int clicked_player, int clicked_slot, + int clicked_manager, int physical_row, bool human_loan, int human_loan_index, + GameRandom& game, WatcomRandom& rand, const PendingOfferHooks& hooks, MinuteReport& report, + const PendingOwnerContext* owner = nullptr) { + PendingOfferResult result; + if(report.unsupported)return result; + if(!g.texts || !g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::OfferSlots+15) || + !g.memory.has(::bmh::layout::CareerSession_Invalid_RuntimeField2+3) || kPoolSlots+44>g.squad_slots.size()) { + report.fail("DispatchClubPlayerPendingOffers: missing native offer state or Original TEXTD");return result; + } + // Owned board storage, not a copied board or a remapped offered-player row. + const size_t board=human_loan ? 0 : size_t(clicked_manager)*kBoard+ + size_t(physical_row)*kBoardSlot; + const uint32_t loan_board=::bmh::layout::ClubInfo_FormatError_RuntimeField+uint32_t(std::max(human_loan_index,0))*kBoardSlot; + const auto board_byte=[&](size_t offset) { + return human_loan ? g.memory.u8(loan_board+uint32_t(offset)) : g.tactics.at(board+offset); + }; + const auto write_board=[&](size_t offset,uint8_t value) { + if(human_loan)g.memory.set8(loan_board+uint32_t(offset),value); + else g.tactics.at(board+offset)=value; + }; + bool sticky=false; + for(int raw=0;raw<4;++raw) { + const uint32_t at=::bmh::layout::OfferSlots+uint32_t(raw)*4; + const uint32_t offer=g.memory.u32(at); + const int active=g.memory.u8(::bmh::layout::ActiveManager); + if(offer==0xffffffffu || int(offer&31)!=active)continue; + if(active<0 || (owner ? active!=owner->manager : size_t(active)>=g.manager_teams.size())) { + report.fail("DispatchClubPlayerPendingOffers: invalid active owner");return result; + } + const int player=int((offer>>10)&0xfff); + const auto range=squad_range(owner ? owner->team : g.manager_teams[size_t(active)]); + size_t offered_slot=range.first; + while(offered_slotteam==kNoTeam + ? int(g.manager_records.at(4*kRecord+0x290)) | + (int(g.manager_records.at(4*kRecord+0x291))<<8) : owner->team; + if(seller<0 || seller>=kLeagueClubs || seller!=expected_seller || + (g.squad_slots.at(kPoolSlots+size_t(raw+40))&0x0fff)!=player) { + report.fail("DispatchClubPlayerPendingOffers: invalid special offer seller/pool provenance (PreMatchOffer requires a club seller)"); + return result; + } + } + if(offer&0x80000000u) { + PendingOfferQuestion question; + question.manager=active;question.raw_offer_slot=raw;question.offered_player=player; + question.clicked_player=clicked_player;question.clicked_source_slot=clicked_slot; + question.current_clicked_name=g.player_name(g.squad_slots.at(size_t(clicked_slot))&0xfff); + question.amount=g.memory.u32(list+0x0c); + question.original_message=question.current_clicked_name+message_text(g,::bmh::layout::Weekly_ProcessPendingBatch_TextPointer)+ + format_amount(g,int32_t(question.amount))+message_text(g,::bmh::layout::Weekly_ProcessPendingBatch_TextPointer2); + if(!hooks.answer) { + report.fail("DispatchClubPlayerPendingOffers: missing manual salary answer");return result; + } + const auto answer=hooks.answer(g,question); + if(answer==PendingOfferAnswer::unsupported) { + report.fail("DispatchClubPlayerPendingOffers: unsupported manual salary answer");return result; + } + if(answer==PendingOfferAnswer::yes) { + if(!(offer&0x20)) { + uint32_t fee=0,salary=0; + market_value(g,clicked_slot,0,98,fee,salary,(board_byte(0x0c)+6)/12,0,rand); + if(salary==0) { + report.fail("DispatchClubPlayerPendingOffers: salary reference zero (Source division by zero)");return result; + } + for(int byte=0;byte<4;++byte)write_board(0x50+size_t(byte),uint8_t(question.amount>>(8*byte))); + write_board(0x0d,uint8_t(question.amount*100u/salary)); + } + ++result.salary_accepted;negotiate=false; + } else sticky=true; + } + if(negotiate) { + const auto outcome=pending_negotiate(g,raw,player,sticky,clicked_player,clicked_slot, + game,rand,hooks,report,owner); + switch(outcome) { + case PendingSettleOutcome::moved: ++result.transferred; break; + case PendingSettleOutcome::buyer_funds_refused: ++result.buyer_funds_refused; break; + case PendingSettleOutcome::buyer_allocator_blocked: ++result.buyer_allocator_blocked; break; + case PendingSettleOutcome::buyer_no_room: ++result.buyer_no_room; break; + case PendingSettleOutcome::unsupported: + return result; + case PendingSettleOutcome::not_moved: + break; + } + } + if(report.unsupported)return result; + } + // Cleanup applies to owned offers even when the offered player disappeared. + g.squad_slots.at(kPoolSlots+size_t(raw+40))=0x0fff; + g.memory.set32(at,0xffffffffu); + ++result.processed;result.forced_acceptance=sticky; + } + result.completed=true; + return result; +} +} // namespace + +PendingOfferResult process_player_card_pending_offers(GameState& g, + const ClubPlayerDetailSelection& selection, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if(report.unsupported)return result; + const auto clicked=club_player_detail_context(g,selection); + if(clicked.national_mode!=0 || !clicked.board || clicked.active_offer<0) { + report.fail("DispatchClubPlayerPendingOffers: clicked card has no ordinary pending action/board");return result; + } + return process_pending_batch(g,selection.player_id,clicked.source_slot,clicked.source_manager, + selection.physical_row,clicked.human_loan,selection.human_loan_index,game,rand,hooks,report); +} + +PendingOfferResult process_natural_pending_offers_after_desk(GameState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if (report.unsupported) return result; + const auto fail = [&](const char* why) -> PendingOfferResult { + report.fail(why); return result; + }; + if (request.runtime_mode != PendingOfferDeskRuntimeMode::normal_interactive) + return fail("AdvanceTurn: unsupported or unspecified transient desk runtime mode"); + constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount, kOrder = ::bmh::layout::NextDeskManager, kDeskPosition = ::bmh::layout::DeskPosition; + constexpr uint32_t kActiveManager = ::bmh::layout::ActiveManager, kOffers = ::bmh::layout::OfferSlots; + if (!g.memory.has(kManagerCount) || !g.memory.has(kOrder + 7) || + !g.memory.has(kDeskPosition) || !g.memory.has(kActiveManager) || + !g.memory.has(kOffers + 15) || kPoolSlots + 44 > g.squad_slots.size()) + return fail("AdvanceTurn: missing native manager/order/offer state"); + const int count = g.memory.u8(kManagerCount); + if (count < 1 || count > 4 || request.manager_count != count || + size_t(count) != g.manager_teams.size()) + return fail("AdvanceTurn: manager count does not match native manager loop"); + if (request.manager_position < 0 || request.manager_position >= count || + int(g.memory.u8(kDeskPosition)) != request.manager_position) + return fail("AdvanceTurn: desk position does not match native bdb77"); + // While a Bundestrainer has taken the national team over (CoachActive), SwapManagerSlots2 has + // cut ManagerCount to one but left the order NextDeskManager of the full game (OriginalManagerCount + // managers): PrepareEvent shuffles only a one-entry prefix, the desk is slot 0 + // (ActiveManager = DeskPosition while the count is one) and the offer owner afterwards is NextDeskManager[0], + // which may be a manager who sits this day out. + const bool takeover = g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0 && g.memory.has(::bmh::layout::OriginalManagerCount); + if (takeover && (count!=1 || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + g.manager_teams[0]!=kNoTeam || 5*kRecord>g.manager_records.size() || 5*kBoard>g.tactics.size())) + return fail("AdvanceTurn: invalid reduced-count national takeover record context"); + const int limit = takeover ? int(g.memory.u8(::bmh::layout::OriginalManagerCount)) : count; + std::array seen{}; + for (int i=0;i=limit || seen[size_t(manager)]) + return fail("AdvanceTurn: invalid native manager order permutation"); + seen[size_t(manager)]=true; + } + const int manager=g.memory.u16(kOrder+uint32_t(request.manager_position)*2); + if (manager<0 || manager>=limit || (manager=g.manager_teams.size())) + return fail("AdvanceTurn: invalid current ordered manager"); + if (takeover && size_t(manager)*kRecord+0x292>g.manager_records.size()) + return fail("AdvanceTurn: missing current ordered manager record"); + const size_t owner_record=size_t(manager)*kRecord+0x290; + const int native_team=takeover ? int(g.manager_records[owner_record]) | + (int(g.manager_records[owner_record+1])<<8) : g.manager_teams[size_t(manager)]; + const PendingOwnerContext owner{manager,native_team,takeover}; + // Records1..3 survive the count-one national takeover. AdvanceTurn reads + // these records directly even while their clubs have no current desk. + if ((takeover && manager=kLeagueClubs)) || + (native_team==kNoTeam && (!takeover || manager!=0))) + return fail("AdvanceTurn: invalid native ordered owner team"); + const auto inactive_club_offer = [&](int raw, int player) { + // Deliberate OpenBMH improvement: AdvanceTurn reports error58 when a + // retained club offer is looked up in the temporary national squad. + // Qualify the old club in spare record4 and the offer's pool identity; + // preserve Source's cleanup, without presenting this context mismatch. + if (!takeover || count!=1 || manager!=0 || + g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 || + 4*kRecord+0x292>g.manager_records.size() || + player<0 || size_t(player)>=g.players.size() || + (g.squad_slots.at(kPoolSlots+size_t(raw+40))&0x0fff)!=player) + return false; + const auto record_team = [&](size_t base) { + return int(g.manager_records[base+0x290]) | + (int(g.manager_records[base+0x291])<<8); + }; + if (record_team(0)!=kNoTeam) return false; + const int club=record_team(4*kRecord); + if (club<0 || club>=138) return false; + const auto squad=squad_range(club); + if (squad.first+squad.count>g.squad_slots.size()) return false; + for (size_t i=squad.first;i=138 && !national_owner)) + return fail("AdvanceTurn: national or unknown owner is unsupported for normal-club offers"); + // AdvanceTurn scans raw offer words until the first owned player resolves in + // an ordinary squad. A missing earlier player requires PresentLoanReturn's error + // presentation; later words belong to DispatchClubPlayerPendingOffers's own batch scan. + const auto range=squad_range(team); + if (range.first+range.count>g.squad_slots.size()) + return fail("AdvanceTurn: truncated ordinary owner squad"); + const int player=int((offer>>10)&0xfff); + size_t slot=range.first; + while(slot=0) { + const auto range=squad_range(native_team); + const int physical_row=anchor_slot-int(range.first); + result=process_pending_batch(g,anchor_player,anchor_slot,manager,physical_row,false,-1, + game,rand,hooks,report,takeover?&owner:nullptr); + if(report.unsupported || !result.completed)return result; + } else { + result.completed=true; // Source still reaches the end-of-loop cleanup. + } + if(request.manager_position==count-1) { + for(int raw=0;raw<4;++raw) { + g.squad_slots.at(kPoolSlots+size_t(raw+40))=0x0fff; + g.memory.set32(kOffers+uint32_t(raw)*4,0xffffffffu); + } + g.memory.set8(kDeskPosition,uint8_t(count)); + } + return result; +} + +PendingOfferResult process_national_nomination_pending_after_desk(GameState& g, + const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand, + const PendingOfferHooks& hooks, MinuteReport& report) { + PendingOfferResult result; + if (report.unsupported) return result; + const auto fail = [&](const char* why) -> PendingOfferResult { + report.fail(why); + return result; + }; + if (request.runtime_mode != PendingOfferDeskRuntimeMode::normal_interactive) + return fail("AdvanceTurn: unsupported or unspecified national desk runtime mode"); + + constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar, kCompetition = ::bmh::layout::SavedCompetition; + constexpr uint32_t kCoachActive = ::bmh::layout::CoachActive, kOriginalCount = ::bmh::layout::OriginalManagerCount; + constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount, kOrder = ::bmh::layout::NextDeskManager; + constexpr uint32_t kPosition = ::bmh::layout::DeskPosition, kActive = ::bmh::layout::ActiveManager, kOffers = ::bmh::layout::OfferSlots; + if (!g.memory.has(kCalendar + uint32_t(g.season_day()) * 2 + 1) || + !g.memory.has(kCompetition + 3) || !g.memory.has(kCoachActive) || + !g.memory.has(kOriginalCount) || !g.memory.has(kManagerCount) || + !g.memory.has(kOrder + 1) || !g.memory.has(kPosition) || !g.memory.has(kActive) || + !g.memory.has(kOffers + 15) || kPoolSlots + 44 > g.squad_slots.size()) + return fail("AdvanceTurn: missing native national desk state"); + + const uint16_t calendar_entry = g.memory.u16(kCalendar + uint32_t(g.season_day()) * 2); + const int original_count = g.memory.u8(kOriginalCount); + const int restored_owner = g.memory.u16(kOrder); + if (request.manager_count != 1 || request.manager_position != 0 || + g.memory.u8(kManagerCount) != 1 || g.manager_teams.size() != 1 || + g.manager_teams[0] != kNoTeam || g.memory.u8(kCoachActive) == 0 || + g.memory.u32(kCompetition) != 0 || calendar_entry != 0x4006 || + day_competitions(g, calendar_entry) != 0x800000 || + original_count < 1 || original_count > 4 || restored_owner >= original_count || + g.memory.u8(kPosition) != 0 || g.memory.u8(kActive) != 0) + return fail("AdvanceTurn: national nomination desk does not match the saved Source context"); + + // Nomination uses the same post-return AdvanceTurn/DispatchClubPlayerPendingOffers sequence. Its + // calendar/competition identity is checked above before the shared scan can + // claim ActiveManager, invoke a presenter or consume either generator. + return process_natural_pending_offers_after_desk(g,request,game,rand,hooks,report); +} + +bool accept_transfer_bid_immediately(GameState& g, int entry, int bid, WatcomRandom& rand, + MinuteReport& report, TransferAllocatorContext allocator) { + if (entry < 0 || entry >= 40 || bid < 0 || bid >= 4) return false; + const uint32_t list = kTransferList + uint32_t(entry) * kListEntry; + if ((g.squad_slots.at(kPoolSlots + size_t(entry)) & 0xfff) == 0xfff || + g.memory.u16(list + uint32_t(bid) * 2) == 0xffff) return false; + execute_transfer(g, entry, list, bid, rand, report, allocator); + if (report.unsupported) return false; + for (int b = 0; b < 4; ++b) g.memory.set16(list + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(kPoolSlots + size_t(entry)) = 0x0fff; + return true; +} + +void transfer_list_countdown(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, bool all, + TransferAllocatorContext allocator) { + StaticMemory& mem = g.memory; + for (int k = 0; k < 40; k++) { + const int player = g.squad_slots.at(kPoolSlots + size_t(k)) & 0xFFF; + if (player == 0xFFF) continue; + const uint32_t e = kTransferList + uint32_t(k) * kListEntry; + const uint8_t left = mem.u8(e + 0x56); + if (left == 0 || left > 9) { + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(kPoolSlots + size_t(k)) = 0x0FFF; + continue; + } + mem.set8(e + 0x56, uint8_t(left - 1)); + const int seller = mem.u16(e + 8) & 0x7FFF; // club of the player (0xFFF: none) + if (all) { + mem.set8(e + 0x56, 0); // TransferListCountdown(1) at the season end: every list is settled now + } else { + if (left - 1 == 1) { + // TransferListCountdown's one-week notice is a system modal (SystemIdentity(4)) + // only when a human seller or any human bidder participates. + // It observes the countdown and raw offer rows; it consumes no RNG + // and cannot change the later expiry decision. + const auto human_participant = [&](int club) { + // FindManagerForClub also recognizes the coach's temporarily saved + // club as owner 4 while manager 0 runs the national team. + return g.manager_of(club) >= 0 || (!g.manager_teams.empty() && + g.manager_teams[0] == 0x165 && mem.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField) && + int(mem.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)) == club); + }; + bool human_involved = human_participant(seller); + for (int bid = 0; bid < 4 && !human_involved; ++bid) { + const int buyer = int16_t(mem.u16(e + uint32_t(bid) * 2)); + if (buyer != -1) human_involved = human_participant(buyer); + } + if (human_involved && g.transfer_decision_observer) { + TransferDecisionEvent event; + event.kind = TransferDecisionEventKind::last_week; + event.offers = project_transfer_offer_list(g, k); + event.viewer_manager = -1; // Source SystemIdentity(4), system identity + event.result_text_address = ::bmh::layout::PendingOffer_TransferLastWeekDialog_ExecutableField; + g.transfer_decision_observer(event); + } + continue; + } + if (left - 1 != 0) continue; + } + if (int16_t(mem.u16(e)) == -1) { + // no bid at all: the player leaves the list, a human seller is told + if (const int m = g.manager_of(seller); m >= 0) + post_composed(g, m, message_text(g, ::bmh::layout::Weekly_TransferListCountdown_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_TransferListCountdown_TextPointer2)); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xffff); + g.squad_slots.at(kPoolSlots + size_t(k)) = 0x0FFF; + continue; + } + if (!decide_bids(g, k, game, rand, report, allocator)) return; + } +} + +void weekly_statistics(GameState& g, int manager) { + Record rec = record(g, manager); + uint8_t week = rec.b(0x285); + auto shift = [&](size_t to, size_t from, size_t n) { + // Int16T: memmove from -> to + std::vector tmp(g.manager_records.begin() + rec.base + from, g.manager_records.begin() + rec.base + from + n); + std::copy(tmp.begin(), tmp.end(), g.manager_records.begin() + rec.base + to); + }; + if (week < 0x34) { + rec.b(0x285) = uint8_t(week + 1); + } else { + shift(0x3d8, 0x3dc, 0xcc); + shift(0x17a, 0x17b, 0x33); + shift(0x648, 0x64c, 0xcc); + shift(0x4a8, 0x4ac, 0xcc); + shift(0x578, 0x57c, 0xcc); + week = 0x33; + } + // HighscoreScore(0x1e, 0, 0xff): account, deposits, shares and bonds + int32_t assets = rec.i32(0x318); + for (int k = 0; k < 6; k++) + assets += int32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(k) * 0x1c) * + g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c)); + for (int k = 0; k < 12; k++) + assets += int32_t(uint32_t(g.stocks.at(size_t(k) * 0x5c + 0x50 + size_t(manager) * 2) | g.stocks.at(size_t(k) * 0x5c + 0x51 + size_t(manager) * 2) << 8) * + uint32_t(g.stocks.at(size_t(k) * 0x5c + 0x4e) | g.stocks.at(size_t(k) * 0x5c + 0x4f) << 8)); // shares (block StockExchange) + for (int b = 0; b < 5; b++) assets -= int32_t(g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(manager) * 0x78 + uint32_t(b) * 0x18)); // credits + rec.set32(0x3d8 + size_t(week) * 4, uint32_t(assets)); + int second = 0; + rec.b(0x17a + week) = uint8_t(facility_rating(g, manager, &second) * 2); + int value = 0; // BMHExeXa + for (int i = 0; i < 0xe; i++) value += kFacilityValue[i]; + for (int i = 0xe; i < 0x16; i++) value += (rec.b(0x2e + size_t(i)) & 7) * kFacilityValue[i]; + rec.set32(0x648 + size_t(week) * 4, uint32_t(value)); + int32_t sum = 0; + for (int i = 0; i < 0x11; i++) sum += rec.i32(0xa34 + size_t(i) * 0xc); + rec.set32(0x4a8 + size_t(week) * 4, uint32_t(sum)); + rec.set32(0x578 + size_t(week) * 4, uint32_t(rec.i32(0x314))); +} + +void weekly_processing(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator) { + const int managers = int(g.manager_teams.size()); + // (BMH_WEEKLY: the draw counts after each step, for comparing with a recording) + auto tr = [&](const char* what) { + if (std::getenv("BMH_WEEKLY")) std::printf(" [weekly %s: game %llu, Watcom %llu]\n", what, (unsigned long long)game.calls(), (unsigned long long)rand.calls()); + }; + tr("start"); + for (int m = 0; m < managers && !report.unsupported; m++) { + manager_offers(g, m, rand, report); + tr("offers"); + if (report.unsupported) return; + facility_ageing(g, m, game, rand, report); + tr("ageing"); + facility_damage(g, m, game, rand); + tr("damage"); + if (g.memory.u8(::bmh::layout::Savestate_Layout_ExecutableField) % 3 == 0) advertising_offers(g, m, rand, report); + tr("advertising"); + } + transfer_list_countdown(g, game, rand, report, false, allocator); + tr("list countdown"); + if (report.unsupported) return; + // new bids for listed players + for (int k = 0; k < 40; k++) { + if (rand.range(0, 1) != 0) continue; + const uint32_t e = kTransferList + uint32_t(k) * kListEntry; + const size_t slot = kPoolSlots + size_t(k); + if (g.squad_slots.at(slot) == 0x0FFF || int16_t(g.memory.u16(e + 6)) != -1) continue; + if (rand.range(0, 1) == 0) continue; + do { + transfer_bid(g, int(slot), e, false, -1, game, rand, report); + if (report.unsupported) return; + } while (rand.range(0, 2) == 0); + } + tr("bids"); + // every player: injuries in training, players out coming back + const bool quiet = g.memory.u8(::bmh::layout::GameMode) == 1; + for (size_t slot = 0; slot < kPoolSlots; slot++) { + const int player = g.squad_slots.at(slot) & 0x0FFF; + if (player == 0x0FFF) continue; + Player& p = g.players.at(size_t(player)); + const uint32_t out = p.w35c >> 27; + const uint32_t w364 = p.w364; + int injury = int((w364 >> 16) & 0x1F); + if (!quiet && game.range(0, 0xb4 - g.level * 2) == 0 && injury == 0 && out == 0) { + if (slot >= 0x870 && rand.range(0, 1) == 0) continue; + int type = rand.range(0, 0x1e); + const int team = slot_team(int(slot)); + const int manager = g.manager_of(team); + type = injure_player(g, int(slot), type, false, manager, rand); // (unless MatchEventsDisabled, off) + if (manager >= 0) { + // "Ihr Spieler X faellt ... aus. Der Grund: ." + post_composed(g, manager, message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer2) + g.player_name(player) + + message_text(g, type < 6 ? ::bmh::layout::Weekly_WeeklyProcessing_TextPointer3 : ::bmh::layout::Weekly_WeeklyProcessing_TextPointer4) + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer5) + + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer + uint32_t(type) * 4) + "."); + } + continue; + } + if (out == 0 || out == 0x1F) continue; + if (injury > 0x18 && rand.range(0, 0x25) == 0) { + // the career is over + p.w35c = (p.w35c & 0x07FFFFFFu) | 0xF8000000u; + p.w364 |= 0x1Fu << 16; + if (const int m = g.manager_of(slot_team(int(slot))); m >= 0) + post_composed(g, m, message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer2) + g.player_name(player) + message_text(g, ::bmh::layout::Weekly_WeeklyProcessing_TextPointer6) + "."); + continue; + } + const bool last = injury == 1; + const int team = slot_team(int(slot)); + const int manager = g.manager_of(team); + int odds = 4; + if (manager >= 0) odds = 6 - record(g, manager).i16(0x8ae) / 0x113; + if (injury != 0 && injury != 0x1F) { + if (injury < 4 && rand.range(0, int16_t(odds)) == 0) injury = 1; + p.w364 = (w364 & 0xFFE0FFFFu) | uint32_t(injury - 1) << 16; + } + if (last || (rand.range(0, int16_t(odds)) == 0 && injury == 0)) { + p.w35c &= 0x07FFFFFFu; + // Int2(team, 100); human teams: the assistant's line-up (option byte 0) + try { + auto_lineup(g, team, 100); + } catch (const std::exception& ex) { + report.fail(std::string("line-up after an injury: ") + ex.what()); + return; + } + } + } + tr("injuries and line-ups"); + // per human manager + for (int m = 0; m < managers; m++) { + Record rec = record(g, m); + const int debt = rec.b(0x174); + if (debt != 0) book_money(g, m, -debt * 1000, true); + const SquadRange range = squad_range(int16_t(rec.u16(0x290))); + if (rec.b(0x287) != 0 && --rec.b(0x287) == 0) { + // the bill of the training camp + int16_t mood = 0; + for (int i = 0; i < 10; i++) mood = int16_t(mood + (g.manager_ratings.at(size_t(m) * 0x3c + size_t(i)) - 100)); + mood = int16_t(mood / 10 + 0x46); + const int a = rand.range(0, 8); + const int b = rand.range(0, 8); + mood = int16_t(std::clamp(int(int16_t(mood + a - b)), 0x14, 0xb4)); + int32_t tmp = mood; + for (int i = 10; i < 0xe; i++) + if (rec.b(size_t(i)) != 0) tmp += rand.range(5, 0xc); + const uint32_t bill = uint32_t(int16_t(tmp) * rec.i32(0x850)) / 100; + book_money(g, m, -int32_t(bill), true); + rec.set32(0x850, 0); + } + for (int s = 0; s < 24; s++) { + const size_t at = size_t(m) * kBoard + size_t(s) * kBoardSlot; + if (g.squad_slots.at(range.first + size_t(s)) == 0x0FFF) continue; + if ((g.tactics.at(at + 0x4f) & 0x80) && rand.range(0, 6) == 0) g.tactics.at(at + 0x4f) &= 0x7F; + if (g.tactics.at(at + 0xc) == 2) g.tactics.at(at + 0xb) &= 0x3F; + // SalaryInjuredPlayerOnBoardPaidOn: the salary of an injured player on the board is paid on + const int player = g.squad_slots.at(range.first + size_t(s)) & 0x0FFF; + if ((g.players.at(size_t(player)).w35c >> 27) != 0 && g.tactics.at(at + 0x43) != 0) { + const int32_t base = int32_t(g.tactics.at(at + 0x50) | g.tactics.at(at + 0x51) << 8 | + g.tactics.at(at + 0x52) << 16 | uint32_t(g.tactics.at(at + 0x53)) << 24); + const uint32_t pay = uint32_t(base * int32_t(((int8_t(g.tactics.at(at + 0x43)) >> 6) & 3) * 0x32 + 0x32)) / 100; + book_money(g, m, -int32_t(pay), true); + } + const uint8_t mood = g.tactics.at(at + 0xc); + if (mood % 0xc <= 7 && !(g.tactics.at(at + 0xb) & 0x20) && mood % 0xc != 0 && mood <= 0xf && + !(g.tactics.at(at + 0x4f) & 0x80) && !quiet) { + const int16_t rating = int16_t(rec.i16(0x8aa) + (rec.i16(0x8ac) >> 2)); + if (rand.range(0, 500 - (rating - 0x2a8) / 2) == 0) { + // InstallDefaultHooks(slot | 0x40): the player asks to talk about his contract. + // Before the contracts screen opens he names the term he wants, + // WatcomRandom(years left, 4), one more if that is no change (below 4), + // and the request is shown (SystemIdentity). The negotiation itself is UI: + // ported is a manager who leaves the screen without an offer, which + // changes nothing else. + const int years = mood / 0xc; + int wanted = rand.range(years, 4); + if (wanted == years && wanted < 4) wanted++; + (void)wanted; + } + } + } + weekly_statistics(g, m); + } +} + +} // namespace bmh + +namespace bmh { + +bool pre_match_offer(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report) { + StaticMemory& mem = g.memory; + if (mem.u32(::bmh::layout::CompetitionSelection) == 2 || mem.u8(::bmh::layout::GameMode) == 1) return false; + Record rec = record(g, manager); + const int chance = rand.range(0, 0x46 - rec.i16(0x8aa) / 0x32); + if (std::getenv("BMH_TRACE_OFFER")) + std::printf(" [pre-match offer, manager %d: W(0, %d) = %d, slots %08x %08x %08x %08x]\n", manager, + 0x46 - rec.i16(0x8aa) / 0x32, chance, mem.u32(::bmh::layout::OfferSlots), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField2), mem.u32(::bmh::layout::Weekly_PreMatchOffer_RuntimeField3)); + if (chance != 0) return false; // (unless WeeklyRuntimeField8) + const int team = int16_t(rec.u16(0x290)); + if (team == kNoTeam) return false; + // RowWhose: a free offer slot k (OfferSlots, 4 entries of -1 when free); the + // offer uses the special transfer list entry 40 + k + int k = 0; + while (k < 4 && mem.u32(::bmh::layout::OfferSlots + uint32_t(k) * 4) != 0xFFFFFFFFu) k++; + if (k == 4) return false; + const uint32_t e = kTransferList + uint32_t(0x28 + k) * kListEntry; + const SquadRange range = squad_range(team); + // a random fit player of the squad who is not bought for later (up to 100 draws hit an + // empty slot; after that the empty slot is taken, as in the original) + int slot = 0, player = 0, empty = 0; + for (;;) { + slot = rand.range(int(range.first), int(range.first + range.count) - 1); + const uint16_t v = g.squad_slots.at(size_t(slot)); + if (v == 0x0FFF && empty++ < 100) continue; + // Deliberate deviation: after 100 empty draws the original goes on with the empty + // slot and reads "player 0xFFF" beyond its player table. That happens only with a + // squad that is nearly empty (a club whose contracts all ran out); there is no + // player to make an offer for, so no offer comes (the draws so far stay as they were). + if (v == 0x0FFF) return false; + player = v & 0x0FFF; + if ((g.players.at(size_t(player)).w35c >> 27) != 0) continue; + bool bought = false; + for (int b = 0; b < 200 && !bought; b++) { + const uint32_t x = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(b) * 4); + bought = x != 0 && int(x & 0xFFF) == player; + } + if (!bought) break; + } + // Range2(slot, 0, W(90, 130), 100, 1, k): the list entry of the offer - the club, + // no bids, asking/demand percentages, market value and salary, the player in pool slot + // 0x28 + k + const int percent = rand.range(0x5a, 0x82); + mem.set16(e + 8, uint16_t(slot_team(slot))); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + mem.set8(e + 0x54, uint8_t(percent)); + mem.set8(e + 0x55, 100); + uint32_t fee = 0, salary = 0; + market_value(g, slot, 0, percent, fee, salary, 1, 0, rand); + mem.set32(e + 0x2c, fee); + mem.set32(e + 0x30, salary); + g.squad_slots.at(kPoolSlots + 0x28 + size_t(k)) = uint16_t(player); + for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF); + // half of the offers are about the salary only (a club tries to lure him away) + const bool lure = rand.range(0, 1) != 0; + if (lure) mem.set16(e + 8, 0xffe); + const int board_slot = slot - int(range.first); + const size_t board = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot; + const uint32_t saved_mailbox_recipient_mask = mem.has(::bmh::layout::MailboxRecipientMask) ? mem.u32(::bmh::layout::MailboxRecipientMask) : 0; // (restored below) + transfer_bid(g, slot, e, true, g.tactics.at(board + 0xc) / 0xc + 1, game, rand, report); + if (report.unsupported || mem.u16(e) == 0xFFFF) return false; + const int bidder = mem.u16(e); + std::string text; + bool warned = false; + if (lure) { + // what he earns now: the salary on the board plus the bonus he can expect + // (ContractOffer with the fitness correction) + const uint32_t earns = expected_bonus(g, manager, 0xff, board_slot, player, true) + + uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16 | uint32_t(g.tactics.at(board + 0x53)) << 24); + const uint32_t r = uint32_t(rand.range(0x62, 0x78)); + if (r * earns / 100 < mem.u32(e + 0xc)) { + warned = true; + // "VORSICHT! bietet ein Gehalt von X EU. (momentan Y EU). Abloesesumme: Z EU." + text = message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer) + g.club_name(bidder) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer2) + + g.player_name(g.squad_slots.at(size_t(slot)) & 0xFFF) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer3) + + format_amount(g, int32_t(mem.u32(e + 0xc))) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer4) + + format_amount(g, int32_t(uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 | + g.tactics.at(board + 0x52) << 16 | + uint32_t(g.tactics.at(board + 0x53)) << 24))) + + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer5) + format_amount(g, int32_t(mem.u32(e + 0x1c))) + "."; // (WeeklyRuntimeField9) + } + } + if (!warned) { + // (ClubName2 with 0x4000 empties the buffer: the text WeeklyRuntimeField10 is lost) + const std::string verb = message_text(g, mem.u8(e + 0x34) > 0x7f ? ::bmh::layout::Weekly_PreMatchOffer_TextPointer8 : ::bmh::layout::Weekly_PreMatchOffer_TextPointer9); + const std::string amount = format_amount(g, int32_t(mem.u32(e + 0x1c))); + text = g.club_name(bidder) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer6) + g.player_name(g.squad_slots.at(size_t(slot)) & 0xFFF) + + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer7) + + // German: " KAUFEN" (with WeeklyRuntimeField11 " "); the English MessageText puts + // the verb first: "BUY him for " + (kEnglishCompetitions ? verb + amount : amount + " " + verb) + message_text(g, ::bmh::layout::Weekly_PreMatchOffer_TextPointer10); + } + // SystemIdentity shows it, PostMessage posts it + post_composed(g, manager, text); + if (mem.has(::bmh::layout::MailboxRecipientMask)) mem.set32(::bmh::layout::MailboxRecipientMask, saved_mailbox_recipient_mask); + mem.set16(e + 8, uint16_t(team | 0x8000)); + mem.set32(::bmh::layout::OfferSlots + uint32_t(k) * 4, uint32_t(player) * 0x400 + uint32_t(manager) | (warned ? 0x80000000u : 0)); + return true; +} + +} // namespace bmh diff --git a/src/game/weekly.hpp b/src/game/weekly.hpp new file mode 100644 index 0000000..937e367 --- /dev/null +++ b/src/game/weekly.hpp @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// OpenBMH deviates from the original: uses the supported weekly processing and transfer rule profile. +// The weekly processing (DayStepRest3, BMH.exe V2.24 + supported rule profile patch). +// +// DayStepRest runs it on the day after a training day when that day has weekday code 3 +// (in games with the full economy, CompetitionSelection bit 0). In order: +// 1. per human manager: offers and incidents (Bool), the ageing of the club's +// facilities (FacilityDamage) and random damage to them (SeasonTicketCompensation), each followed +// by the season ticket compensation (Void3); every third week new advertising +// offers (TransferListCountdown2) +// 2. the transfer list (TransferListCountdown(0)): the days left of every listed player count +// down; at 0 the highest-rated eligible bid wins unless a human-seller selector is set +// 3. new bids for listed players (TransferBid) +// 4. every player in a squad: injuries in training, players out (w35c bits 27-31) come +// back or retire +// 5. per human manager: debts, the training camp bill, player bonuses, the weekly +// statistics (FacilityRating) +// Messages to the managers (PostMessage / SystemIdentity) are not produced; dialogs that +// wait for a decision of the player are reported as unsupported. + +#include "game/match_engine.hpp" +#include "game/random.hpp" +#include "game/state.hpp" +#include "game/transfer_allocator.hpp" + +#include +#include +#include + +namespace bmh { + +// Projection passed to the optional original-style seller decision callback +// (TransferListCountdown -> IncomingTransferScreen). Rows retain raw bid slots 0..3; ranking, +// quote RNG, and transaction remain in the synchronous weekly call site. +struct TransferOfferCandidateView { + int bid_index = -1; + bool present = false; + int buyer = -1; + int buyer_manager = -1; + uint32_t fee = 0; + uint32_t monthly_salary = 0; + uint32_t fee_reference = 0; // RateTransferBidSource for this offer's term + uint32_t salary_reference = 0; + uint8_t contract_months = 0; // raw term low 7 bits; high bit is loan + bool loan = false; + std::array bonuses{}; + bool affordable = false; + bool has_squad_room = false; + bool passes_foreign_limit = false; + bool loan_permitted = true; + bool transaction_supported = true; // false for human-involved loans until return lifecycle is ported + bool eligible = false; +}; + +struct TransferOfferListView { + bool valid = false; + int list_entry = -1; + int player = -1; + int seller = -1; + int seller_manager = -1; + int seller_loan_count = -1; // DeskActions_Unsupported_RuntimeField[seller_manager], -1 when unavailable + int preferred_bid_index = -1; + bool preferred_bid_passed_random_check = false; // TransferListCountdown uVar6 < ranking score + int rejected_bid_index = -1; + uint32_t notice_text_address = 0; + uint32_t quoted_fee = 0; + uint32_t quoted_monthly_salary = 0; + uint8_t quoted_years = 0; + uint32_t asking_fee = 0; + uint32_t asking_monthly_salary = 0; + int offer_count = 0; + std::array offers{}; +}; + +// Source-backed read-only events around transfer settlement and countdown +// notices. `offers` owns a snapshot of all four raw bid slots; selected_bid_index +// is the ranked raw row, not a compact row. last_week is the system modal at +// countdown 2 -> 1 and carries result_text_address PendingOffer_TransferLastWeekDialog_ExecutableField. +enum class TransferDecisionEventKind { evaluation, confirmation, last_week }; +struct TransferDecisionEvent { + TransferDecisionEventKind kind = TransferDecisionEventKind::evaluation; + TransferOfferListView offers; + int selected_bid_index = -1; + bool accepted = false; // evaluation: the one W(90,110) result; confirmation: accepted/declined + int viewer_manager = -1; // ActiveManager at evaluation; human seller first, otherwise buyer + uint32_t result_text_address = 0; // evaluation: OK/NEIN; confirmation: PendingOffer_FormatError_ExecutableField2 / PendingOffer_PendingOfferNoticeDialog_ExecutableField +}; + +// Projects the current live rows without mutation or RNG. The selector caller +// performs the Source-ranked selection and ProjectTransferOfferList post-selection check. +TransferOfferListView project_transfer_offer_list(const GameState& g, int list_entry); + +void weekly_processing(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +// The single steps, public for tests. +void manager_offers(GameState& g, int manager, WatcomRandom& rand, MinuteReport& report); // Bool +void facility_ageing(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report); // FacilityDamage +void facility_damage(GameState& g, int manager, GameRandom& game, WatcomRandom& rand); // SeasonTicketCompensation +void season_ticket_compensation(GameState& g, int manager); // Void3 +struct SeasonTicketCompensationNotice { + int manager = -1; + int missing_tickets = 0; + int usable_places = 0; + int remaining_weeks = 0; + int32_t signed_amount = 0; +}; +using SeasonTicketCompensationNoticeHook = + std::function; +// Source-visible compensation path: the notice receives the state after the +// usable-capacity calculation, but before the forced/statistical money booking. +void season_ticket_compensation_source(GameState& g, int manager, + const SeasonTicketCompensationNoticeHook& notice = {}); +void advertising_offers(GameState& g, int manager, WatcomRandom& rand, MinuteReport& report); // TransferListCountdown2 +// TransferListCountdown(all): the days left of every listed player count down; at 0 the best bid wins +// (with `all`, at the season end, every list is settled at once) +void transfer_list_countdown(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, bool all = false, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); +// TransferBid(slot, list entry, 0, -1): a new bid of some club for the player in the +// absolute squad slot (a listed player), or with list_entry 0 a move of the player to a +// club that wants him. +void transfer_bid(GameState& g, int slot, uint32_t list_entry, bool high, int months, GameRandom& game, + WatcomRandom& rand, MinuteReport& report); +void weekly_statistics(GameState& g, int manager); // FacilityRating + +// FacilityRating2(manager, with_rand, &second): rating of a human club's stadium facilities +// (about 24-100). *second receives the covered share of the stands in percent. With `rand` +// (the attendance calculation) every stand under construction costs 10-12 % of the +// facility sum, drawn per stand. +int facility_rating(GameState& g, int manager, int* second, WatcomRandom* rand = nullptr); + +// Squad helpers shared with the month change (month.cpp): +// Nationality: nationality of a player (w368 bits 27-31, +32 with the flag in *PlayerBonuses). +int nationality(const GameState& g, int player); +// SquadCount(team, flags): players of a club (bit 1: the injured too; bit 0: plus the +// players bought for later, table Career_RemoveJoinLoans_RuntimeField). +int squad_count(const GameState& g, int team, int flags); +// SlotTeam: club of an absolute squad slot, -1 for the transfer pool. +int slot_team(int slot); +// Int2(team, 100) after a transfer (only clubs with a squad). +void lineup_after_transfer(GameState& g, int team); +// ReleasePlayer(seller, player): the player leaves the club (0xFFF: the pool). +bool remove_from_seller(GameState& g, int seller, int player, MinuteReport& report); +// Finalize a high-confidence manager offer immediately after the seller/player accepts it. +bool accept_transfer_bid_immediately(GameState& g, int list_entry, int bid, WatcomRandom& rand, + MinuteReport& report, + TransferAllocatorContext allocator = TransferAllocatorContext::unsupported); + +} // namespace bmh + +namespace bmh { + +// PreMatchOffer, before a human manager's matchday: now and then a club makes an offer for +// one of his players (1 in 71 - manager rating / 50). +// Returns whether an offer was shown (its message box waits for a click before the desk). +bool pre_match_offer(GameState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report); + +// ClubAttraction(team, 0): how attractive a club is for advertisers (0-100): its European +// campaign, its league and table position (weekly.cpp). +int club_attraction(const GameState& g, int team); + +} // namespace bmh diff --git a/src/launch/archive.cpp b/src/launch/archive.cpp new file mode 100644 index 0000000..64f25df --- /dev/null +++ b/src/launch/archive.cpp @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "launch/archive.hpp" + +#include +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#endif + +#include "miniz.h" + +extern "C" { +#include "7z.h" +#include "7zAlloc.h" +#include "7zCrc.h" +} + +namespace bmh::launch { + +namespace { + +std::vector read_whole(const std::filesystem::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) throw ArchiveError("cannot open " + path_to_utf8(file)); + in.seekg(0, std::ios::end); + const auto size = in.tellg(); + if (size < 0) throw ArchiveError("cannot read " + path_to_utf8(file)); + // The largest real package (a box with three editions) has 55 MB; anything far beyond + // that is no BMH package. + if (uint64_t(size) > 512ull * 1024 * 1024) throw ArchiveError(path_to_utf8(file) + " is too large for a BMH package"); + std::vector data(static_cast(size)); + in.seekg(0); + in.read(reinterpret_cast(data.data()), std::streamsize(data.size())); + if (!in) throw ArchiveError("cannot read " + path_to_utf8(file)); + return data; +} + +// Code page 437 (the DOS code page old ZIP tools wrote names in) to UTF-8, for names +// without the ZIP UTF-8 flag. Only the upper half differs from ASCII. +std::string cp437_to_utf8(const std::string& text) { + static const char16_t kHigh[128] = { + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0}; + std::string out; + for (unsigned char c : text) { + const unsigned u = c < 0x80 ? c : kHigh[c - 0x80]; + if (u < 0x80) out += char(u); + else if (u < 0x800) out += char(0xC0 | (u >> 6)), out += char(0x80 | (u & 0x3F)); + else out += char(0xE0 | (u >> 12)), out += char(0x80 | ((u >> 6) & 0x3F)), out += char(0x80 | (u & 0x3F)); + } + return out; +} + +std::string utf16_to_utf8(const std::vector& text) { + std::string out; + for (size_t i = 0; i < text.size() && text[i] != 0; ++i) { + uint32_t u = text[i]; + if (u >= 0xD800 && u < 0xDC00 && i + 1 < text.size() && text[i + 1] >= 0xDC00 && text[i + 1] < 0xE000) + u = 0x10000 + ((u - 0xD800) << 10) + (text[++i] - 0xDC00); + if (u < 0x80) out += char(u); + else if (u < 0x800) out += char(0xC0 | (u >> 6)), out += char(0x80 | (u & 0x3F)); + else if (u < 0x10000) out += char(0xE0 | (u >> 12)), out += char(0x80 | ((u >> 6) & 0x3F)), out += char(0x80 | (u & 0x3F)); + else + out += char(0xF0 | (u >> 18)), out += char(0x80 | ((u >> 12) & 0x3F)), out += char(0x80 | ((u >> 6) & 0x3F)), + out += char(0x80 | (u & 0x3F)); + } + return out; +} + +std::string normalise(std::string name) { + for (char& c : name) + if (c == '\\') c = '/'; + while (!name.empty() && name.front() == '/') name.erase(name.begin()); + return name; +} + +// The LZMA SDK reads through an ISeekInStream; this one serves the archive from memory. +struct MemoryStream { + ISeekInStream vt; // first member: the SDK passes &vt around + const uint8_t* data = nullptr; + size_t size = 0, pos = 0; +}; + +SRes memory_read(ISeekInStreamPtr p, void* buf, size_t* size) { + auto* s = reinterpret_cast(const_cast(p)); + const size_t n = std::min(*size, s->size - s->pos); + std::memcpy(buf, s->data + s->pos, n); + s->pos += n; + *size = n; + return SZ_OK; +} + +SRes memory_seek(ISeekInStreamPtr p, Int64* pos, ESzSeek origin) { + auto* s = reinterpret_cast(const_cast(p)); + Int64 base = origin == SZ_SEEK_SET ? 0 : origin == SZ_SEEK_CUR ? Int64(s->pos) : Int64(s->size); + const Int64 target = base + *pos; + if (target < 0 || uint64_t(target) > s->size) return SZ_ERROR_PARAM; + s->pos = size_t(target); + *pos = target; + return SZ_OK; +} + +} // namespace + +std::filesystem::path path_from_utf8(const std::string& text) { + return std::filesystem::path(std::u8string(text.begin(), text.end())); +} + +std::string path_to_utf8(const std::filesystem::path& path) { + const std::u8string u = path.u8string(); + return std::string(u.begin(), u.end()); +} + +std::vector utf8_arguments(int argc, char** argv) { + std::vector out; +#ifdef _WIN32 + int count = 0; + if (LPWSTR* wide = CommandLineToArgvW(GetCommandLineW(), &count)) { + for (int i = 0; i < count; ++i) out.push_back(path_to_utf8(std::filesystem::path(wide[i]))); + LocalFree(wide); + if (count == argc) return out; + out.clear(); + } +#endif + for (int i = 0; i < argc; ++i) out.emplace_back(argv[i]); + return out; +} + +ArchiveFormat archive_format(const std::filesystem::path& file) { + std::ifstream in(file, std::ios::binary); + unsigned char head[8] = {}; + in.read(reinterpret_cast(head), sizeof head); + if (in.gcount() < 4) return ArchiveFormat::none; + if (head[0] == 'P' && head[1] == 'K' && (head[2] == 3 || head[2] == 5) && (head[3] == 4 || head[3] == 6)) + return ArchiveFormat::zip; + if (in.gcount() >= 6 && std::memcmp(head, "7z\xBC\xAF\x27\x1C", 6) == 0) return ArchiveFormat::seven_zip; + if (head[0] == 0x60 && head[1] == 0xEA) return ArchiveFormat::arj; + if (std::memcmp(head, "Rar!", 4) == 0) return ArchiveFormat::rar; + return ArchiveFormat::none; +} + +struct Archive::Impl { + ArchiveFormat format = ArchiveFormat::none; + std::vector bytes; + std::vector entries; + std::vector source_index; // entry -> index in the archive's own list + // ZIP + mz_zip_archive zip{}; + bool zip_open = false; + // 7z + MemoryStream stream; + CLookToRead2 look{}; + CSzArEx db{}; + ISzAlloc alloc{SzAlloc, SzFree}; + bool db_open = false; + UInt32 block_index = 0xFFFFFFFF; // the solid block cached in out_buffer + Byte* out_buffer = nullptr; + size_t out_buffer_size = 0; + + ~Impl() { + if (zip_open) mz_zip_reader_end(&zip); + if (db_open) SzArEx_Free(&db, &alloc); + if (out_buffer) ISzAlloc_Free(&alloc, out_buffer); + if (look.buf) ISzAlloc_Free(&alloc, look.buf); + } + + void open_zip() { + if (!mz_zip_reader_init_mem(&zip, bytes.data(), bytes.size(), 0)) + throw ArchiveError(std::string("damaged ZIP archive: ") + mz_zip_get_error_string(mz_zip_get_last_error(&zip))); + zip_open = true; + const mz_uint count = mz_zip_reader_get_num_files(&zip); + for (mz_uint i = 0; i < count; ++i) { + mz_zip_archive_file_stat st{}; + if (!mz_zip_reader_file_stat(&zip, i, &st)) throw ArchiveError("damaged ZIP directory"); + // bit 11 of the general purpose flags: the name is UTF-8 + const bool utf8 = (st.m_bit_flag & 0x800) != 0; + std::string name = st.m_filename; + entries.push_back({normalise(utf8 ? name : cp437_to_utf8(name)), st.m_uncomp_size, st.m_is_directory != 0}); + source_index.push_back(i); + } + } + + void open_7z() { + static const bool crc_ready = [] { CrcGenerateTable(); return true; }(); + (void)crc_ready; + stream.vt.Read = memory_read; + stream.vt.Seek = memory_seek; + stream.data = bytes.data(); + stream.size = bytes.size(); + LookToRead2_CreateVTable(&look, False); + constexpr size_t kBuffer = size_t(1) << 18; + look.buf = static_cast(ISzAlloc_Alloc(&alloc, kBuffer)); + if (!look.buf) throw ArchiveError("out of memory"); + look.bufSize = kBuffer; + look.realStream = &stream.vt; + LookToRead2_INIT(&look); + SzArEx_Init(&db); + if (SzArEx_Open(&db, &look.vt, &alloc, &alloc) != SZ_OK) throw ArchiveError("damaged 7z archive"); + db_open = true; + for (UInt32 i = 0; i < db.NumFiles; ++i) { + const size_t len = SzArEx_GetFileNameUtf16(&db, i, nullptr); + std::vector name(len); + SzArEx_GetFileNameUtf16(&db, i, name.data()); + const bool dir = SzArEx_IsDir(&db, i) != 0; + entries.push_back({normalise(utf16_to_utf8(name)), dir ? 0 : SzArEx_GetFileSize(&db, i), dir}); + source_index.push_back(i); + } + } +}; + +Archive::Archive(std::unique_ptr impl) : impl_(std::move(impl)) {} +Archive::Archive(Archive&&) noexcept = default; +Archive& Archive::operator=(Archive&&) noexcept = default; +Archive::~Archive() = default; + +Archive Archive::open(const std::filesystem::path& file) { + const ArchiveFormat format = archive_format(file); + if (format != ArchiveFormat::zip && format != ArchiveFormat::seven_zip) + throw ArchiveError(path_to_utf8(file) + " is no ZIP or 7z archive"); + auto impl = std::make_unique(); + impl->format = format; + impl->bytes = read_whole(file); + if (format == ArchiveFormat::zip) impl->open_zip(); + else impl->open_7z(); + return Archive(std::move(impl)); +} + +ArchiveFormat Archive::format() const { return impl_->format; } +const std::vector& Archive::entries() const { return impl_->entries; } + +std::vector Archive::read(size_t index) { + Impl& a = *impl_; + if (index >= a.entries.size()) throw ArchiveError("no such archive entry"); + if (a.entries[index].directory) return {}; + if (a.format == ArchiveFormat::zip) { + size_t size = 0; + void* p = mz_zip_reader_extract_to_heap(&a.zip, a.source_index[index], &size, 0); + if (!p) throw ArchiveError("cannot unpack " + a.entries[index].name); + std::vector out(static_cast(p), static_cast(p) + size); + mz_free(p); + return out; + } + size_t offset = 0, processed = 0; + if (SzArEx_Extract(&a.db, &a.look.vt, a.source_index[index], &a.block_index, &a.out_buffer, &a.out_buffer_size, + &offset, &processed, &a.alloc, &a.alloc) != SZ_OK) + throw ArchiveError("cannot unpack " + a.entries[index].name); + return std::vector(a.out_buffer + offset, a.out_buffer + offset + processed); +} + +} // namespace bmh::launch diff --git a/src/launch/archive.hpp b/src/launch/archive.hpp new file mode 100644 index 0000000..7fce4be --- /dev/null +++ b/src/launch/archive.hpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Read-only access to the archives a player may hand to OpenBMH instead of an installed +// game directory: ZIP (miniz) and 7z (the LZMA SDK's C decoder). The archive is read into +// memory once, so paths with characters outside the ANSI code page (the box names contain +// an en dash) work on Windows too. ARJ (the 1994 installation disk) and RAR are recognised +// only to give a clear message. + +#include +#include +#include +#include +#include +#include + +namespace bmh::launch { + +class ArchiveError : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +enum class ArchiveFormat { none, zip, seven_zip, arj, rar }; + +// The format by the first bytes of the file (none: not an archive we know). +ArchiveFormat archive_format(const std::filesystem::path& file); + +struct ArchiveEntry { + std::string name; // UTF-8, '/' as separator, no leading '/' + uint64_t size = 0; // uncompressed size + bool directory = false; +}; + +class Archive { +public: + // Opens a ZIP or 7z archive; throws ArchiveError for anything else or a damaged file. + static Archive open(const std::filesystem::path& file); + Archive(Archive&&) noexcept; + Archive& operator=(Archive&&) noexcept; + ~Archive(); + + ArchiveFormat format() const; + const std::vector& entries() const; + // The uncompressed bytes of entry `index`. + std::vector read(size_t index); + + struct Impl; + +private: + explicit Archive(std::unique_ptr impl); + std::unique_ptr impl_; +}; + +// A path from UTF-8 text (std::filesystem::path(std::string) would use the ANSI code page on +// Windows). +std::filesystem::path path_from_utf8(const std::string& text); +std::string path_to_utf8(const std::filesystem::path& path); + +// The program arguments as UTF-8. On Windows `argv` is in the ANSI code page, which cannot +// hold every file name (an en dash, other alphabets); there the wide command line is used. +std::vector utf8_arguments(int argc, char** argv); + +} // namespace bmh::launch diff --git a/src/launch/file_dialog.cpp b/src/launch/file_dialog.cpp new file mode 100644 index 0000000..88dac73 --- /dev/null +++ b/src/launch/file_dialog.cpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "launch/file_dialog.hpp" + +#include + +#include + +#include "launch/archive.hpp" + +namespace bmh::launch { + +std::optional choose_game_file(const std::string& title) { + (void)title; // (nfd 1.2 has no dialog title parameter; the window title is the system's) + NFD::Guard guard; + NFD::UniquePathU8 path; + // one filter with all accepted kinds; the check after the choice decides + const nfdu8filteritem_t filters[] = {{"BMH game (ZIP, 7z, BMH.EXE, FLTD.EXE)", "zip,7z,exe"}}; + const nfdresult_t result = NFD::OpenDialog(path, filters, 1); + if (result == NFD_CANCEL) return std::nullopt; + if (result != NFD_OKAY) throw std::runtime_error(std::string("no file dialog: ") + NFD::GetError()); + return path_from_utf8(path.get()); +} + +} // namespace bmh::launch diff --git a/src/launch/file_dialog.hpp b/src/launch/file_dialog.hpp new file mode 100644 index 0000000..2a89752 --- /dev/null +++ b/src/launch/file_dialog.hpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The system's "open file" dialog for choosing the game when OpenBMH starts without one: +// a ZIP/7z archive or the game's EXE. Windows, macOS and Linux (GTK or the desktop portal) +// through nativefiledialog-extended. + +#include +#include +#include + +namespace bmh::launch { + +// nullopt when the player cancels; throws std::runtime_error when no dialog can be shown +// (e.g. no desktop session on Linux). +std::optional choose_game_file(const std::string& title); + +} // namespace bmh::launch diff --git a/src/launch/fltd.cpp b/src/launch/fltd.cpp new file mode 100644 index 0000000..6ed3ed3 --- /dev/null +++ b/src/launch/fltd.cpp @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "launch/fltd.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "formats/rule_base.hpp" +#include "launch/archive.hpp" +#include "launch/game_data.hpp" + +namespace fs = std::filesystem; + +namespace bmh::launch { + +namespace { + +// The English image: address = file offset - 0x496d (157 of 165 data strings are referenced +// with that offset), initialised data up to Career_CompetitionPointersEnglish_RuntimeField. +constexpr uint32_t kEnFileOffset = 0x496d; +constexpr uint32_t kEnDataStart = ::bmh::layout::EnDataStart, kEnDataEnd = ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField; +constexpr uint32_t kFltdSize = 507925; +// The German image the engine expects: LE objects from layout field, data object GermanDataSegmentBegin-layout field. +constexpr uint32_t kDeBase = 0x10000, kDeEnd = ::bmh::layout::GermanImageEnd; +// A zero byte in the German BSS: the empty string of empty_pointers entries. +constexpr uint32_t kEmptyString = ::bmh::layout::EmptyString; + +enum class Kind { copy, keep, empty_pointers, own_text }; + +struct Entry { + uint32_t de; // German address + uint32_t length; // bytes of the German object (texts: with the closing NUL) + Kind kind; + uint32_t en; // English address (copy) + std::vector bytes; // the German values (keep) +}; + +const std::vector kMap = { +#include "launch/fltd_map.inc" +}; + +// OpenBMH's English texts for V2.24 texts the English V2.20 does not have. Each must fit the +// German text's room (its length including the NUL). +struct OwnText { + uint32_t de; + const char* text; +}; +const OwnText kOwnTexts[] = { + {::bmh::layout::Fltd_Layout_TextPointer, ", "}, + {::bmh::layout::Fltd_Layout_TextPointer2, ": "}, + {::bmh::layout::Fltd_Layout_TextPointer3, "s"}, // plural ending (German "e") + {::bmh::layout::Fltd_Layout_TextPointer4, " #"}, + {::bmh::layout::Fltd_Layout_TextPointer5, "Competition closed"}, + {::bmh::layout::Fltd_Layout_ExecutableField, "As not all season ticket holders fit into the stadium, you pay "}, + {::bmh::layout::Fltd_Layout_ExecutableField2, " compensation."}, + {::bmh::layout::CareerSession_FormatNumber_TextPointer, "("}, + {::bmh::layout::CareerSession_FormatNumber_ExecutableField2, "# disc.)"}, + {::bmh::layout::Fltd_Layout_ExecutableField3, "The sponsor feels exploited. He pays only "}, + {::bmh::layout::Fltd_Layout_ExecutableField4, " percent of the price."}, + {::bmh::layout::CurrencySuffixText, " &"}, // the pound sign of the English font + {::bmh::layout::Fltd_Layout_ExecutableField5, "AUTO"}, + {::bmh::layout::BalancePlan_DrawRows_TextPointer, "+)"}, + {::bmh::layout::Fltd_Layout_ExecutableField6, "-"}, +}; + +} // namespace + +LeImage translate_fltd(const fs::path& fltd_exe) { + const Bytes raw = read_file(fltd_exe); + if (raw.size() != kFltdSize || raw[0] != 'M' || raw[1] != 'Z') + throw std::runtime_error(path_to_utf8(fltd_exe) + " is not the Football Limited FLTD.EXE"); + const auto en = [&](uint32_t address) -> uint8_t { + const size_t at = size_t(address) + kEnFileOffset; + return at < raw.size() ? raw[at] : 0; + }; + Bytes image(kDeEnd - kDeBase, 0); + const auto put = [&](uint32_t address, uint8_t value) { + if (address < kDeBase || address >= kDeEnd) throw std::runtime_error("FLTD map outside the image"); + image[address - kDeBase] = value; + }; + // the English data segment at its own addresses (German code addresses: never read as data) + for (uint32_t a = kEnDataStart; a < kEnDataEnd; ++a) put(a, en(a)); + // (the map is sorted by German address; a copy reaches up to the next entry, because the + // object extents of the decompiler are sometimes finer than the tables - LeagueSizes/a2bce) + // (the German values are written last: a keep-de range such as the competition table + // CupTable covers entries inside it) + for (int pass = 0; pass < 2; ++pass) + for (size_t n = 0; n < kMap.size(); ++n) { + const Entry& e = kMap[n]; + if ((e.kind == Kind::keep) != (pass == 1)) continue; + switch (e.kind) { + case Kind::copy: { + uint32_t length = e.length; + if (n + 1 < kMap.size() && kMap[n + 1].de > e.de) length = std::max(length, std::min(kMap[n + 1].de - e.de, 0x800u)); + for (uint32_t i = 0; i < length; ++i) put(e.de + i, en(e.en + i)); + break; + } + case Kind::keep: + for (uint32_t i = 0; i < e.length && i < e.bytes.size(); ++i) put(e.de + i, e.bytes[i]); + break; + case Kind::empty_pointers: + for (uint32_t i = 0; i + 4 <= e.length; i += 4) + for (uint32_t b = 0; b < 4; ++b) put(e.de + i + b, uint8_t(kEmptyString >> (8 * b))); + break; + case Kind::own_text: { + const OwnText* t = nullptr; + for (const OwnText& o : kOwnTexts) + if (o.de == e.de) t = &o; + const std::string text = t ? t->text : ""; + if (text.size() + 1 > e.length) throw std::runtime_error("English text does not fit at " + std::to_string(e.de)); + for (uint32_t i = 0; i < e.length; ++i) put(e.de + i, i < text.size() ? uint8_t(text[i]) : 0); + break; + } + } + } + LeImage out = LeImage::from_bytes(kDeBase, std::move(image)); + apply_rule_base(out); + return out; +} + +bool prepare_english_game(const fs::path& source, const fs::path& target, std::string& error) { + try { + std::error_code ec; + fs::create_directories(target); + const auto copy = [&](const fs::path& from, const fs::path& to) { + fs::create_directories(to.parent_path()); + fs::copy_file(from, to, fs::copy_options::overwrite_existing); + }; + // the shared data files and directories (names as the German game has them) + for (const char* name : {"M3.DAT", "M3.MEN", "M3PC.COL"}) + if (auto f = find_file(source, name)) copy(*f, target / name); + for (const char* dir : {"KB", "W", "F", "S"}) { + auto d = find_file(source, dir); + if (!d) continue; + for (const auto& e : fs::directory_iterator(*d)) { + std::string name = path_to_utf8(e.path().filename()); + for (char& c : name) c = char(std::toupper(static_cast(c))); + if (e.is_regular_file()) copy(e.path(), target / dir / path_from_utf8(name)); + } + } + if (auto f = find_file(source, "TEXTE.BLK")) copy(*f, target / "TEXTD.BLK"); + if (auto f = find_file(source, "M3E.MAN")) copy(*f, target / "M3D.MAN"); + const auto exe = find_file(source, "FLTD.EXE"); + if (!exe) throw std::runtime_error("FLTD.EXE is missing"); + save_image(translate_fltd(*exe), target / "BMH.exe"); + return true; + } catch (const std::exception& e) { + error = e.what(); + return false; + } +} + +} // namespace bmh::launch diff --git a/src/launch/fltd.hpp b/src/launch/fltd.hpp new file mode 100644 index 0000000..c67e5f3 --- /dev/null +++ b/src/launch/fltd.hpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The English "Football Limited" (FLTD.EXE) as data for the one OpenBMH engine. +// +// The engine reads its data the German way: BMH.EXE tables at German addresses, TEXTD.BLK and +// M3D.MAN. prepare_english_game() turns an English installation into such a data directory, +// once, in the launcher cache: +// - TEXTE.BLK -> TEXTD.BLK and M3E.MAN -> M3D.MAN (same formats, the text slots are the +// same variables; docs/formats/TEXTD_INVENTORY.md), +// - FLTD.EXE -> "BMH.exe" in the OpenBMH image format (formats/le.hpp): an image in the +// German address space. Every German data object the engine reads is filled from its +// English counterpart (src/launch/fltd_map.inc, generated by runtime verification), German +// numbers keep V2.24 features the English V2.20 lacks, OpenBMH's own English texts +// stand in for V2.24 texts, and the whole English data segment also lies at its own +// addresses so that English pointers stay valid. Then the rule base is applied. +// - the pictures, fonts, sounds and the other data files are copied unchanged. +// The English league structure (20 20 20 20 10 + the four international leagues of 12) +// arrives through the size table at LeagueSizes and is installed by the career session. +// Background: runtime verification + +#include +#include + +#include "formats/le.hpp" + +namespace bmh::launch { + +// The German-layout image of FLTD.EXE (throws std::runtime_error for another file). +LeImage translate_fltd(const std::filesystem::path& fltd_exe); + +// Builds the German-layout data directory `target` from the English game in `source`. +// Returns false with `error` set when a file cannot be read or written. +bool prepare_english_game(const std::filesystem::path& source, const std::filesystem::path& target, std::string& error); + +} // namespace bmh::launch diff --git a/src/launch/fltd_map.inc b/src/launch/fltd_map.inc new file mode 100644 index 0000000..572856f --- /dev/null +++ b/src/launch/fltd_map.inc @@ -0,0 +1,355 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Generated by runtime verification - do not edit. DE data object -> FLTD.EXE (EN address). +// {DE address, length, kind, EN address, keep-de bytes} + {::bmh::layout::GermanDataSegmentBegin, 4, Kind::keep, 0, {0x01,0x01,0x01,0x00}}, + {::bmh::layout::DeskDrawers_Recent_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation162, {}}, + {::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation244, {}}, + {::bmh::layout::TransferMarket_Rect_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation245, {}}, + {::bmh::layout::TransferMarket_Rect_TextPointer2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation248, {}}, + {::bmh::layout::TransferMarket_Rect_ExecutableField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation249, {}}, + {::bmh::layout::TransferMarket_Rect_ExecutableField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation250, {}}, + {::bmh::layout::Fltd_Layout_TextPointer, 3, Kind::own_text, 0, {}}, // V2.24 format string of the transfer screens (in DE also used by the supported rule profile patch FltdMapOperation; EN pair still to find) + {::bmh::layout::Fltd_Layout_TextPointer2, 3, Kind::own_text, 0, {}}, // V2.24 format string of the transfer screens + {::bmh::layout::Fltd_Layout_TextPointer3, 2, Kind::own_text, 0, {}}, // V2.24 format string of the transfer screens + {::bmh::layout::Fltd_Layout_TextPointer4, 3, Kind::own_text, 0, {}}, // V2.24 format string of the transfer screens + {::bmh::layout::Fltd_Layout_TextPointer5, 20, Kind::own_text, 0, {}}, // 'Wettbewerb gesperrt' (V2.24, date text of DeskDate2; EN 677 has none) + {::bmh::layout::LeaguePairings_DateString_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation5, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation6, {}}, + {::bmh::layout::Calendar_Information_ExecutableField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation158, {}}, + {::bmh::layout::Calendar_Information_TextPointer, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation159, {}}, + {::bmh::layout::ClubInfo_Raw_ExecutableField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation164, {}}, + {::bmh::layout::Contracts_RenderRoster_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation165, {}}, + {::bmh::layout::ClubInfo_Render_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation166, {}}, + {::bmh::layout::ClubInfo_Render_ExecutableField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation167, {}}, + {::bmh::layout::ClubInfo_Render_ExecutableField2, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation168, {}}, + {::bmh::layout::ClubInfo_Render_ExecutableField3, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation169, {}}, + {::bmh::layout::ClubInfo_Render_ExecutableField4, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation170, {}}, + {::bmh::layout::ClubInfo_Render_ExecutableField5, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation171, {}}, + {::bmh::layout::ClubInfo_Raw_ExecutableField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation172, {}}, + {::bmh::layout::Contracts_RenderRoster_ExecutableField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation173, {}}, + {::bmh::layout::Contracts_RenderRoster_ExecutableField3, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation174, {}}, + {::bmh::layout::Contracts_RenderRoster_ExecutableField4, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation175, {}}, + {::bmh::layout::IncomingTransfer_RenderAtElapsed_ExecutableField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation121, {}}, + {::bmh::layout::ContractExpiryWarningText, 75, Kind::own_text, 0, {}}, // Contract warnings are read from each edition's own runtime field. + {::bmh::layout::Fltd_Layout_ExecutableField, 75, Kind::own_text, 0, {}}, // pending offer notice (Void3, no EN pair) + {::bmh::layout::Fltd_Layout_ExecutableField2, 16, Kind::own_text, 0, {}}, // pending offer notice + {::bmh::layout::CareerSession_FormatNumber_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation141, {}}, + {::bmh::layout::Stadium_FormatError_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation142, {}}, + {::bmh::layout::Stadium_FormatError_ExecutableField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation146, {}}, + {::bmh::layout::Stadium_Out_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation147, {}}, + {::bmh::layout::Stadium_RenderBlockExpansion_TextPointer, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation148, {}}, + {::bmh::layout::CareerSession_FormatNumber_TextPointer, 2, Kind::own_text, 0, {}}, // '(' of '(# Rabatt)', V2.24 stadium discount (ConstructionPricePercent; not in EN 28b6d) + {::bmh::layout::CareerSession_FormatNumber_ExecutableField2, 10, Kind::own_text, 0, {}}, // '# Rabatt)' V2.24 + {::bmh::layout::Fltd_Layout_ExecutableField3, 49, Kind::own_text, 0, {}}, // 'Der Sponsor fuehlt sich ausgenutzt ...' V2.24 (PayConstruction; not in EN 2b38d) + {::bmh::layout::Fltd_Layout_ExecutableField4, 26, Kind::own_text, 0, {}}, // ' Prozent der Kaufsumme' V2.24 + {::bmh::layout::ClubPlayerDetail_Copy_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation302, {}}, + {::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation303, {}}, + {::bmh::layout::Contracts_Out_TextPointer, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation148, {}}, + {::bmh::layout::ClubPlayerDetail_Copy_TextPointer, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation305, {}}, + {::bmh::layout::ClubPlayerDetail_Copy_TextPointer2, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation306, {}}, + {::bmh::layout::CurrencySuffixText, 4, Kind::own_text, 0, {}}, // ' EU' currency suffix (FormatNumber; EN FormatAmount formats money without a suffix string) + {::bmh::layout::Bank_OriginalToUtf8_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation193, {}}, + {::bmh::layout::Fltd_Layout_ExecutableField5, 5, Kind::own_text, 0, {}}, // 'AUTO' (NeedsInitialization; not in EN 43100: V2.24 training automation) + {::bmh::layout::Bank_FormatError_ExecutableField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation148, {}}, + {::bmh::layout::Bank_OriginalToUtf8_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation203, {}}, + {::bmh::layout::Bank_OriginalToUtf8_ExecutableField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation204, {}}, + {::bmh::layout::Bank_DrawPropertyCard_TextPointer, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation205, {}}, + {::bmh::layout::Bank_OriginalToUtf8_ExecutableField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation216, {}}, + {::bmh::layout::Bank_OriginalToUtf8_ExecutableField4, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation217, {}}, + {::bmh::layout::Bank_OriginalToUtf8_TextPointer2, 19, Kind::copy, ::bmh::layout::EnglishLayoutTranslation218, {}}, + {::bmh::layout::GermanLayoutTranslation, 11, Kind::copy, ::bmh::layout::EnglishLayoutTranslation219, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation96, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer3, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation97, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer4, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation98, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer5, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation99, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer6, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation100, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer7, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation101, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer8, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation102, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer9, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation103, {}}, + {::bmh::layout::LeagueTable_Glyph_TextPointer, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation104, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer10, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation105, {}}, + {::bmh::layout::CupDraw_DrawGroupOverview_TextPointer11, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation106, {}}, + {::bmh::layout::CareerSession_FormatError_TextPointer, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation109, {}}, + {::bmh::layout::LeaguePairings_Fill_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation110, {}}, + {::bmh::layout::LeaguePairings_FormatError_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation111, {}}, + {::bmh::layout::LeaguePairings_FormatError_ExecutableField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation112, {}}, + {::bmh::layout::LeaguePairings_FormatError_TextPointer2, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation219, {}}, + {::bmh::layout::LeaguePairings_FormatError_TextPointer3, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation149, {}}, + {::bmh::layout::Strengths_Fill_TextPointer, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation118, {}}, + {::bmh::layout::SaveLoad_Render_ExecutableField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation300, {}}, + {::bmh::layout::SaveLoad_Render_TextPointer, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation205, {}}, + {::bmh::layout::BalancePlan_DrawRows_TextPointer, 3, Kind::own_text, 0, {}}, // balance plan (Redraw, V2.24 balance plan) + {::bmh::layout::Advertising_FormatError_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation123, {}}, + {::bmh::layout::Advertising_FormatError_ExecutableField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation128, {}}, + {::bmh::layout::Advertising_FormatError_ExecutableField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation129, {}}, + {::bmh::layout::Advertising_String_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation130, {}}, + {::bmh::layout::CupDraw_FormatError_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation44, {}}, + {::bmh::layout::CupDraw_FormatError_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation45, {}}, + {::bmh::layout::CupDraw_FormatError_ExecutableField2, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation46, {}}, + {::bmh::layout::CupDraw_FormatError_TextPointer2, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation47, {}}, + {::bmh::layout::CupDraw_FormatError_TextPointer3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation48, {}}, + {::bmh::layout::RealityReporter_Font_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation49, {}}, // reporter word separator (DE RealityReporterPanel3 / EN dcb4) + {::bmh::layout::Fltd_Layout_ExecutableField6, 2, Kind::own_text, 0, {}}, // '-' (RealityReporterPanel2; EN dc3f only has ' ') + {::bmh::layout::SeriesRecords_Render_ExecutableField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation68, {}}, + {::bmh::layout::DeskRecords_FillRect_ExecutableField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation69, {}}, + {::bmh::layout::SeriesRecords_Render_ExecutableField4, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation70, {}}, + {::bmh::layout::TeamStatistics_Render_ExecutableField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation72, {}}, + {::bmh::layout::DeskDrawers_Curve_ExecutableField, 24, Kind::copy, ::bmh::layout::EnglishLayoutTranslation160, {}}, + {::bmh::layout::DeskState_FormatError_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation161, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation224, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation225, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField3, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation226, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField4, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation227, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField5, 11, Kind::copy, ::bmh::layout::EnglishLayoutTranslation228, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField6, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation229, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField7, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation230, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField8, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation231, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField9, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation232, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField10, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation233, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField11, 72, Kind::copy, ::bmh::layout::EnglishLayoutTranslation234, {}}, + {::bmh::layout::Tactics_DrawSetting_RuntimeField12, 71, Kind::copy, ::bmh::layout::EnglishLayoutTranslation235, {}}, + {::bmh::layout::Tactics_Click_RuntimeField, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation236, {}}, + {::bmh::layout::Tactics_Click_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation237, {}}, + {::bmh::layout::Tactics_Click_RuntimeField3, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation238, {}}, + {::bmh::layout::Tactics_Click_RuntimeField4, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation239, {}}, + {::bmh::layout::Tactics_Click_RuntimeField5, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation240, {}}, + {::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation241, {}}, + {::bmh::layout::Tactics_Click_RuntimeField6, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation242, {}}, + {::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation243, {}}, + {::bmh::layout::TransferMarket_Click_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation246, {}}, + {::bmh::layout::TransferMarket_Click_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation246, {}}, + {::bmh::layout::TransferMarket_Click_RuntimeField3, 74, Kind::copy, ::bmh::layout::EnglishLayoutTranslation247, {}}, + {::bmh::layout::Bank_OriginalToUtf8_RuntimeField, 144, Kind::empty_pointers, 0, {}}, + {::bmh::layout::Analytics_FormatError_ExecutableField, 72, Kind::copy, ::bmh::layout::EnglishLayoutTranslation50, {}}, // EN196f1: graph labels, distinct from fund-name suffixes + {::bmh::layout::AdGroupId, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation51, {}}, + {::bmh::layout::GameEnd_SourceHyphenator_ExecutableField, 18, Kind::copy, ::bmh::layout::EnglishLayoutTranslation52, {}}, + {::bmh::layout::GameEnd_SourceHyphenator_RuntimeField, 120, Kind::copy, ::bmh::layout::EnglishLayoutTranslation53, {}}, + {::bmh::layout::CareerSession_DispatchSettings_RuntimeField, 20, Kind::copy, ::bmh::layout::EnglishLayoutTranslation54, {}}, + {::bmh::layout::SaveLoad_Render_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation55, {}}, + {::bmh::layout::SaveLoad_Render_RuntimeField2, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation56, {}}, + {::bmh::layout::SaveLoad_Render_RuntimeField3, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation57, {}}, + {::bmh::layout::DeskActions_ConfigureTrainingCampData_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation58, {}}, + {::bmh::layout::Difficulty, 1, Kind::keep, 0, {0x05}}, + {::bmh::layout::ManagerAutomation, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation59, {}}, + {::bmh::layout::DeskState_DeskDate_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation60, {}}, + {::bmh::layout::CalendarState_CalendarFromGame_ExecutableField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation61, {}}, + {::bmh::layout::CalendarState_CalendarFromGame_ExecutableField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation62, {}}, + {::bmh::layout::ManagerCount, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation63, {}}, + {::bmh::layout::LeaguePresentationOptions, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation64, {}}, + {::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField3, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation65, {}}, + {::bmh::layout::SeasonEntrants_SeasonEntrantsFromGame_TextPointer, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation66, {}}, + {::bmh::layout::PlainBackground, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation67, {}}, + {::bmh::layout::ActiveSelectors, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation251, {}}, + {::bmh::layout::CurrencyMultiplier, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation252, {}}, + {::bmh::layout::CurrencyDivisor, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation253, {}}, + {::bmh::layout::CompetitionCalendar, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation254, {}}, + {::bmh::layout::LeagueCalendarBits, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation255, {}}, + {::bmh::layout::EventPasses, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation256, {}}, + {::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation257, {}}, + {::bmh::layout::LeagueSizes, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation258, {}}, + {::bmh::layout::LeaguePairings_LeaguePairingsConstants_RuntimeField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation259, {}}, + {::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation260, {}}, + {::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField2, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation261, {}}, + {::bmh::layout::DeskDrawers_Curve_RuntimeField, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation262, {}}, + {::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation264, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation263, {}}, + {::bmh::layout::CalendarLeagueCounts, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation265, {}}, + {::bmh::layout::LeaguePairings_SelectorEvent_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation266, {}}, + {::bmh::layout::CalendarFirstLeague, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation267, {}}, + {::bmh::layout::CareerSession_FormatError_RuntimeField4, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation268, {}}, + {::bmh::layout::GermanLayoutTranslation2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation269, {}}, + {::bmh::layout::GermanLayoutTranslation3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation270, {}}, + {::bmh::layout::TeamsWithSquads, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation271, {}}, + {::bmh::layout::CareerSession_DispatchLineup_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation272, {}}, + {::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField6, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation273, {}}, + {::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation274, {}}, + {::bmh::layout::NoTeamSquadStart, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation275, {}}, + {::bmh::layout::CareerSession_DataDirectory_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation276, {}}, + {::bmh::layout::CareerSession_DataDirectory_RuntimeField2, 12, Kind::copy, ::bmh::layout::EnglishLayoutTranslation277, {}}, + {::bmh::layout::CareerSession_DataDirectory_RuntimeField3, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation278, {}}, + {::bmh::layout::CareerSession_DataDirectory_RuntimeField4, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation279, {}}, + {::bmh::layout::CupTable, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation280, {}}, + {::bmh::layout::SeasonPromotion_FormatError_RuntimeField, 26, Kind::copy, ::bmh::layout::EnglishLayoutTranslation281, {}}, + {::bmh::layout::Advertising_PatternRect_RuntimeField, 256, Kind::copy, ::bmh::layout::EnglishLayoutTranslation282, {}}, + {::bmh::layout::LiveMatchday_PatternRect_RuntimeField, 497, Kind::copy, ::bmh::layout::EnglishLayoutTranslation283, {}}, + {::bmh::layout::TextGradientMode, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation28, {}}, + {::bmh::layout::AlternateEventRoll, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation29, {}}, + {::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation30, {}}, + {::bmh::layout::CompactDialogFrame, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation31, {}}, + {::bmh::layout::CareerSession_DispatchStadium_RuntimeField, 64, Kind::copy, ::bmh::layout::EnglishLayoutTranslation32, {}}, + {::bmh::layout::OutgoingTransfer_Line_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation33, {}}, + {::bmh::layout::OriginalManagerCount, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation34, {}}, + {::bmh::layout::CoachActive, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation35, {}}, + {::bmh::layout::Career_BuildStadium_RuntimeField, 115, Kind::copy, ::bmh::layout::EnglishLayoutTranslation36, {}}, + {::bmh::layout::CareerSession_DispatchStadium_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation37, {}}, + {::bmh::layout::Career_BuildStadium_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation38, {}}, + {::bmh::layout::Career_BuildStadium_RuntimeField3, 147, Kind::copy, ::bmh::layout::EnglishLayoutTranslation39, {}}, + {::bmh::layout::TableFlags, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation40, {}}, + {::bmh::layout::TeamStatistics_Render_RuntimeField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation41, {}}, + {::bmh::layout::Savestate_Layout_ExecutableField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation42, {}}, + {::bmh::layout::Advertising_Text_RuntimeField, 210, Kind::copy, ::bmh::layout::EnglishLayoutTranslation43, {}}, + {::bmh::layout::SeriesSelector, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation74, {}}, // EN175bf: current/best streak column selectors + {::bmh::layout::WorldCupStatistics_FormatError_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation75, {}}, // EN184a8: national-badge bank segment counts + {::bmh::layout::WorldCupStatistics_FormatError_RuntimeField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation76, {}}, + {::bmh::layout::WorldCupStatistics_FormatError_RuntimeField3, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation77, {}}, + {::bmh::layout::Analytics_FormatError_RuntimeField, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation78, {}}, + {::bmh::layout::Analytics_Render_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation79, {}}, + {::bmh::layout::Analytics_Render_RuntimeField2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation80, {}}, + {::bmh::layout::Analytics_FormatError_RuntimeField2, 18, Kind::copy, ::bmh::layout::EnglishLayoutTranslation81, {}}, // graph count classes: EN pads two bytes after its y coordinates + {::bmh::layout::Analytics_Render_RuntimeField3, 16, Kind::copy, ::bmh::layout::EnglishLayoutTranslation82, {}}, + {::bmh::layout::Analytics_FormatError_RuntimeField3, 72, Kind::copy, ::bmh::layout::EnglishLayoutTranslation83, {}}, + {::bmh::layout::Analytics_FormatError_RuntimeField4, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation84, {}}, + {::bmh::layout::Opportunities_Render_RuntimeField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation85, {}}, // EN1a334 rank colours + {::bmh::layout::Opportunities_Render_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation86, {}}, + {::bmh::layout::Opportunities_Render_RuntimeField3, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation87, {}}, + {::bmh::layout::Opportunities_FormatError_RuntimeField, 18, Kind::copy, ::bmh::layout::EnglishLayoutTranslation88, {}}, // EN1a7d9: nine left/right/top/bottom cells; EN pads each table + {::bmh::layout::Opportunities_FormatError_RuntimeField2, 18, Kind::copy, ::bmh::layout::EnglishLayoutTranslation89, {}}, + {::bmh::layout::Opportunities_FormatError_RuntimeField3, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation90, {}}, + {::bmh::layout::Opportunities_StatisticsWindow_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation91, {}}, + {::bmh::layout::Advertising_Text_RuntimeField2, 33, Kind::copy, ::bmh::layout::EnglishLayoutTranslation92, {}}, + {::bmh::layout::CupDraw_GroupMarker_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation, {}}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation2, {}}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation3, {}}, + {::bmh::layout::Career_CompetitionPointers_RuntimeField4, 5, Kind::keep, 0, {0x00,0x06,0x0c,0x0e,0x0f}}, + {::bmh::layout::Career_CompetitionPointers_RuntimeField5, 5, Kind::keep, 0, {0x00,0x04,0x08,0x0c,0x0e}}, + {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation4, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation150, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField2, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation151, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField3, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation152, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField4, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation153, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField5, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation154, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField6, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation155, {}}, + {::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation156, {}}, + {::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField7, 10, Kind::copy, ::bmh::layout::EnglishLayoutTranslation157, {}}, + {::bmh::layout::Pitch_Render_RuntimeField, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation163, {}}, + {::bmh::layout::SeasonEntrants_FormatError_ExecutableField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation176, {}}, + {::bmh::layout::SeasonEntrants_FormatError_ExecutableField2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation177, {}}, + {::bmh::layout::SeasonEntrants_FormatError_ExecutableField3, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation178, {}}, + {::bmh::layout::SeasonEntrants_FormatError_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation179, {}}, + {::bmh::layout::SeasonEntrants_FormatError_TextPointer, 9, Kind::keep, 0, {0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x01}}, + {::bmh::layout::LiveMatchday_Render_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation180, {}}, + {::bmh::layout::LiveMatchday_Render_RuntimeField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation181, {}}, + {::bmh::layout::LiveMatchday_Render_RuntimeField3, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation182, {}}, + {::bmh::layout::IncomingTransfer_OutcomeFrameAt_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation120, {}}, + {::bmh::layout::IncomingTransfer_RenderAtElapsed_RuntimeField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation122, {}}, + {::bmh::layout::CareerSession_FormatError_RuntimeField5, 20, Kind::keep, 0, {0x14,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x0f,0x00,0x00,0x00}}, + {::bmh::layout::Stadium_Out_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation143, {}}, + {::bmh::layout::Stadium_Out_RuntimeField2, 30, Kind::copy, ::bmh::layout::EnglishLayoutTranslation144, {}}, + {::bmh::layout::CareerSession_Invalid_RuntimeField, 11, Kind::copy, ::bmh::layout::EnglishLayoutTranslation145, {}}, + {::bmh::layout::Contracts_Out_TextPointer2, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation301, {}}, + {::bmh::layout::PlayerCard_PlayerCardMarketValue_RuntimeField, 10, Kind::copy, ::bmh::layout::EnglishLayoutTranslation304, {}}, + {::bmh::layout::ClubPlayerDetail_Copy_RuntimeField, 6, Kind::keep, 0, {0x56,0x56,0x76,0x76,0x9e,0x9e}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation307, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation308, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField3, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation309, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField4, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation310, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField5, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation311, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField6, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation312, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField7, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation313, {}}, + {::bmh::layout::MailboxScreen_Click_RuntimeField8, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation314, {}}, + {::bmh::layout::MailboxScreen_Render_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation315, {}}, + {::bmh::layout::MailboxScreen_Render_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation316, {}}, + {::bmh::layout::MailboxScreen_Render_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation317, {}}, + {::bmh::layout::MailboxScreen_Render_RuntimeField4, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation318, {}}, + {::bmh::layout::ProcessTimer_FormatError_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation284, {}}, + {::bmh::layout::Advertising_Button_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation299, {}}, + {::bmh::layout::Training_Render_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation183, {}}, + {::bmh::layout::Training_Render_TextPointer, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation184, {}}, + {::bmh::layout::Training_Render_TextPointer2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation185, {}}, + {::bmh::layout::Training_Click_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation186, {}}, + {::bmh::layout::Training_Click_RuntimeField2, 8, Kind::keep, 0, {0x61,0x00,0x9a,0x00,0x24,0x01,0x08,0x01}}, + {::bmh::layout::Training_Click_RuntimeField3, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation187, {}}, + {::bmh::layout::Training_Click_RuntimeField4, 4, Kind::keep, 0, {0xac,0xac,0xd7,0xd7}}, + {::bmh::layout::Training_Click_RuntimeField5, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation188, {}}, + {::bmh::layout::Training_Click_RuntimeField6, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation189, {}}, + {::bmh::layout::Training_Click_RuntimeField7, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation190, {}}, + {::bmh::layout::Training_Click_RuntimeField8, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation191, {}}, + {::bmh::layout::Training_Click_RuntimeField9, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation192, {}}, + {::bmh::layout::Advertising_Click_RuntimeField, 48, Kind::copy, ::bmh::layout::EnglishLayoutTranslation194, {}}, + {::bmh::layout::Advertising_Click_RuntimeField2, 24, Kind::copy, ::bmh::layout::EnglishLayoutTranslation195, {}}, + {::bmh::layout::GameEndAlternate_FormatError_ExecutableField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation196, {}}, + {::bmh::layout::TrainingCamp_ResortDetails_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation197, {}}, + {::bmh::layout::TrainingCamp_FocusControls_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation198, {}}, + {::bmh::layout::TrainingCamp_Click_RuntimeField, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation199, {}}, + {::bmh::layout::TrainingCamp_Click_RuntimeField2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation200, {}}, + {::bmh::layout::TrainingCamp_FocusControls_RuntimeField2, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation201, {}}, + {::bmh::layout::TrainingCamp_FocusControls_TextPointer, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation202, {}}, + {::bmh::layout::Bank_FinishCredit_RuntimeField, 16, Kind::copy, ::bmh::layout::EnglishLayoutTranslation206, {}}, + {::bmh::layout::Bank_FinishCredit_RuntimeField2, 16, Kind::copy, ::bmh::layout::EnglishLayoutTranslation207, {}}, + {::bmh::layout::Bank_FinishCredit_RuntimeField3, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation208, {}}, + {::bmh::layout::Bank_FinishCredit_RuntimeField4, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation209, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation210, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField2, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation211, {}}, + {::bmh::layout::Bank_OriginalToUtf8_RuntimeField2, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation212, {}}, + {::bmh::layout::Bank_OriginalToUtf8_RuntimeField3, 15, Kind::copy, ::bmh::layout::EnglishLayoutTranslation213, {}}, + {::bmh::layout::Bank_OriginalToUtf8_RuntimeField4, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation214, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField14, 52, Kind::copy, ::bmh::layout::EnglishLayoutTranslation215, {}}, + {::bmh::layout::BankCredit_BankCreditContext_RuntimeField3, 49, Kind::copy, ::bmh::layout::EnglishLayoutTranslation220, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField15, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation221, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField16, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation222, {}}, + {::bmh::layout::Bank_FormatError_RuntimeField17, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation223, {}}, + {::bmh::layout::LeaguePairings_Fill_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation93, {}}, + {::bmh::layout::LeaguePairings_Fill_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation94, {}}, + {::bmh::layout::CareerSession_DispatchLeagueTableControl_RuntimeField, 10, Kind::copy, ::bmh::layout::EnglishLayoutTranslation95, {}}, + {::bmh::layout::LeaguePairings_SelectorEvent_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation107, {}}, + {::bmh::layout::LeaguePairings_SelectorEvent_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation108, {}}, + {::bmh::layout::LeaguePairings_Selector_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation113, {}}, + {::bmh::layout::LeaguePairings_Selector_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation114, {}}, + {::bmh::layout::LeaguePairings_Selector_RuntimeField3, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation115, {}}, + {::bmh::layout::LeaguePairings_Selector_RuntimeField4, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation116, {}}, + {::bmh::layout::Strengths_PointerDown_RuntimeField, 9, Kind::copy, ::bmh::layout::EnglishLayoutTranslation117, {}}, + {::bmh::layout::Strengths_Fill_RuntimeField3, 16, Kind::copy, ::bmh::layout::EnglishLayoutTranslation119, {}}, + {::bmh::layout::Settings_Letter_TextPointer, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation285, {}}, + {::bmh::layout::Settings_ProjectSettingsAvailability_RuntimeField, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation286, {}}, + {::bmh::layout::Settings_ProjectSettingsAvailability_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation287, {}}, + {::bmh::layout::Settings_ProjectSettingsAvailability_RuntimeField3, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation288, {}}, + {::bmh::layout::Settings_ProjectSettingsAvailability_RuntimeField4, 57, Kind::copy, ::bmh::layout::EnglishLayoutTranslation289, {}}, + {::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField, 27, Kind::copy, ::bmh::layout::EnglishLayoutTranslation290, {}}, // Sportschau rating tables (added by hand, see manual.txt) + {::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField7, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation291, {}}, // Sportschau award ends + timeline (EN: one padding byte more) + {::bmh::layout::Setup_FormatError_RuntimeField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation9, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField2, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation10, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField3, 16, Kind::copy, ::bmh::layout::EnglishLayoutTranslation11, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField4, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation12, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField5, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation13, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField6, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation14, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField7, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation15, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField8, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation16, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField9, 3, Kind::copy, ::bmh::layout::EnglishLayoutTranslation17, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField10, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation18, {}}, + {::bmh::layout::Setup_FormatError_RuntimeField11, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation19, {}}, + {::bmh::layout::BalancePlan_DrawRows_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation20, {}}, + {::bmh::layout::BalancePlan_DrawRows_RuntimeField2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation21, {}}, + {::bmh::layout::BalancePlan_DrawRows_TextPointer2, 6, Kind::copy, ::bmh::layout::EnglishLayoutTranslation22, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField2, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation23, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField3, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation24, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField4, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation25, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField5, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation26, {}}, + {::bmh::layout::Manager_FormatError_RuntimeField6, 23, Kind::copy, ::bmh::layout::EnglishLayoutTranslation27, {}}, + {::bmh::layout::Advertising_FormatError_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation124, {}}, + {::bmh::layout::Advertising_FormatError_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation125, {}}, + {::bmh::layout::Advertising_FormatError_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation126, {}}, + {::bmh::layout::Advertising_FormatError_RuntimeField4, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation127, {}}, + {::bmh::layout::Advertising_Click_RuntimeField3, 28, Kind::copy, ::bmh::layout::EnglishLayoutTranslation131, {}}, + {::bmh::layout::Advertising_Render_RuntimeField, 12, Kind::copy, ::bmh::layout::EnglishLayoutTranslation132, {}}, + {::bmh::layout::Advertising_Click_RuntimeField4, 28, Kind::copy, ::bmh::layout::EnglishLayoutTranslation133, {}}, + {::bmh::layout::Advertising_Render_RuntimeField2, 12, Kind::copy, ::bmh::layout::EnglishLayoutTranslation134, {}}, + {::bmh::layout::Advertising_Click_RuntimeField5, 28, Kind::copy, ::bmh::layout::EnglishLayoutTranslation135, {}}, + {::bmh::layout::Advertising_Render_RuntimeField3, 12, Kind::copy, ::bmh::layout::EnglishLayoutTranslation136, {}}, + {::bmh::layout::Advertising_Click_RuntimeField6, 28, Kind::copy, ::bmh::layout::EnglishLayoutTranslation137, {}}, + {::bmh::layout::Advertising_Render_RuntimeField4, 12, Kind::copy, ::bmh::layout::EnglishLayoutTranslation138, {}}, + {::bmh::layout::Advertising_Render_RuntimeField5, 5, Kind::copy, ::bmh::layout::EnglishLayoutTranslation139, {}}, + {::bmh::layout::Advertising_Render_RuntimeField6, 7, Kind::copy, ::bmh::layout::EnglishLayoutTranslation140, {}}, + {::bmh::layout::ForeignPlayerLimitEnabled, 128, Kind::copy, ::bmh::layout::EnglishLayoutTranslation292, {}}, + {::bmh::layout::ClubInfo_Raw_RuntimeField, 1, Kind::keep, 0, {0x01}}, + {::bmh::layout::ClubInfo_Raw_RuntimeField2, 96, Kind::copy, ::bmh::layout::EnglishLayoutTranslation293, {}}, + {::bmh::layout::Desktop_Key_RuntimeField, 30, Kind::copy, ::bmh::layout::EnglishLayoutTranslation294, {}}, + {::bmh::layout::ClubInfo_Raw_RuntimeField3, 159, Kind::copy, ::bmh::layout::EnglishLayoutTranslation295, {}}, + {::bmh::layout::MatchEventsDisabled, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation296, {}}, + {::bmh::layout::CareerSession_FormatError_RuntimeField7, 2, Kind::copy, ::bmh::layout::EnglishLayoutTranslation297, {}}, + {::bmh::layout::LiveMatchday_Render_ExecutableField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation298, {}}, + {::bmh::layout::CupDraw_FormatError_ExecutableField3, 36, Kind::copy, ::bmh::layout::EnglishLayoutTranslation45, {}}, + {::bmh::layout::Career_BuildStadium_RuntimeField4, 8, Kind::copy, ::bmh::layout::EnglishLayoutTranslation7, {}}, + {::bmh::layout::Career_CareerAddManager_ExecutableField, 4, Kind::copy, ::bmh::layout::EnglishLayoutTranslation8, {}}, + {::bmh::layout::TeamStatistics_Render_RuntimeField2, 35, Kind::copy, ::bmh::layout::EnglishLayoutTranslation71, {}}, + {::bmh::layout::Desktop_Copy_TextPointer, 1, Kind::keep, 0, {0xfb}}, + {::bmh::layout::Desktop_Copy_TextPointer2, 1, Kind::copy, ::bmh::layout::EnglishLayoutTranslation73, {}}, diff --git a/src/launch/game_data.cpp b/src/launch/game_data.cpp new file mode 100644 index 0000000..199b631 --- /dev/null +++ b/src/launch/game_data.cpp @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "launch/game_data.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "formats/le.hpp" +#include "formats/m3d.hpp" +#include "formats/textd.hpp" +#include "launch/archive.hpp" +#include "launch/fltd.hpp" + +namespace fs = std::filesystem; + +namespace bmh::launch { + +namespace { + +std::string upper(std::string s) { + for (char& c : s) c = char(std::toupper(static_cast(c))); + return s; +} + +// The data files every version has (the German editions and the English one share the +// pictures, fonts and sounds; checked against the CD, the nine edition packages and FTL). +constexpr int kPictures[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 69, 70, 74, 128, 129, 131, 132, 133, 134, 135, 136, 137, 138, 139}; +constexpr int kBadges[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 17, 18, 19, 20, 44, 45, 46, 47, 48, 49, 50, 51, 52}; + +struct Required { + const char* name; + uint64_t size; // 0: any size above zero +}; +constexpr Required kCommon[] = {{"M3.DAT", 1408}, {"M3.MEN", 864}, {"M3PC.COL", 768}}; + +// Game EXEs by family. The German ones all have 602,527 bytes; the hashes differ between +// the editions, so only the size is required. +struct Family { + GameFamily family; + const char* exe; + uint64_t exe_size; + const char* texts; + const char* database; +}; +constexpr Family kFamilies[] = { + {GameFamily::german, "BMH.EXE", 602527, "TEXTD.BLK", "M3D.MAN"}, + {GameFamily::english, "FLTD.EXE", 507925, "TEXTE.BLK", "M3E.MAN"}, + {GameFamily::disk1994, "M3.EXE", 0, "", "M3PC.MAN"}, +}; + +std::optional family_of_exe(const std::string& file_name) { + const std::string u = upper(file_name); + for (const Family& f : kFamilies) + if (u == f.exe) return f; + return std::nullopt; +} + +// Every game EXE directly in `directory`. +std::vector> game_exes(const fs::path& directory) { + std::vector> out; + std::error_code ec; + for (const auto& e : fs::directory_iterator(directory, ec)) { + if (!e.is_regular_file(ec)) continue; + if (auto f = family_of_exe(path_to_utf8(e.path().filename()))) out.emplace_back(*f, e.path()); + } + return out; +} + +void require(GameCheck& c, const fs::path& dir, const std::string& name, uint64_t size, const std::string& shown) { + const auto p = find_file(dir, name); + if (!p) { + c.problems.push_back(shown + " is missing"); + return; + } + std::error_code ec; + const uint64_t actual = fs::file_size(*p, ec); + if (ec || actual == 0) c.problems.push_back(shown + " is empty or unreadable"); + else if (size != 0 && actual != size) + c.problems.push_back(shown + " has " + std::to_string(actual) + " bytes instead of " + std::to_string(size)); +} + +// The shared picture/font/sound files of the sub directories KB, W, F and S. +void require_media(GameCheck& c) { + const auto sub = [&](const char* name) -> std::optional { + auto p = find_file(c.directory, name); + if (!p || !fs::is_directory(*p)) { + c.problems.push_back(std::string("the directory ") + name + " is missing"); + return std::nullopt; + } + return p; + }; + // (a long list of missing files says less than the count and the first ones) + const auto files = [&](const fs::path& dir, const char* shown, const std::vector& names) { + std::vector missing; + for (const auto& n : names) + if (!find_file(dir, n)) missing.push_back(n); + if (missing.empty()) return; + std::string text = std::string(shown) + ": " + std::to_string(missing.size()) + " file(s) missing ("; + for (size_t i = 0; i < missing.size() && i < 5; ++i) text += (i ? ", " : "") + missing[i]; + c.problems.push_back(text + (missing.size() > 5 ? ", ...)" : ")")); + }; + std::vector names; + if (auto kb = sub("KB")) { + for (int n : kPictures) names.push_back(std::to_string(n) + ".VGA"); + files(*kb, "KB", names); + } + names.clear(); + if (auto w = sub("W")) { + for (int n : kBadges) names.push_back(std::to_string(n) + ".VGA"); + files(*w, "W", names); + } + if (auto f = sub("F")) files(*f, "F", {"BMH2.FNT", "BMH3.FNT"}); + if (auto s = sub("S")) files(*s, "S", {"2000", "2001", "2002", "2003"}); +} + +// A readable title from the text block (ISO 646-DE: the brackets are umlauts). +std::string text_title(const std::string& raw) { + std::string out; + for (unsigned char ch : raw) { + switch (ch) { + case '[': out += "\xC3\x84"; break; + case '\\': out += "\xC3\x96"; break; + case ']': out += "\xC3\x9C"; break; + case '{': out += "\xC3\xA4"; break; + case '|': out += "\xC3\xB6"; break; + case '}': out += "\xC3\xBC"; break; + case '~': out += "\xC3\x9F"; break; + default: out += ch >= 0x20 && ch < 0x7F ? char(ch) : '?'; + } + } + return out; +} + +void check_german(GameCheck& c) { + // (a translated English game has BMH.exe in the OpenBMH image format, launch/fltd.hpp) + bool image = false; + if (const auto exe = find_file(c.directory, "BMH.EXE")) { + std::ifstream in(*exe, std::ios::binary); + char head[13] = {}; + in.read(head, sizeof head); + image = std::string(head, sizeof head) == "OPENBMH-IMAGE"; + } + require(c, c.directory, "BMH.EXE", image ? 0 : 602527, "BMH.EXE"); + require(c, c.directory, "TEXTD.BLK", 0, "TEXTD.BLK"); + require(c, c.directory, "M3D.MAN", 0, "M3D.MAN"); + for (const Required& r : kCommon) require(c, c.directory, r.name, r.size, r.name); + require_media(c); + if (!c.problems.empty()) return; + // the files must also load: the engine reads tables from the EXE, the texts and the + // database of clubs and players + try { + load_le(*find_file(c.directory, "BMH.EXE")); + } catch (const std::exception& e) { + c.problems.push_back(std::string("BMH.EXE cannot be read: ") + e.what()); + } + try { + const TextDb texts = load_textd(*find_file(c.directory, "TEXTD.BLK")); + // the supported rule profile editions greet with their title as the first mailbox message (text 1001); + // the CD version has another greeting there + c.title = "Bundesliga Manager Hattrick"; + if (texts.strings.size() > 1001 && texts.strings[1001].rfind("Bundesliga Manager", 0) == 0) + c.title = text_title(texts.strings[1001]); + } catch (const std::exception& e) { + c.problems.push_back(std::string("TEXTD.BLK cannot be read: ") + e.what()); + } + try { + load_database(*find_file(c.directory, "M3D.MAN")); + } catch (const std::exception& e) { + c.problems.push_back(std::string("M3D.MAN cannot be read: ") + e.what()); + } +} + +void check_english(GameCheck& c) { + require(c, c.directory, "FLTD.EXE", 507925, "FLTD.EXE"); + require(c, c.directory, "TEXTE.BLK", 0, "TEXTE.BLK"); + require(c, c.directory, "M3E.MAN", 0, "M3E.MAN"); + for (const Required& r : kCommon) require(c, c.directory, r.name, r.size, r.name); + require_media(c); + c.title = "Football Limited (English)"; +} + +// A cheap content hash (FNV-1a, 64 bit) that names the cache folder of an archive. +std::string content_hash(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + uint64_t h = 0xcbf29ce484222325ull; + char buf[1 << 16]; + while (in) { + in.read(buf, sizeof buf); + for (std::streamsize i = 0; i < in.gcount(); ++i) h = (h ^ uint8_t(buf[i])) * 0x100000001b3ull; + } + char text[17]; + std::snprintf(text, sizeof text, "%016llx", static_cast(h)); + return text; +} + +// Whether an archive file belongs to the game data: the original file kinds, the sounds +// (S\2000...) and savegames. Pictures, manuals and other fan extras are left out of the +// cache (their long names also overflow the 260 characters of a Windows path). +bool is_game_file(const std::string& relative) { + const std::string u = upper(relative); + const std::string base = u.substr(u.find_last_of('/') + 1); + if (u.rfind("S/", 0) == 0 && base.find('.') == std::string::npos) return true; // sounds + const size_t dot = base.find_last_of('.'); + if (dot == std::string::npos) return false; + const std::string ext = base.substr(dot + 1); + for (const char* e : {"EXE", "BLK", "MAN", "DAT", "MEN", "COL", "VGA", "FNT", "LBM", "EIN", "CFG", "FBM", "WAP"}) + if (ext == e) return true; + return false; +} + +bool is_archive_name(const std::string& name) { + const std::string u = upper(name); + for (const char* ext : {".ZIP", ".7Z", ".ARJ", ".RAR", ".LZH", ".TAR", ".GZ"}) + if (u.size() > std::strlen(ext) && u.compare(u.size() - std::strlen(ext), std::string::npos, ext) == 0) return true; + return false; +} + +// Unpacks the one game of an archive into the cache (or finds it there). +ResolvedGame unpack(const fs::path& file, const fs::path& cache) { + ResolvedGame r; + const ArchiveFormat format = archive_format(file); + if (format == ArchiveFormat::arj) { + r.error = "This is an ARJ archive (the installer format of the 1994 floppy disks). OpenBMH cannot read it; " + "please unpack the installed game."; + return r; + } + if (format == ArchiveFormat::rar) { + r.error = "RAR archives are not supported; please use ZIP or 7z."; + return r; + } + try { + Archive archive = Archive::open(file); + const auto& entries = archive.entries(); + // exactly one game EXE; its directory is the game's root in the archive + std::vector exes; + bool nested = false, installer = false; + for (size_t i = 0; i < entries.size(); ++i) { + if (entries[i].directory) continue; + const std::string& n = entries[i].name; + const std::string base = n.substr(n.find_last_of('/') + 1); + if (family_of_exe(base)) exes.push_back(i); + if (is_archive_name(base)) nested = true; + if (upper(base) == "INSTALL.EXE") installer = true; + } + if (exes.empty()) { + if (installer) r.error = "The archive holds an installer (INSTALL.EXE), not an installed game."; + else if (nested) r.error = "The archive contains further archives (a box with several editions). " + "Please choose the archive of one edition."; + else r.error = "The archive contains no BMH.EXE or FLTD.EXE."; + return r; + } + if (exes.size() > 1) { + r.error = "The archive contains " + std::to_string(exes.size()) + + " games. Please use an archive with exactly one game."; + return r; + } + const std::string& exe_name = entries[exes[0]].name; + const std::string root = exe_name.substr(0, exe_name.find_last_of('/') + 1); // "" or "dir/.../" + + const fs::path target = cache / content_hash(file); + const fs::path marker = target / ".openbmh-unpacked"; + std::error_code ec; + if (!fs::exists(marker, ec)) { + const fs::path temp = cache / (content_hash(file) + ".partial"); + fs::remove_all(temp, ec); + fs::create_directories(temp); + uint64_t total = 0; + for (size_t i = 0; i < entries.size(); ++i) { + const ArchiveEntry& e = entries[i]; + if (e.name.compare(0, root.size(), root) != 0 || e.name.size() == root.size()) continue; + const std::string rel = e.name.substr(root.size()); + // no absolute paths and no way out of the target directory + const fs::path relative = path_from_utf8(rel); + bool safe = !relative.is_absolute() && !relative.has_root_name(); + for (const auto& part : relative) safe = safe && part != ".."; + if (!safe) throw ArchiveError("unsafe path in the archive: " + e.name); + if (!e.directory && !is_game_file(rel)) continue; + total += e.size; + if (total > 256ull * 1024 * 1024) throw ArchiveError("the game in the archive is too large"); + if (e.directory) { + fs::create_directories(temp / relative); + continue; + } + fs::create_directories((temp / relative).parent_path()); + const std::vector bytes = archive.read(i); + std::ofstream out(temp / relative, std::ios::binary); + out.write(reinterpret_cast(bytes.data()), std::streamsize(bytes.size())); + if (!out) throw ArchiveError("cannot write " + path_to_utf8(temp / relative)); + } + std::ofstream(temp / ".openbmh-unpacked") << path_to_utf8(file) << "\n"; + fs::remove_all(target, ec); + fs::rename(temp, target); + } + r.check = check_game_directory(target); + r.unpacked = true; + } catch (const std::exception& e) { + r.error = std::string("The archive cannot be used: ") + e.what(); + } + return r; +} + +ResolvedGame resolve_game_unchecked(const fs::path& input, const fs::path& cache); + +} // namespace + +std::optional find_file(const fs::path& directory, const std::string& name) { + std::error_code ec; + const fs::path exact = directory / path_from_utf8(name); + if (fs::exists(exact, ec)) return exact; + const std::string wanted = upper(name); + for (const auto& e : fs::directory_iterator(directory, ec)) + if (upper(path_to_utf8(e.path().filename())) == wanted) return e.path(); + return std::nullopt; +} + +GameCheck check_game_directory(const fs::path& path) { + GameCheck c; + std::error_code ec; + fs::path dir = fs::is_directory(path, ec) ? path : path.parent_path(); + auto exes = game_exes(dir); + if (exes.empty()) { + // an edition folder with the game one level below (e.g. "BMH 2026-27 supported rule profile\BMH") + std::vector candidates; + for (const auto& e : fs::directory_iterator(dir, ec)) + if (e.is_directory(ec) && !game_exes(e.path()).empty()) candidates.push_back(e.path()); + if (candidates.size() == 1) { + dir = candidates[0]; + exes = game_exes(dir); + } + } + c.directory = dir; + if (exes.empty()) { + c.problems.push_back("no BMH.EXE or FLTD.EXE in " + path_to_utf8(dir)); + return c; + } + // a named EXE decides; otherwise the German game before the English one + std::sort(exes.begin(), exes.end(), [](const auto& a, const auto& b) { return int(a.first.family) < int(b.first.family); }); + auto chosen = exes.front(); + if (!fs::is_directory(path, ec)) + for (const auto& e : exes) + if (upper(path_to_utf8(e.second.filename())) == upper(path_to_utf8(path.filename()))) chosen = e; + c.family = chosen.first.family; + c.exe = chosen.second; + switch (c.family) { + case GameFamily::german: + check_german(c); + c.playable = c.problems.empty(); + break; + case GameFamily::english: + check_english(c); + // complete English data is translated for the engine when the game is resolved + // (resolve_game -> prepare_english_game); the check itself stays on the original + break; + case GameFamily::disk1994: + c.title = "Bundesliga Manager Hattrick (1994 floppy version)"; + c.unsupported = "The 1994 floppy version (M3.EXE) is not supported; please use the CD version or a later edition."; + break; + case GameFamily::unknown: break; + } + return c; +} + +ResolvedGame resolve_game(const fs::path& input, const fs::path& cache) { + try { + ResolvedGame game = resolve_game_unchecked(input, cache); + // The English Football Limited runs on the same engine through a German-layout data + // directory, built once in the cache (launch/fltd.hpp); its name follows FLTD.EXE. + if (game.error.empty() && game.check.family == GameFamily::english && game.check.problems.empty()) { + const fs::path prepared = cache / ("en-" + content_hash(game.check.exe)); + const fs::path marker = prepared / ".openbmh-english"; + // the version of the translation (launch/fltd.cpp, fltd_map.inc): a cache built + // by another version is built again + constexpr const char* kTranslation = "english translation 12"; // 12: contract warning ContractExpiryWarningText; 11: statistics windows, graph labels/count classes, streaks and national-badge banks + std::string built; + { + std::ifstream in(marker); + std::getline(in, built); + } + std::error_code ec; + if (built != kTranslation) { + fs::remove_all(prepared, ec); + std::string error; + if (!prepare_english_game(game.check.directory, prepared, error)) { + game.error = "The English version cannot be prepared: " + error; + return game; + } + std::ofstream(marker) << kTranslation << "\n" << path_to_utf8(game.check.directory) << "\n"; + } + game.check.directory = prepared; + game.check.playable = true; + game.unpacked = true; + } + return game; + } catch (const std::exception& e) { + // (file system errors, names that cannot be converted) + ResolvedGame r; + r.error = std::string("The game cannot be opened: ") + e.what(); + return r; + } +} + +namespace { +ResolvedGame resolve_game_unchecked(const fs::path& input, const fs::path& cache) { + std::error_code ec; + if (!fs::exists(input, ec)) { + ResolvedGame r; + r.error = "not found: " + path_to_utf8(input); + return r; + } + if (fs::is_directory(input, ec)) return {check_game_directory(input), {}, false}; + if (family_of_exe(path_to_utf8(input.filename()))) return {check_game_directory(input), {}, false}; + if (archive_format(input) != ArchiveFormat::none) return unpack(input, cache); + ResolvedGame r; + r.error = path_to_utf8(input.filename()) + " is neither a game directory, BMH.EXE/FLTD.EXE nor a ZIP/7z archive."; + return r; +} +} // namespace + +fs::path default_cache_directory() { + const auto env = [](const char* name) -> std::optional { +#ifdef _WIN32 + // (the wide environment: the profile path may hold characters outside the code page) + std::wstring wname(name, name + std::strlen(name)); + wchar_t* v = nullptr; + size_t length = 0; + if (_wdupenv_s(&v, &length, wname.c_str()) == 0 && v) { + const fs::path value = *v ? fs::path(v) : fs::path(); + std::free(v); + if (!value.empty()) return value; + } +#else + if (const char* v = std::getenv(name); v && *v) return fs::path(v); +#endif + return std::nullopt; + }; +#if defined(_WIN32) + if (auto base = env("LOCALAPPDATA")) return *base / "OpenBMH" / "games"; + return fs::temp_directory_path() / "OpenBMH" / "games"; +#elif defined(__APPLE__) + if (auto home = env("HOME")) return *home / "Library" / "Application Support" / "OpenBMH" / "games"; + return fs::temp_directory_path() / "OpenBMH" / "games"; +#else + if (auto data = env("XDG_DATA_HOME")) return *data / "openbmh" / "games"; + if (auto home = env("HOME")) return *home / ".local" / "share" / "openbmh" / "games"; + return fs::temp_directory_path() / "openbmh" / "games"; +#endif +} + +std::string describe(const ResolvedGame& game) { + if (!game.error.empty()) return game.error; + const GameCheck& c = game.check; + std::string text; + if (!c.title.empty()) text += c.title + "\n"; + text += path_to_utf8(c.directory) + "\n"; + for (const auto& p : c.problems) text += "- " + p + "\n"; + if (!c.unsupported.empty()) text += c.unsupported + "\n"; + if (c.playable) text += "The game data is complete.\n"; + return text; +} + +} // namespace bmh::launch diff --git a/src/launch/game_data.hpp b/src/launch/game_data.hpp new file mode 100644 index 0000000..51d9f89 --- /dev/null +++ b/src/launch/game_data.hpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// Finding and checking the original game data OpenBMH runs on. +// +// The player names one of: an installed game directory, the game's EXE in it (BMH.EXE of +// the German versions, FLTD.EXE of the English "Football Limited"), or a ZIP/7z archive +// holding exactly one such game. An archive is unpacked once into the cache directory (a +// folder per archive content hash) and reused on the next start. +// +// OpenBMH has one game and match engine (the supported rule profile rules); the original files are only +// data. The check therefore asks whether the data is complete and readable, not which +// edition it is. Fan extras next to the files (pictures, manuals) are ignored. + +#include +#include +#include +#include +#include + +namespace bmh::launch { + +enum class GameFamily { + unknown, + german, // BMH.EXE + TEXTD.BLK + M3D.MAN (CD 1996, CLASSIC/UNLIMITED/supported rule profile editions) + english, // FLTD.EXE + TEXTE.BLK + M3E.MAN (Football Limited) + disk1994, // M3.EXE + M3PC.* (the 1994 floppy version): recognised, not supported +}; + +struct GameCheck { + GameFamily family = GameFamily::unknown; + std::filesystem::path directory; // the game directory (where the EXE is) + std::filesystem::path exe; // the EXE as found (its case may differ) + std::string title; // e.g. "Bundesliga Manager Hattrick 2026-27 (supported rule profile)" + std::vector problems; // missing or unreadable files; empty = data complete + // Data complete and the engine can run it. False also for complete data the engine does + // not run yet (`unsupported` says why). + bool playable = false; + std::string unsupported; +}; + +// The file `name` in `directory`, matched without regard to case (the packages mix +// "BMH.exe", "BMH.EXE" and "20.vga"); nullopt if there is none. +std::optional find_file(const std::filesystem::path& directory, const std::string& name); + +// Checks an installed game directory (or the directory of a named EXE). A directory without +// a game EXE but with exactly one sub directory holding one (an edition folder with BMH\ +// inside) is followed. +GameCheck check_game_directory(const std::filesystem::path& path); + +struct ResolvedGame { + GameCheck check; + std::string error; // why no game directory could be found (empty: check is valid) + bool unpacked = false; // the directory comes from the archive cache +}; + +// Resolves what the player gave: a directory, an EXE or an archive. `cache` is where +// archives are unpacked (see default_cache_directory()). +ResolvedGame resolve_game(const std::filesystem::path& input, const std::filesystem::path& cache); + +// The per-user cache for unpacked archives: %LOCALAPPDATA%\OpenBMH\games, +// ~/Library/Application Support/OpenBMH/games, $XDG_DATA_HOME/openbmh/games. +std::filesystem::path default_cache_directory(); + +// One line per problem, for message boxes and the console. +std::string describe(const ResolvedGame& game); + +} // namespace bmh::launch diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..c62fb9b --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-only +// OpenBMH - first milestone: asset viewer. +// Shows the original .VGA screens with the original palette and font. +// openbmh --data +// Left/Right: previous/next image, Esc: quit +// openbmh --data --dump [--image N] render one screen to a file, no window +#include + +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/m3d.hpp" +#include "formats/palette.hpp" +#include "formats/vga.hpp" + +namespace fs = std::filesystem; +using namespace bmh; + +constexpr int SCREEN_W = 320, SCREEN_H = 240, SCALE = 3; + +static std::vector find_images(const fs::path& data) { + std::vector> found; + for (const auto& e : fs::directory_iterator(data / "KB")) { + std::string stem = e.path().stem().string(), ext = e.path().extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::toupper); + if (ext == ".VGA" && !stem.empty() && stem.find_first_not_of("0123456789") == std::string::npos) + found.emplace_back(std::stoi(stem), e.path()); + } + std::sort(found.begin(), found.end()); + std::vector out; + for (auto& f : found) out.push_back(f.second); + return out; +} + +static Image render_screen(const fs::path& image, const Font& font, const Palette& pal, const std::string& club) { + Image screen(SCREEN_W, SCREEN_H, 0); + Image img = load_vga(image); + screen.blit(img, (SCREEN_W - img.width) / 2, (SCREEN_H - img.height) / 2); + std::string caption = + image.filename().string() + " " + std::to_string(img.width) + "x" + std::to_string(img.height) + " " + club; + font.draw(screen, 3, 2, caption, pal.nearest(0, 0, 0)); // shadow + font.draw(screen, 2, 1, caption, pal.nearest(255, 255, 255)); + return screen; +} + +int main(int argc, char** argv) { + fs::path data = ".", dump; + size_t current = 0; + for (int i = 1; i + 1 < argc; i++) { + std::string arg = argv[i]; + if (arg == "--data") data = argv[i + 1]; + if (arg == "--dump") dump = argv[i + 1]; + if (arg == "--image") current = std::stoul(argv[i + 1]); + } + + try { + Palette pal = load_palette(data / "M3PC.COL"); + Font font = load_font(data / "F" / "BMH2.FNT"); + Database db = load_database(data / "M3D.MAN"); + std::vector images = find_images(data); + if (images.empty()) throw FormatError("no KB\\*.VGA images found in " + data.string()); + current %= images.size(); + auto club = [&](size_t i) { return db.club_names[i % db.club_names.size()]; }; + + if (!dump.empty()) { + Image screen = render_screen(images[current], font, pal, club(current)); + SDL_Surface* s = SDL_CreateRGBSurfaceWithFormat(0, SCREEN_W, SCREEN_H, 32, SDL_PIXELFORMAT_ARGB8888); + auto* px = static_cast(s->pixels); + for (int y = 0; y < SCREEN_H; y++) + for (int x = 0; x < SCREEN_W; x++) px[y * (s->pitch / 4) + x] = pal.argb[screen.at(x, y)]; + int rc = SDL_SaveBMP(s, dump.string().c_str()); + SDL_FreeSurface(s); + if (rc != 0) throw FormatError(std::string("cannot write ") + dump.string() + ": " + SDL_GetError()); + return 0; + } + + SDL_Init(SDL_INIT_VIDEO); + SDL_Window* win = SDL_CreateWindow("OpenBMH", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_W * SCALE, + SCREEN_H * SCALE, SDL_WINDOW_RESIZABLE); + SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC); + SDL_RenderSetLogicalSize(ren, SCREEN_W, SCREEN_H); + SDL_Texture* tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_W, SCREEN_H); + + bool dirty = true, running = true; + std::vector argb(SCREEN_W * SCREEN_H); + while (running) { + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + if (ev.type == SDL_QUIT) running = false; + if (ev.type == SDL_KEYDOWN) { + switch (ev.key.keysym.sym) { + case SDLK_ESCAPE: running = false; break; + case SDLK_RIGHT: current = (current + 1) % images.size(); dirty = true; break; + case SDLK_LEFT: current = (current + images.size() - 1) % images.size(); dirty = true; break; + } + } + } + if (dirty) { + Image screen = render_screen(images[current], font, pal, club(current)); + for (size_t i = 0; i < argb.size(); i++) argb[i] = pal.argb[screen.pixels[i]]; + SDL_UpdateTexture(tex, nullptr, argb.data(), SCREEN_W * 4); + SDL_SetWindowTitle(win, ("OpenBMH - " + images[current].filename().string()).c_str()); + dirty = false; + } + SDL_RenderClear(ren); + SDL_RenderCopy(ren, tex, nullptr, nullptr); + SDL_RenderPresent(ren); + } + SDL_DestroyTexture(tex); + SDL_DestroyRenderer(ren); + SDL_DestroyWindow(win); + SDL_Quit(); + } catch (const std::exception& ex) { + std::fprintf(stderr, "error: %s\n", ex.what()); + return 1; + } + return 0; +} diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt new file mode 100644 index 0000000..df48396 --- /dev/null +++ b/src/ui/CMakeLists.txt @@ -0,0 +1,241 @@ +# SPDX-License-Identifier: GPL-3.0-only +# SDL-independent UI; shared file formats and game logic come from bmhcore. +add_library(bmhui STATIC + setup.cpp + manager.cpp + flow.cpp + desk_state.cpp + desk_drawers.cpp + desktop.cpp + preparation.cpp + preparation_flow.cpp + lineup.cpp + training.cpp + training_camp.cpp + bank.cpp + stadium.cpp + toto.cpp + transfer_market.cpp + save_load.cpp + tactics.cpp + live_intervention.cpp + live_matchday.cpp + live_set_piece.cpp + live_reality.cpp + reality_reporter.cpp + pitch.cpp + player_card.cpp + matchday_results.cpp + matchday_results_screen.cpp + league_table.cpp + league_table_range_dialog.cpp + league_pairings.cpp + friendly_match.cpp + national_friendly_ui.cpp + calendar_state.cpp + calendar.cpp + indoor_standings.cpp + strengths_state.cpp + strengths.cpp + top_scorers_state.cpp + top_scorers.cpp + desk_records.cpp + opportunities.cpp + statistics_rankings.cpp + alltime_table.cpp + world_cup_statistics.cpp + finance_totals.cpp + series_records.cpp + analytics.cpp + minute_statistics.cpp + transfer_history.cpp + other_games_state.cpp + other_games.cpp + process_timer.cpp + contracts.cpp + incoming_transfer.cpp + outgoing_transfer.cpp + balance_plan.cpp + pending_offer.cpp + settings.cpp + sprite_font.cpp + advertising.cpp + environment.cpp + achievements.cpp + mailbox_state.cpp + mailbox_screen.cpp + season_entrants.cpp + season_promotion.cpp + cup_draw.cpp + club_info.cpp + team_statistics.cpp + club_player_detail.cpp + game_end.cpp + game_end_alternate.cpp + game_end_tax_animation.cpp + sportschau.cpp) +target_link_libraries(bmhui PUBLIC bmhcore) +add_executable(openbmh_ui main.cpp) +target_link_libraries(openbmh_ui PRIVATE bmhui ${BMH_SDL_TARGET}) +add_executable(ui_setup_tests tests.cpp) +target_link_libraries(ui_setup_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_setup_tests COMMAND ui_setup_tests "${BMH_DATA}") +add_executable(ui_national_friendly_tests ../../tests/national_friendly_ui_tests.cpp) +target_link_libraries(ui_national_friendly_tests PRIVATE bmhui) +add_test(NAME ui_national_friendly_tests COMMAND ui_national_friendly_tests) +add_executable(ui_manager_tests manager_tests.cpp) +target_link_libraries(ui_manager_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_manager_tests COMMAND ui_manager_tests "${BMH_DATA}") +set(BMH_UI_REFERENCE_SAVE "" CACHE FILEPATH "Optional original LABA0012 desktop reference; never bundled") +add_executable(ui_desktop_tests desktop_tests.cpp) +target_link_libraries(ui_desktop_tests PRIVATE bmhui) +set(BMH_TEST_UI_DESKTOP_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_desktop_tests; not distributed") +bmh_add_data_test(NAME ui_desktop_tests REQUIRED_OPTIONS BMH_TEST_UI_DESKTOP_TESTS_INPUT_1 COMMAND ui_desktop_tests "${BMH_DATA}" "${BMH_UI_REFERENCE_SAVE}" + "${BMH_TEST_UI_DESKTOP_TESTS_INPUT_1}") +set(BMH_UI_PREPARATION_SAVE "" CACHE FILEPATH "Optional original LABA0020 reference after observed menu entry effects; never bundled") +foreach(menu lineup training tactics preparation pitch player_card) + add_executable(ui_${menu}_tests ${menu}_tests.cpp) + target_link_libraries(ui_${menu}_tests PRIVATE bmhui) + bmh_add_data_test(NAME ui_${menu}_tests COMMAND ui_${menu}_tests "${BMH_DATA}" "${BMH_UI_PREPARATION_SAVE}") +endforeach() +add_executable(ui_training_camp_tests training_camp_tests.cpp) +target_link_libraries(ui_training_camp_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_training_camp_tests COMMAND ui_training_camp_tests "${BMH_DATA}") +add_executable(ui_bank_tests bank_tests.cpp) +target_link_libraries(ui_bank_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_bank_tests COMMAND ui_bank_tests "${BMH_DATA}") +add_executable(ui_matchday_results_tests matchday_results_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(ui_matchday_results_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_matchday_results_tests COMMAND ui_matchday_results_tests "${BMH_DATA}") +add_executable(ui_league_table_tests league_table_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(ui_league_table_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_league_table_tests COMMAND ui_league_table_tests "${BMH_DATA}") +add_executable(ui_friendly_match_tests friendly_match_tests.cpp) +target_link_libraries(ui_friendly_match_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_friendly_match_tests COMMAND ui_friendly_match_tests "${BMH_DATA}") +add_executable(ui_contracts_tests contracts_tests.cpp) +target_link_libraries(ui_contracts_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_contracts_tests COMMAND ui_contracts_tests "${BMH_DATA}") +add_executable(ui_transfer_market_tests transfer_market_tests.cpp) +target_link_libraries(ui_transfer_market_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_transfer_market_tests COMMAND ui_transfer_market_tests "${BMH_DATA}") +add_executable(ui_incoming_transfer_tests incoming_transfer_tests.cpp) +target_link_libraries(ui_incoming_transfer_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_incoming_transfer_tests COMMAND ui_incoming_transfer_tests "${BMH_DATA}") +add_executable(ui_outgoing_transfer_tests outgoing_transfer_tests.cpp) +target_link_libraries(ui_outgoing_transfer_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_outgoing_transfer_tests COMMAND ui_outgoing_transfer_tests "${BMH_DATA}") +add_executable(ui_balance_plan_tests balance_plan_tests.cpp) +target_link_libraries(ui_balance_plan_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_balance_plan_tests COMMAND ui_balance_plan_tests "${BMH_DATA}") +add_executable(ui_live_intervention_tests live_intervention_tests.cpp) +target_link_libraries(ui_live_intervention_tests PRIVATE bmhui) +add_test(NAME ui_live_intervention_tests COMMAND ui_live_intervention_tests) +add_executable(ui_mailbox_state_tests mailbox_state_tests.cpp) +target_link_libraries(ui_mailbox_state_tests PRIVATE bmhui) +add_test(NAME ui_mailbox_state_tests COMMAND ui_mailbox_state_tests) +add_executable(ui_mailbox_screen_tests mailbox_screen_tests.cpp) +target_link_libraries(ui_mailbox_screen_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_mailbox_screen_tests COMMAND ui_mailbox_screen_tests "${BMH_DATA}") +add_executable(ui_settings_tests settings_tests.cpp) +target_link_libraries(ui_settings_tests PRIVATE bmhui) +set(BMH_UI_SETTINGS_SAVE "" CACHE FILEPATH "Optional Original settings capture save; never bundled") +bmh_add_data_test(NAME ui_settings_tests COMMAND ui_settings_tests "${BMH_DATA}" "${BMH_UI_SETTINGS_SAVE}") +add_executable(ui_advertising_tests advertising_tests.cpp ${BMH_APP_SESSION_SOURCE}) +target_link_libraries(ui_advertising_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_advertising_tests COMMAND ui_advertising_tests "${BMH_DATA}") +add_executable(ui_environment_tests environment_tests.cpp) +target_link_libraries(ui_environment_tests PRIVATE bmhui) +set(BMH_TEST_UI_ENVIRONMENT_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_environment_tests; not distributed") +bmh_add_data_test(NAME ui_environment_tests REQUIRED_OPTIONS BMH_TEST_UI_ENVIRONMENT_TESTS_INPUT_1 COMMAND ui_environment_tests "${BMH_DATA}" + "${BMH_TEST_UI_ENVIRONMENT_TESTS_INPUT_1}") +add_executable(ui_achievements_tests achievements_tests.cpp) +target_link_libraries(ui_achievements_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_achievements_tests COMMAND ui_achievements_tests "${BMH_DATA}") +add_executable(ui_sprite_font_tests sprite_font_tests.cpp) +target_link_libraries(ui_sprite_font_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_sprite_font_tests COMMAND ui_sprite_font_tests "${BMH_DATA}") +if(MSVC) + target_compile_options(bmhui PRIVATE /W4 /utf-8) + target_compile_options(openbmh_ui PRIVATE /utf-8) +else() + target_compile_options(bmhui PRIVATE -Wall -Wextra) + target_compile_options(openbmh_ui PRIVATE -Wall -Wextra) +endif() + +add_executable(ui_season_entrants_tests season_entrants_tests.cpp) +target_link_libraries(ui_season_entrants_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_season_entrants_tests COMMAND ui_season_entrants_tests "${BMH_DATA}") + +add_executable(ui_game_end_alternate_tests ../../tests/game_end_alternate_tests.cpp) +target_link_libraries(ui_game_end_alternate_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_game_end_alternate_tests COMMAND ui_game_end_alternate_tests "${BMH_DATA}") + +add_executable(ui_game_end_tax_animation_tests ../../tests/game_end_tax_animation_tests.cpp) +target_link_libraries(ui_game_end_tax_animation_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_game_end_tax_animation_tests REQUIRED_OPTIONS BMH_TEST_INPUTS REQUIRED_FILES tax-animation-script.bin COMMAND ui_game_end_tax_animation_tests "${BMH_DATA}") + +add_executable(ui_game_end_tests game_end_tests.cpp) +target_link_libraries(ui_game_end_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_game_end_tests COMMAND ui_game_end_tests "${BMH_DATA}") + +add_executable(ui_club_info_tests ../../tests/club_info_ui_tests.cpp) +target_link_libraries(ui_club_info_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_club_info_tests COMMAND ui_club_info_tests "${BMH_DATA}") + +add_executable(ui_club_player_detail_tests ../../tests/club_player_detail_ui_tests.cpp) +target_link_libraries(ui_club_player_detail_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_club_player_detail_tests COMMAND ui_club_player_detail_tests "${BMH_DATA}") + +add_executable(ui_team_statistics_tests ../../tests/team_statistics_tests.cpp) +target_link_libraries(ui_team_statistics_tests PRIVATE bmhui) +set(BMH_TEST_UI_TEAM_STATISTICS_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_team_statistics_tests; not distributed") +bmh_add_data_test(NAME ui_team_statistics_tests REQUIRED_OPTIONS BMH_TEST_UI_TEAM_STATISTICS_TESTS_INPUT_1 COMMAND ui_team_statistics_tests "${BMH_DATA}" "${BMH_TEST_UI_TEAM_STATISTICS_TESTS_INPUT_1}") + +add_executable(ui_team_statistics_source_oracle_tests ../../tests/team_statistics_source_oracle_tests.cpp) +target_link_libraries(ui_team_statistics_source_oracle_tests PRIVATE bmhui) +set(BMH_TEST_UI_TEAM_STATISTICS_SOURCE_ORACLE_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_team_statistics_source_oracle_tests; not distributed") +bmh_add_data_test(NAME ui_team_statistics_source_oracle_tests REQUIRED_OPTIONS BMH_TEST_UI_TEAM_STATISTICS_SOURCE_ORACLE_TESTS_INPUT_1 COMMAND ui_team_statistics_source_oracle_tests "${BMH_DATA}" "${BMH_TEST_UI_TEAM_STATISTICS_SOURCE_ORACLE_TESTS_INPUT_1}") + +add_executable(ui_pending_offer_tests ../../tests/pending_offer_ui_tests.cpp) +target_link_libraries(ui_pending_offer_tests PRIVATE bmhui) +set(BMH_TEST_UI_PENDING_OFFER_TESTS_INPUT_1 "" CACHE PATH "External input 1 for ui_pending_offer_tests; not distributed") +bmh_add_data_test(NAME ui_pending_offer_tests REQUIRED_OPTIONS BMH_TEST_UI_PENDING_OFFER_TESTS_INPUT_1 COMMAND ui_pending_offer_tests "${BMH_DATA}" + "${BMH_TEST_UI_PENDING_OFFER_TESTS_INPUT_1}") + +add_executable(ui_top_scorers_tests top_scorers_tests.cpp) +target_link_libraries(ui_top_scorers_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_top_scorers_tests COMMAND ui_top_scorers_tests "${BMH_DATA}") +add_executable(ui_opportunities_tests opportunities_tests.cpp) +target_link_libraries(ui_opportunities_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_opportunities_tests COMMAND ui_opportunities_tests "${BMH_DATA}") +add_executable(ui_statistics_rankings_tests statistics_rankings_tests.cpp) +target_link_libraries(ui_statistics_rankings_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_statistics_rankings_tests COMMAND ui_statistics_rankings_tests "${BMH_DATA}") +add_executable(ui_alltime_table_tests alltime_table_tests.cpp) +target_link_libraries(ui_alltime_table_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_alltime_table_tests COMMAND ui_alltime_table_tests "${BMH_DATA}") +add_executable(ui_world_cup_statistics_tests world_cup_statistics_tests.cpp) +target_link_libraries(ui_world_cup_statistics_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_world_cup_statistics_tests COMMAND ui_world_cup_statistics_tests "${BMH_DATA}") +add_executable(ui_finance_totals_tests finance_totals_tests.cpp) +target_link_libraries(ui_finance_totals_tests PRIVATE bmhui) +set(BMH_STATISTICS_FINANCE_TEST_SAVE "" CACHE FILEPATH "External save for finance totals tests") +bmh_add_data_test(NAME ui_finance_totals_tests REQUIRED_OPTIONS BMH_STATISTICS_FINANCE_TEST_SAVE + COMMAND ui_finance_totals_tests "${BMH_DATA}" "${BMH_STATISTICS_FINANCE_TEST_SAVE}") +add_executable(ui_series_records_tests series_records_tests.cpp) +target_link_libraries(ui_series_records_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_series_records_tests COMMAND ui_series_records_tests "${BMH_DATA}") +add_executable(ui_analytics_tests analytics_tests.cpp) +target_link_libraries(ui_analytics_tests PRIVATE bmhui) +bmh_add_data_test(NAME ui_analytics_tests COMMAND ui_analytics_tests "${BMH_DATA}") +add_executable(minute_statistics_tests minute_statistics_tests.cpp) +target_link_libraries(minute_statistics_tests PRIVATE bmhui) +bmh_add_data_test(NAME minute_statistics_tests COMMAND minute_statistics_tests "${BMH_DATA}") +add_executable(transfer_history_tests transfer_history_tests.cpp) +target_link_libraries(transfer_history_tests PRIVATE bmhui) +bmh_add_data_test(NAME transfer_history_tests COMMAND transfer_history_tests "${BMH_DATA}") + +add_executable(sportschau_ui_tests ../../tests/sportschau_ui_tests.cpp) +target_link_libraries(sportschau_ui_tests PRIVATE bmhui) +bmh_add_data_test(NAME sportschau_ui_tests COMMAND sportschau_ui_tests "${BMH_DATA}") diff --git a/src/ui/achievements.cpp b/src/ui/achievements.cpp new file mode 100644 index 0000000..ba4b2e6 --- /dev/null +++ b/src/ui/achievements.cpp @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/achievements.hpp" + +#include +#include +#include + +#include "formats/binary.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +namespace bmh::ui { +namespace { +constexpr int kFirstPlotX = 0x41; +constexpr int kPlotRight = 0x107; +constexpr int kWindowLeft = 0x2b, kWindowTop = 0x14; +constexpr int kWindowRight = 0x11a, kWindowBottom = 0xd2; +constexpr uint32_t kLeagueHeaderTable = ::bmh::layout::LeagueHeaderTable; +constexpr uint32_t kRoundNameTable = ::bmh::layout::RoundNameTable; +constexpr uint32_t kEuropeNameTable = ::bmh::layout::EuropeNameTable; + +void fill(Image& out, int x, int y, int w, int h, uint8_t color) { + const int x0=std::max(0,x), y0=std::max(0,y), x1=std::min(out.width,x+w), y1=std::min(out.height,y+h); + for(int yy=y0;yysource.width||sy+h>source.height)throw FormatError("achievements: Source KB56 bounds"); + for(int yy=0;yy=0&&y+yy>=0&&x+xx& b,size_t at){return uint16_t(b.at(at))|uint16_t(uint16_t(b.at(at+1))<<8);} +// FNT files consume the game's single-byte encoding; only JSON/test boundaries use UTF-8. +std::string text(const TextDb& db,size_t id){return db.strings.at(id);} +std::string source_text(const GameState& game,uint32_t pointer_variable){return message_text(game,pointer_variable);} +} + +bool achievements_available(const GameState& game) { + // AchievementsFromGame's Source gate is LeagueRoundCounters: no league position has been recorded yet. + // This is the first byte of the serialized nine-byte league_rounds block. Read the + // decoded authoritative block so a cold-loaded save does not depend on an optional + // runtime-memory mirror being present. + return !game.league_rounds.empty() && game.league_rounds.front()!=0; +} + +AchievementsState achievements_from_game(const GameState& game,const LeImage& exe, + const DeskRequest& owner,const Image& underlay) { + if(owner.kind!=DeskRequestKind::open_menu||owner.menu_kind!=4||owner.manager_slot<0||owner.manager_slot>3|| + game.memory.has(::bmh::layout::ActiveManager)&&game.memory.u8(::bmh::layout::ActiveManager)!=owner.manager_slot|| + size_t(owner.manager_slot)>=game.manager_teams.size()||owner.revision==UINT64_MAX|| + underlay.width!=320||underlay.height!=240||!game.texts) + throw FormatError("achievements: invalid Source desk owner"); + const size_t base=size_t(owner.manager_slot)*0xb0c; + if(base+0x556>game.manager_records.size())throw FormatError("achievements: truncated Source manager history"); + AchievementsState out;out.owner=owner;out.manager_slot=owner.manager_slot;out.underlay=underlay; + out.season_count=std::clamp(game.season+1,1,50);out.selected_season=out.season_count-1; + out.decorated_background=!game.memory.has(::bmh::layout::PlainBackground)||game.memory.u8(::bmh::layout::PlainBackground)==0; + out.source_panel=!game.memory.has(::bmh::layout::SolidPanelBackground)||game.memory.u8(::bmh::layout::SolidPanelBackground)==0; + out.gradient_text=!game.memory.has(::bmh::layout::TextGradientDisabled)||game.memory.u8(::bmh::layout::TextGradientDisabled)==0; + out.title=original_to_utf8(source_text(game,::bmh::layout::Achievements_FormatError_TextPointer6)); + out.manager_team_name=original_to_utf8(game.club_name(game.manager_teams[size_t(owner.manager_slot)])); + // AchievementsRuntimeField is a u16 per manager at manager-record +0x2aa: seasons before + // this manager began. The displayed heading is a Source-formatted year number, + // not the current club name. + const int manager_start=rd16(game.manager_records,base+0x2aa); + for(int season=0;season>5)==1)round=8; + value+=source_text(game,kRoundNameTable+uint32_t(round)*4); + return value; + }; + row.cup_text=cup_text(row.cup_result,1); + row.europe_text=cup_text(row.europe_result,2); + const int europe_stage=row.europe_result&0x1f; + if(europe_stage!=0&&europe_stage!=8){ + const int competition=row.europe_result>>5; + row.europe_text += source_text(game,::bmh::layout::Achievements_FormatError_TextPointer7)+source_text(game,kEuropeNameTable+uint32_t(competition)*4); + } + } + return out; +} + +AchievementsScreen::AchievementsScreen(const std::filesystem::path& data,AchievementsState state) + :exe_(load_le(asset_path(data,"BMH.exe"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))), + body_(load_font(asset_path(data/"F","BMH3.FNT"))), + header_(load_font(asset_path(data/"F","BMH2.FNT"))), + sprite_font_(data),background_(load_vga(asset_path(data/"KB","129.VGA"))), + panel_(load_vga(asset_path(data/"KB","56.VGA"))),state_(std::move(state)) { + if(state_.manager_slot<0||state_.manager_slot>3||state_.season_count<1||state_.season_count>50|| + state_.selected_season < -1||state_.selected_season>=state_.season_count||state_.underlay.width!=320|| + state_.underlay.height!=240||background_.width!=320||background_.height!=240|| + panel_.width<281||panel_.height<190) + throw FormatError("achievements: incomplete Original projection/assets"); + (void)render(); +} + +void AchievementsScreen::draw_text(Image& out,int x,int baseline,std::string_view value,uint8_t color)const{ + if(value.empty())return; + // DrawnFirstBy validates baseline-font-height, then passes the baseline to Draw. + body_.draw(out,x,baseline-body_.baseline,value,color); +} + +Image AchievementsScreen::render()const{ + Image out=state_.decorated_background?background_:Image(320,240,0); + if(!state_.decorated_background){ + fill(out,0,4,320,13,0x44);fill(out,0,0xe4,320,10,0x44); + fill(out,1,5,318,11,0x39);fill(out,1,0xe5,318,8,0x39); + } + sprite_font_.draw(out,SpriteFont::centered_title_x(sprite_font_.text_width(state_.title)),0x0d,state_.title,5); + sprite_font_.draw(out,5,0xeb,state_.manager_team_name,5); + if(state_.source_panel)copy(out,panel_,kWindowLeft,kWindowTop-19,kWindowLeft+1,kWindowTop+1, + kWindowRight-kWindowLeft-1,kWindowBottom-kWindowTop-1,0xc0); + else fill(out,kWindowLeft,kWindowTop,kWindowRight-kWindowLeft+1,kWindowBottom-kWindowTop+1,0x42); + for(int x=kWindowLeft;x<=kWindowRight;++x){out.at(x,kWindowTop)=0x46;out.at(x,kWindowBottom)=0x40;} + for(int y=kWindowTop;y<=kWindowBottom;++y){out.at(kWindowLeft,y)=0x46;out.at(kWindowRight,y)=0x40;} + // AchievementsFromGame reads these exact y coordinates and palette indices from BMH.exe. + const std::array baselines{{exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField4),exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField5),exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField6)}}; + // AchievementsFromGame draws the three colored, three-pixel graph traces before the headers/bars. + for(int season=1;seasonout.height||y1>out.height)continue; + const int dx=std::abs(x1-x0), sx=x0 Abs starts its accumulator at zero. Move + // the major axis first; the minor axis advances only on overflow. + int accumulator=0; + auto plot=[&]{if(x0>=0&&x0<320&&y0>=0&&y0<240) + out.at(x0,y0)=exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField+uint32_t(line));}; + plot(); + if(dy=dx){accumulator-=dx;y0+=sy;}plot();} + } else { + for(int step=0;step=dy){accumulator-=dy;x0+=sx;}plot();} + } + } + } + constexpr std::array headings{{::bmh::layout::LeagueHeaderTable,::bmh::layout::Achievements_Fill_ExecutableField,::bmh::layout::Achievements_Fill_ExecutableField2}}; + for(int column=0;column<3;++column){ + const int y=baselines[size_t(column)]; + const auto& label=texts_[text_id(headings[size_t(column)])]; + // AchievementsFromGame selects font 2 for each centered heading; DrawnFirstBy + // centers within inclusive x=0..319 and then restores font 3. + const int width=header_.text_width(label); + header_.draw(out,319/2-width/2,y+9-header_.baseline,label,0x6b); + fill(out,0x3f,y,0xca,1,0x5f); + } + for(int season=0;season=0){ + const int step=exe_.u8(::bmh::layout::LeagueSizes+uint32_t(step_index)); + const int height=std::min(remaining,step); + const int palette=row.league_result==0?4:color_index; + // Fill2 calls Fill3 with inclusive x endpoints (x+1..x+2 and x..x+1). + fill(out,x+1,y-height,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField2+uint32_t(palette*2))); + fill(out,x,y-height-1,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField3+uint32_t(palette*2))); + y-=step;remaining-=step; + ++color_index; + const int previous=step_index--; + if(step_index==2)step_index=previous-2; + } + } + if(row.cup_result!=0){ + const int rounds=row.cup_result; + const int height=rounds*3; + const int y=baselines[1]-1; + const int palette=rounds==7?4:2; + fill(out,x+1,y-height,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField2+uint32_t(palette*2))); + fill(out,x,y-height-1,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField3+uint32_t(palette*2))); + } + const int europe_round=row.europe_result&0x1f; + if(europe_round!=0){ + const int height=europe_round*3; + const int y=baselines[2]-1; + const int palette=europe_round==7?4:row.europe_result>>5; + fill(out,x+1,y-height,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField2+uint32_t(palette*2))); + fill(out,x,y-height-1,2,height+1,exe_.u8(::bmh::layout::Achievements_Fill_RuntimeField3+uint32_t(palette*2))); + } + } + const int detail_y=0xbb; + if(state_.source_panel)copy(out,panel_,0x2d,0xb4-19,0x2e,0xb5,0x118-0x2d-1,0xcd-0xb4-1,0xc0); + else fill(out,0x2d,0xb4,0x118-0x2d+1,0xcd-0xb4+1,0x42); + for(int x=0x2d;x<=0x118;++x){out.at(x,0xb4)=0x46;out.at(x,0xcd)=0x40;} + for(int y=0xb4;y<=0xcd;++y){out.at(0x2d,y)=0x46;out.at(0x118,y)=0x40;} + if(state_.selected_season>=0){ + const auto& selected=state_.seasons[size_t(state_.selected_season)]; + draw_text(out,0x32,detail_y,selected.season_label,0x69); + if(selected.league_result==0xff){ + draw_text(out,0x42,0xd9,text(texts_,text_id(::bmh::layout::Achievements_Fill_TextPointer)),0x69); + }else{ + draw_text(out,0x4c,detail_y,selected.league_text,selected.league_color); + draw_text(out,0x4c,detail_y+8,selected.cup_text,(selected.cup_result&0x1f)==7?0x27:0x69); + draw_text(out,0x4c,detail_y+16,selected.europe_text,(selected.europe_result&0x1f)==7?0x27:0x69); + } + } + return out; +} + +bool AchievementsScreen::move(int x,int y){ + if(pending_)return false; + const int previous=state_.selected_season; + if(xkPlotRight||y<0x16||y>0xd0){ + state_.selected_season=-1; + return previous!=-1; + } + const int season=(x-kFirstPlotX)/4; + // Source leaves the previous detail intact when the pointer lands in a + // four-pixel column beyond this manager's saved history. + if(seasonkPlotRight||y<0x16||y>0xd0)return {}; + const int season=(x-kFirstPlotX)/4; + if(season<0||season>=state_.season_count||season==state_.selected_season)return {}; + state_.selected_season=season;return {AchievementsRequestKind::none,state_.owner,season}; +} + +} // namespace bmh::ui diff --git a/src/ui/achievements.hpp b/src/ui/achievements.hpp new file mode 100644 index 0000000..fdf6a6f --- /dev/null +++ b/src/ui/achievements.hpp @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/state.hpp" +#include "ui/desktop.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +// AchievementsFromGame's 0xda record: one triple for each of the manager's 50 seasons. +struct AchievementSeason { + uint8_t league_result = 0xff, cup_result = 0, europe_result = 0; + uint8_t league_color = 0x69; + int graph_y = 0; + std::string season_label; + std::string league_text, cup_text, europe_text; +}; + +struct AchievementsState { + DeskRequest owner{}; + int manager_slot = -1; + int season_count = 0; + int selected_season = 0; + std::array seasons{}; + std::string title; + std::string manager_team_name; + Image underlay; + bool decorated_background = true; + bool source_panel = true; + bool gradient_text = true; +}; + +AchievementsState achievements_from_game(const GameState&, const LeImage&, + const DeskRequest&, const Image& underlay); +bool achievements_available(const GameState&); + +enum class AchievementsRequestKind : uint8_t { none, close }; +struct AchievementsRequest { + AchievementsRequestKind kind = AchievementsRequestKind::none; + DeskRequest owner{}; + int selected_season = 0; + bool operator==(const AchievementsRequest&) const = default; +}; + +class AchievementsScreen { +public: + AchievementsScreen(const std::filesystem::path&, AchievementsState); + Image render() const; + bool move(int x, int y); + AchievementsRequest pointer_down(int x, int y, bool right = false); + const AchievementsState& state() const { return state_; } + const std::optional& pending() const { return pending_; } +private: + LeImage exe_; + TextDb texts_; + Font body_, header_; + SpriteFont sprite_font_; + Image background_, panel_; + AchievementsState state_; + std::optional pending_; + void draw_text(Image&, int, int, std::string_view, uint8_t) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/achievements_tests.cpp b/src/ui/achievements_tests.cpp new file mode 100644 index 0000000..ab070c5 --- /dev/null +++ b/src/ui/achievements_tests.cpp @@ -0,0 +1,156 @@ +#include "../../tests/test_inputs.hpp" +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/achievements.hpp" + +#include +#include +#include +#include + +#include "game/messages.hpp" + +namespace { +void check(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); } +} + +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: ui_achievements_tests ORIGINAL_DATA"); + const std::filesystem::path data(argv[1]); + const auto exe = bmh::load_le(bmh::ui::asset_path(data, "BMH.exe")); + const auto texts = bmh::load_textd(bmh::ui::asset_path(data, "TEXTD.BLK")); + bmh::GameState game; + game.manager_records.assign(4 * 0xb0c, 0); + game.manager_teams = {0, 1, 2, 3}; + game.club_ids = {0, 1, 2, 3}; + game.club_names = {'B','a','y','e','r','n',0}; + game.manager_records[0x2aa] = 4; // format field, manager's first season offset. + game.manager_records[0xda] = 1; + game.manager_records[0xdb] = 1; + game.manager_records[0xdc] = 0x21; + game.manager_records[0xda + 3] = 5; + game.manager_records[0xdb + 3] = 7; + game.manager_records[0xdc + 3] = 0x43; + game.manager_records[0xda + 6] = 0xff; + game.season = 2; + game.league_rounds = std::vector(9, 0); + game.texts = &texts; + + check(!bmh::ui::achievements_available(game), "legacy routine blocks before first recorded league round"); + game.league_rounds[0] = 1; + check(bmh::ui::achievements_available(game), "cold-loaded league_rounds[0] opens Source gate"); + bmh::ui::DeskRequest owner; + owner.kind = bmh::ui::DeskRequestKind::open_menu; + owner.menu_kind = 4; + owner.manager_slot = 0; + owner.item_id = 12; + owner.revision = 9; + const bmh::Image underlay(320, 240, 0x40); + const auto state = bmh::ui::achievements_from_game(game, exe, owner, underlay); + check(state.season_count == 3 && state.selected_season == 2, + "Source displays seasons 0 through format field, capped by the 50-entry history"); + check(state.seasons[0].league_result == 1 && state.seasons[0].cup_result == 1 && + state.seasons[0].europe_result == 0x21 && state.seasons[1].cup_result == 7 && + state.seasons[1].europe_result == 0x43 && state.seasons[2].league_result == 0xff, + "projection preserves all three raw manager-history bytes per year"); + check(state.seasons[0].graph_y == int(uint8_t(0xa4 - 2 - 2 - (0x48 - 1) / 2)) && + state.seasons[0].season_label == format_number(game,int(exe.u16(::bmh::layout::Achievements_FormatError_RuntimeField2))+4,0xc4)+exe.cstring(::bmh::layout::Achievements_FormatError_RuntimeField) && + state.seasons[2].league_text.empty(), + "Source graph coordinate, 16-bit year base, and 0xff prior-manager sentinel"); + bmh::ui::AchievementsScreen screen(data, state); + auto frame = screen.render(); + check(frame.width == 320 && frame.height == 240 && frame.pixels != underlay.pixels, + "Original KB129/SpriteFont and KB56 detail-panel renderer draws achievements"); + check(frame.pixels[size_t(int(exe.u8(::bmh::layout::Achievements_Fill_RuntimeField4))-2)*size_t(frame.width)+0x43]==exe.u8(::bmh::layout::Achievements_Fill_RuntimeField2), + "legacy routine uses low-word color index 0 for the first nonzero league band"); + const auto header = bmh::load_font(bmh::ui::asset_path(data / "F", "BMH2.FNT")); + const auto& heading = texts[bmh::text_id(::bmh::layout::LeagueHeaderTable)]; + bmh::Image heading_mask(header.text_width(heading), header.height); + header.draw(heading_mask, 0, 0, heading, 1); + const int heading_x = 319 / 2 - heading_mask.width / 2; + const int heading_y = int(exe.u8(::bmh::layout::Achievements_Fill_RuntimeField4)) + 9 - header.baseline; + int heading_ink = 0; + for(int y=0;y0 && frame.at(0x108,int(exe.u8(::bmh::layout::Achievements_Fill_RuntimeField4)))==0x5f, + "Source graph baseline includes its right endpoint"); + + // WEEK196's first three history triples straddle the signed-char boundary. + // A signed 132 -> -124 trace to 123 crossed the top of the graph and + // produced the user's black pixels at 67,29 and 71,29. + auto boundary_game=game; + const std::array history{{11,1,0,10,5,0,18,1,0}}; + std::copy(history.begin(),history.end(),boundary_game.manager_records.begin()+0xda); + auto boundary_state=bmh::ui::achievements_from_game(boundary_game,exe,owner,underlay); + check(boundary_state.seasons[0].graph_y==132 && + boundary_state.seasons[1].graph_y==123 && boundary_state.seasons[2].graph_y==135, + "legacy routine retains unsigned byte y coordinates across 127/128"); + boundary_state.selected_season=-1; + bmh::ui::AchievementsScreen boundary_screen(data,boundary_state); + auto boundary_frame=boundary_screen.render(); + auto panel=bmh::load_vga(bmh::ui::asset_path(data/"KB","56.VGA")); + check(boundary_frame.at(67,29)==panel.at(66,9) && + boundary_frame.at(71,29)==panel.at(70,9), + "unsigned Source graph traces leave the upper-panel pixels intact"); + auto check_traces=[&](const std::array& points){ + auto traces=boundary_state; + for(int i=0;i<3;++i){ + traces.seasons[size_t(i)].league_result=0xfe; + traces.seasons[size_t(i)].cup_result=0; + traces.seasons[size_t(i)].europe_result=0; + traces.seasons[size_t(i)].graph_y=points[size_t(i)]; + } + bmh::ui::AchievementsScreen trace_screen(data,traces); + auto actual=trace_screen.render(); + auto blank=traces; + for(int i=0;i<3;++i)blank.seasons[size_t(i)].graph_y=240; + bmh::ui::AchievementsScreen blank_screen(data,blank); + auto expected=blank_screen.render(); + // Closed-form positions are an independent oracle for legacy routine's + // zero accumulator: minor displacement=floor(step*minor/major). + for(int season=1;season<3;++season)for(int line=0;line<3;++line){ + const int x0=0x41+(season-1)*4; + const int y0=uint8_t(points[size_t(season-1)]+line); + const int y1=uint8_t(points[size_t(season)]+line); + const int dy=std::abs(y1-y0),sy=y1 +#include +#include +#include +#include +#include +#include +#include + +#include "formats/textd.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "game/week.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +namespace bmh::ui { +namespace { +constexpr size_t kManagerRecord = 0xb0c; +constexpr size_t kAdvertisingContracts = 0xa34; +constexpr size_t kContractBytes = 0x0c; +constexpr int kBoardCount = 14; + +// Games sorts the unsigned 32-bit keys in descending order and swaps +// the parallel 16-bit record indices at the same time. Keep its midpoint pivot +// and partition boundaries: equal keys intentionally do not retain input order. +void original_contract_sort(std::array& keys, + std::array& slots, + int first, int count) { + while (count > 1) { + const uint32_t pivot = keys[size_t(first + count / 2)]; + int left = -1; // Original ushort starts at 0xffff, then wraps to index 0. + int right = count; + do { + do { ++left; } while (pivot < keys[size_t(first + left)]); + do { --right; } while (keys[size_t(first + right)] < pivot); + if (right <= left) break; + std::swap(keys[size_t(first + left)], keys[size_t(first + right)]); + std::swap(slots[size_t(first + left)], slots[size_t(first + right)]); + } while (true); + + original_contract_sort(keys, slots, first, left); + first += left; + count -= left; + } +} + +uint32_t u32(const std::vector& bytes, size_t at) { + return uint32_t(bytes.at(at)) | uint32_t(bytes.at(at + 1)) << 8 | + uint32_t(bytes.at(at + 2)) << 16 | uint32_t(bytes.at(at + 3)) << 24; +} + +int32_t signed32(uint32_t value) { return std::bit_cast(value); } +int32_t wrap_add(int32_t a, int32_t b) { return signed32(uint32_t(a) + uint32_t(b)); } +int32_t wrap_mul(int32_t a, int32_t b) { return signed32(uint32_t(a) * uint32_t(b)); } +int32_t wrap_neg(int32_t value) { return signed32(0u - uint32_t(value)); } +int32_t mem_i32(const GameState& game, uint32_t address) { + return signed32(game.memory.u32(address)); +} +std::string original_two_digit(int value) { + std::string result = std::to_string(value); + if (result.size() < 2) result.insert(result.begin(), '%'); + return result; +} +std::string original_grouped_number(uint32_t value) { + std::string digits = std::to_string(value); + const int actual = int(digits.size()); + for (int from = actual - 3; from > 0; from -= 3) digits.insert(size_t(from), "."); + return digits; +} + +int32_t original_share_adjustment(const GameState& game, int manager, bool income) { + // SharesAndLoans/Rec32: original LE code reads each owned fund from + // FundBlock + k*0x1c (MOVDWORD at 4bacb), not byte stride seven. Its unit prices + // at BMH.exe+MonthRuntimeField10 are {15,18,21,24,27,30}; owned counts use Advertising_OriginalShareAdjustment_RuntimeField + k*0x1c. + // The outstanding-share/loan rows are saved at Loans. + constexpr std::array kShareUnits{15, 18, 21, 24, 27, 30}; + const uint8_t manager_count = game.memory.u8(::bmh::layout::ManagerCount); // runtime ManagerCount + if (manager_count > 4) throw FormatError("advertising: invalid Original manager count"); + int32_t amount = 0; + if (income) { + for (int k = 0; k < 6; ++k) { + const uint32_t shares = game.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c); + const uint32_t unit = uint32_t(shares) * uint32_t(kShareUnits[size_t(k)]) / 10000; + const uint32_t owned = game.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(k) * 0x1c); + amount = wrap_add(amount, signed32(unit * owned)); + } + } + for (uint32_t other = 0; other <= manager_count; ++other) { + if (!income) { + const uint32_t row = other * 0x18 + uint32_t(manager) * 0x78; + amount = wrap_add(amount, wrap_neg(mem_i32(game, ::bmh::layout::Loans + row + 8))); + } else if (other != 0) { + const uint32_t row = uint32_t(manager + 1) * 0x18 + (other - 1) * 0x78; + amount = wrap_add(amount, mem_i32(game, ::bmh::layout::Loans + row + 8)); + } + } + return amount; +} + +int32_t original_finance_adjustment(const GameState& game, int manager) { + // DailyInterest2(0): same record arithmetic as daily interest, with all booking, + // news, and random branches skipped. Record +0x314 balance, +0x318 deposit, + // +0x31c credit line; -0x8e94 is -36500. + constexpr int32_t kAnnualRate = -0x8e94; + const size_t rec = size_t(manager) * kManagerRecord; + const int32_t balance = int32_t(u32(game.manager_records, rec + 0x314)); + const int32_t deposit = int32_t(u32(game.manager_records, rec + 0x318)); + const int32_t credit = int32_t(u32(game.manager_records, rec + 0x31c)); + int32_t result = 0; + if (balance < 0) { + const int32_t with_credit = wrap_add(balance, credit); + if (with_credit < 0) result = wrap_mul(with_credit, 0x12) / kAnnualRate; + int32_t below_credit = wrap_neg(credit); + if (below_credit < balance) below_credit = balance; + result = wrap_add(result, wrap_mul(below_credit, 0xc) / kAnnualRate); + } else { + result = balance / kAnnualRate; + } + const int32_t deposit_units = wrap_mul(deposit / 10000, 20000); + return wrap_add(result, deposit_units / kAnnualRate); +} + +std::string original_currency_text(const GameState& game, int32_t value, + int flags = 0x88, std::string_view suffix = ".") { + // ConvertCurrency multiplies in 32-bit arithmetic before signed division. + // Do the product modulo 2^32 explicitly, then reject the two undefined + // division cases rather than invoking C++ signed-division UB. + const int32_t multiplier = game.memory.has(::bmh::layout::CurrencyMultiplier) ? + signed32(game.memory.u32(::bmh::layout::CurrencyMultiplier)) : 1; + const int32_t divisor = game.memory.has(::bmh::layout::CurrencyDivisor) ? + signed32(game.memory.u32(::bmh::layout::CurrencyDivisor)) : 1; + if (divisor == 0) throw FormatError("advertising: invalid Original currency divisor"); + const int32_t product = wrap_mul(value, multiplier); + if (product == std::numeric_limits::min() && divisor == -1) + throw FormatError("advertising: invalid Original currency division"); + const int32_t converted = product / divisor; + return original_to_utf8(format_number(game, converted, flags) + " EU" + std::string(suffix)); +} + +AdvertisingFinancePreview original_finance_preview_impl(const GameState& game, int manager) { + if (!game.memory.has(::bmh::layout::ActiveManager) || int(game.memory.u8(::bmh::layout::ActiveManager)) != manager) + throw FormatError("advertising: finance preview manager is not the active Original manager"); + const size_t rec = size_t(manager) * kManagerRecord; + constexpr std::array kFacilityCost{ + 2000,3000,3000,8000,4000,3000,2500,2500,2500,2500,2600,2600,2600,2600, + 13000,9000,9000,8000,1000,1500,1500,2000}; // BMHExeXa, BMH.exe+BalancePlanRuntimeField5 + constexpr std::array kFacilityIncome{0,5000,5000,4800,2400,8000}; + + int32_t income = 0; + for (int i = 0; i < 6; ++i) { + const uint8_t level = game.manager_records.at(rec + size_t(i)); + if (level == 0) continue; + const int facility_level = i == 0 ? ((int(level) - 1) / 0x55 + 1) : 1; + income = wrap_add(income, facility_level * int32_t(kFacilityIncome[size_t(i)])); + } + for (int slot = 0; slot < 16; ++slot) + income = wrap_add(income, signed32(u32(game.manager_records, + rec + kAdvertisingContracts + size_t(slot) * kContractBytes))); + income = wrap_add(income, original_share_adjustment(game, manager, true)); + + // DeskDate2 computes CareerSession_PairingsRuntimeDraw_ExecutableField5 from the day counter; month_code is its + // already-port-tested month result. DeskState_DeskDate_RuntimeField is days-per-month (Feb corrected + // for the current leap year), used as the preview multiplier. + uint32_t day = game.date; + int year_phase = 3; + while (day > uint32_t((year_phase == 4 ? 1 : 0) + 0x16c)) { + if (year_phase == 4) { year_phase = 0; --day; } + day -= 0x16d; + ++year_phase; + } + const int month = month_code(game.date); + if (month < 0 || month >= 13) + throw FormatError("advertising: invalid Original finance month"); + const int month_factor = month == 2 && year_phase == 4 ? 29 : + std::array{0,31,28,31,30,31,30,31,31,30,31,30,31}[size_t(month)]; + income = wrap_add(income, wrap_neg(wrap_mul(original_finance_adjustment(game, manager), month_factor))); + + // OpenBMH deviates from the original: uses the supported youth-academy cap and its saved cost fields. +// OriginalFinancePreview(0): pure amount of BMHExeXa, record +0x854/+0x858, + // MonthlyPay flags 0x0a (salary+bonus without statistic writes), and six + // saved supported rule profile cost words. The cap for index 1 comes from TeamLeague3. + int32_t expenses = 0; + for (int i = 0; i < 14; ++i) expenses = wrap_add(expenses, kFacilityCost[size_t(i)]); + for (int i = 14; i < 22; ++i) + expenses = wrap_add(expenses, + int32_t(game.manager_records.at(rec + 0x2e + size_t(i)) & 7) * kFacilityCost[size_t(i)]); + expenses = wrap_add(expenses, signed32(u32(game.manager_records, rec + 0x854))); + expenses = wrap_add(expenses, signed32(u32(game.manager_records, rec + 0x858))); + constexpr size_t kBoard = 0x840, kBoardSlot = 0x58; + for (size_t slot = 0; slot < 24; ++slot) { + const size_t board = size_t(manager) * kBoard + slot * kBoardSlot; + if (game.tactics.at(board + 0x3d) == 0xff) continue; + const uint32_t bonus = uint32_t(game.tactics.at(board + 0x4e)) | + (uint32_t(game.tactics.at(board + 0x4f) & 0x7f) << 8); + expenses = wrap_add(expenses, signed32(u32(game.tactics, board + 0x50))); + expenses = wrap_add(expenses, int32_t(bonus)); + } + const int team = int(u32(game.manager_records, rec + 0x290) & 0xffff); + const int league = team > 0x164 ? 0 : team_league(team); // TeamLeague2 + const int32_t youth_cap = league == 0 ? 1500000 : league == 1 ? 1000000 : + league <= 3 ? 580000 : 280000; + for (int k = 0; k < 6; ++k) { + int32_t item = mem_i32(game, ::bmh::layout::Spending + uint32_t(manager) * 0x24 + uint32_t(k) * 4); + if (k == 0 || k == 2) { + // MonthlyExpenses clears these indexes unconditionally (CMP AX,3 / CMP AX,1). + item = 0; + } else if (k == 1 && item != 0) { + item = u32(game.manager_records, rec + 0x880) < uint32_t(youth_cap) ? youth_cap : 0; + } + expenses = wrap_add(expenses, item); + } + expenses = wrap_add(expenses, wrap_neg(original_share_adjustment(game, manager, false))); + expenses = wrap_add(expenses, int32_t(game.manager_records.at(rec + 0x179)) * 1000); + if (expenses < 0) expenses = 0; + const int32_t balance = wrap_add(income, wrap_neg(expenses)); + return {income, expenses, balance, + original_currency_text(game, income), original_currency_text(game, expenses), + original_currency_text(game, balance)}; +} + +std::string utf8(std::string_view original) { return original_to_utf8(original); } + +std::string original_advertising_amount_text(const GameState& game, int32_t value) { + const int32_t multiplier = game.memory.has(::bmh::layout::CurrencyMultiplier) ? + signed32(game.memory.u32(::bmh::layout::CurrencyMultiplier)) : 1; + const int32_t divisor = game.memory.has(::bmh::layout::CurrencyDivisor) ? + signed32(game.memory.u32(::bmh::layout::CurrencyDivisor)) : 1; + if (divisor == 0) throw FormatError("advertising: invalid Original currency divisor"); + const int32_t product = wrap_mul(value, multiplier); + if (product == std::numeric_limits::min() && divisor == -1) + throw FormatError("advertising: invalid Original currency division"); + // FormatNumber(..., 0x108, AdvertisingRuntimeField): width eight, converted currency, + // and the standard EU suffix emitted by the 0x100 formatter flag. + return original_to_utf8(format_number(game, product / divisor, 0x08) + " EU"); +} + +AdvertisingContract contract_from_game(const GameState& game, int manager, int slot) { + const size_t at = size_t(manager) * kManagerRecord + kAdvertisingContracts + + size_t(slot) * kContractBytes; + const auto& record = game.manager_records; + AdvertisingContract value; + value.record_slot = slot; + value.monthly_amount = int32_t(u32(record, at)); + std::copy_n(record.begin() + static_cast(at), value.bytes.size(), value.bytes.begin()); + value.months_remaining = record.at(at + 5); + const uint8_t flags = record.at(at + 6); + value.extension_months = flags & 0x7f; + value.option_marker = (flags & 0x80) != 0; + value.sponsor_id = record.at(at + 7); + value.active = value.monthly_amount != 0; + if (value.active) { + // OriginalFinancePreview3 selects the second ten-name table only for contract index 15. + if (value.sponsor_id >= 10) + throw FormatError("advertising: active contract has invalid sponsor identity"); + const uint32_t sponsor_text = ::bmh::layout::Advertising_FormatError_ExecutableField3 + uint32_t(value.sponsor_id) * 4 + + (slot == 15 ? 10 * 4 : 0); + value.sponsor_name = utf8(message_text(game, sponsor_text)); + if (value.sponsor_name.empty()) + throw FormatError("advertising: active contract sponsor name is unavailable"); + value.amount_text = original_advertising_amount_text(game, value.monthly_amount); + } + return value; +} + +void copy(Image& out, const Image& src, int sx, int sy, int x, int y, int w, int h) { + if (sx < 0 || sy < 0 || sx + w > src.width || sy + h > src.height || + x < 0 || y < 0 || x + w > out.width || y + h > out.height) + throw FormatError("advertising: original VGA crop outside image"); + for (int yy = 0; yy < h; ++yy) + for (int xx = 0; xx < w; ++xx) + out.at(x + xx, y + yy) = src.pixels[size_t(sy + yy) * src.width + sx + xx]; +} + +void fill_rect(Image& image, int x, int y, int width, int height, uint8_t color) { + if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > image.width || y + height > image.height) + throw FormatError("advertising: rectangle outside image"); + for (int yy = y; yy < y + height; ++yy) + for (int xx = x; xx < x + width; ++xx) + image.at(xx, yy) = color; +} + +void rectangle(Image& image, int x, int y, int width, int height, uint8_t color) { + for (int xx = x; xx < x + width; ++xx) { + image.at(xx, y) = color; + image.at(xx, y + height - 1) = color; + } + for (int yy = y; yy < y + height; ++yy) { + image.at(x, yy) = color; + image.at(x + width - 1, yy) = color; + } +} + +} + +AdvertisingFinancePreview original_finance_preview(const GameState& game, int manager) { + return original_finance_preview_impl(game, manager); +} + +AdvertisingState advertising_from_game(const GameState& game, int manager_slot, uint64_t revision) { + if (manager_slot < 0 || manager_slot > 3 || manager_slot >= int(game.manager_teams.size())) + throw FormatError("advertising: invalid manager slot"); + const size_t record = size_t(manager_slot) * kManagerRecord; + if (record + kAdvertisingContracts + 16 * kContractBytes > game.manager_records.size()) + throw FormatError("advertising: manager record has no complete contract block"); + if (!game.texts) throw FormatError("advertising: original TEXTD strings are unavailable"); + + AdvertisingState state; + state.manager_slot = manager_slot; + state.revision = revision; + state.runtime_team_id = game.manager_teams[size_t(manager_slot)]; + if (state.runtime_team_id < 0) throw FormatError("advertising: invalid manager team"); + state.club_name = utf8(game.club_name(state.runtime_team_id)); + if (record + 0x23a > game.manager_records.size() || + size_t(state.runtime_team_id) * 2 + 2 > game.club_heap_78.size()) + throw FormatError("advertising: manager identity is unavailable"); + const auto manager_name_begin = game.manager_records.begin() + std::ptrdiff_t(record + 0xa8); + const auto manager_name_end = std::find(manager_name_begin, manager_name_begin + 26, uint8_t(0)); + state.manager_name = original_to_utf8(std::string_view( + reinterpret_cast(&*manager_name_begin), size_t(manager_name_end - manager_name_begin))); + state.manager_portrait = game.manager_records.at(record + 0x221); + state.notification_ack_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer17)); + state.spending_blocked_text = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer21)); + state.spending_funds_text = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer18)); + state.badge_sprite = (int(game.club_heap_78[size_t(state.runtime_team_id) * 2]) | + (int(game.club_heap_78[size_t(state.runtime_team_id) * 2 + 1]) << 8)) & 0x1ff; + state.title = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer20)); + if (state.title.empty()) state.title = "Werbung"; + state.original_panel = !game.memory.has(::bmh::layout::SolidPanelBackground) || game.memory.u8(::bmh::layout::SolidPanelBackground) == 0; + state.decorated_background = !game.memory.has(::bmh::layout::PlainBackground) || game.memory.u8(::bmh::layout::PlainBackground) == 0; + state.font_gradient = !game.memory.has(::bmh::layout::TextGradientDisabled) || game.memory.u8(::bmh::layout::TextGradientDisabled) == 0; + state.duration_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer8)); + state.month_suffix = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer9)); + state.option_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer10)); + state.terminable_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer11)); + state.boards_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer12)); + state.offer_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer13)); + state.bonus_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer14)); + state.per_month_suffix = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer15)); + state.no_offer_text = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer6)); + state.space_available_text = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer7)); + state.cancel_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer2)); + state.accept_label = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer3)); + state.spending_labels = {utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer4)), + utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer5)), + utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer5))}; + state.merchandise_calculator_title = state.spending_labels[0]; + state.budget_calculator_title = state.spending_labels[1]; + for (int id = 0; id < 10; ++id) { + state.board_sponsor_names[size_t(id)] = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_ExecutableField3 + uint32_t(id) * 4)); + state.television_sponsor_names[size_t(id)] = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_ExecutableField3 + uint32_t(10 + id) * 4)); + } + for (int display = 0; display < 16; ++display) { + state.offers[size_t(display)] = bmh::advertising_offers(game, manager_slot, display); + } + for (int slot = 16; slot <= 18; ++slot) + state.spending[size_t(slot - 16)] = bmh::advertising_spending(game, manager_slot, slot); + + for (size_t display = 0; display < state.offers.size(); ++display) + for (const auto& offer : state.offers[display].offers) + if (offer.raw_slot >= 0 && offer.raw_slot < 10) + state.offer_amount_text[display][size_t(offer.raw_slot)] = + original_advertising_amount_text(game, int32_t(offer.monthly_amount)); + + std::array boards; + std::array sort_key{}; + for (int slot = 0; slot < kBoardCount; ++slot) { + boards[size_t(slot)] = contract_from_game(game, manager_slot, slot); + const auto& contract = boards[size_t(slot)]; + sort_key[size_t(slot)] = uint32_t(contract.monthly_amount); + if (contract.active && !contract.option_marker) sort_key[size_t(slot)] += 1000000; + } + std::array order{}; + for (int i = 0; i < kBoardCount; ++i) order[size_t(i)] = i; + // AdBoardOrder orders unsigned keys using the Original partition swaps, + // including equal keys; only the owned key/index arrays change here. + original_contract_sort(sort_key, order, 0, kBoardCount); + state.boards.reserve(kBoardCount); + for (int slot : order) state.boards.push_back(std::move(boards[size_t(slot)])); + state.shirt = contract_from_game(game, manager_slot, 14); + state.television = contract_from_game(game, manager_slot, 15); + state.finance_preview = original_finance_preview(game, manager_slot); + for (size_t i = 0; i < state.finance_labels.size(); ++i) + state.finance_labels[i] = utf8(message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer16 + uint32_t(i) * 4)); + // AdvertisingFromGame: its three auxiliary displays are separate from sponsor + // contracts. Indices 17/18 read the same two amounts charged by OriginalFinancePreview. + if (const auto weeks = game.manager_records.at(record + 0x287); weeks != 0) + state.auxiliary_text[0] = utf8(format_number(game, weeks, 0x81) + message_text(game, ::bmh::layout::Advertising_FormatError_TextPointer19)); + for (size_t i = 1; i < state.auxiliary_text.size(); ++i) + state.auxiliary_text[i] = original_currency_text(game, + signed32(u32(game.manager_records, record + 0x810 + (16 + i) * 4)), 0x81); + return state; +} + +std::string advertising_state_json(const AdvertisingState& state, int selected_contract, + bool close_requested, int selected_offer, bool offer_open) { + std::ostringstream out; + out << "{\"screen\":\"advertising\",\"read_only\":false,\"revision\":" << state.revision + << ",\"manager_slot\":" << state.manager_slot + << ",\"runtime_team_id\":" << state.runtime_team_id + << ",\"club_name\":" << json_quote(state.club_name) + << ",\"title\":" << json_quote(state.title) + << ",\"original_panel\":" << (state.original_panel ? "true" : "false") + << ",\"decorated_background\":" << (state.decorated_background ? "true" : "false") + << ",\"finance_preview\":{\"income\":" << state.finance_preview.income + << ",\"expenses\":" << state.finance_preview.expenses + << ",\"balance\":" << state.finance_preview.balance + << ",\"income_text\":" << json_quote(state.finance_preview.income_text) + << ",\"expenses_text\":" << json_quote(state.finance_preview.expenses_text) + << ",\"balance_text\":" << json_quote(state.finance_preview.balance_text) + << ",\"source\":\"FinanceTotalsFromGame3(0)/OriginalFinancePreview(0)\"}" + << ",\"spending_views\":["; + for (size_t i = 0; i < state.spending.size(); ++i) { + if (i) out << ','; + const auto& v = state.spending[i]; + out << "{\"manager\":" << v.manager << ",\"target_slot\":" << v.target_slot + << ",\"current_amount\":" << v.current_amount << ",\"maximum_amount\":" << v.maximum_amount + << ",\"delivery_weeks\":" << unsigned(v.delivery_weeks) + << ",\"available\":" << (v.available ? "true" : "false") << '}'; + } + out << "],\"notification_text\":" << json_quote(state.notification_text) + << ",\"notification_warning\":" << (state.notification_warning ? "true" : "false") + << ",\"selected_contract\":" << selected_contract + << ",\"offer_open\":" << (offer_open ? "true" : "false") + << ",\"selected_offer\":" << selected_offer + << ",\"close_requested\":" << (close_requested ? "true" : "false") + << ",\"boards\":["; + auto write_contract = [&](const AdvertisingContract& value) { + out << "{\"record_slot\":" << value.record_slot << ",\"sponsor_id\":" << value.sponsor_id + << ",\"sponsor_name\":" << json_quote(value.sponsor_name) + << ",\"amount_text\":" << json_quote(value.amount_text) + << ",\"active\":" << (value.active ? "true" : "false") + << ",\"monthly_amount\":" << value.monthly_amount + << ",\"months_remaining\":" << unsigned(value.months_remaining) + << ",\"extension_months\":" << unsigned(value.extension_months) + << ",\"option_marker\":" << (value.option_marker ? "true" : "false") << '}'; + }; + for (size_t i = 0; i < state.boards.size(); ++i) { + if (i) out << ','; + write_contract(state.boards[i]); + } + out << "],\"shirt\":"; + write_contract(state.shirt); + out << ",\"television\":"; + write_contract(state.television); + out << ",\"offer_views\":["; + for (size_t i = 0; i < state.offers.size(); ++i) { + if (i) out << ','; + const auto& view = state.offers[i]; + out << "{\"display_slot\":" << view.display_slot << ",\"contract_slot\":" << view.contract_slot + << ",\"pool_group\":" << view.pool_group << ",\"free_boards\":" << view.free_boards << ",\"status\":" + << unsigned(view.status) << ",\"offers\":["; + for (size_t j = 0; j < view.offers.size(); ++j) { + if (j) out << ','; + const auto& offer = view.offers[j]; + out << "{\"raw_slot\":" << offer.raw_slot << ",\"amount\":" << offer.monthly_amount + << ",\"bundle_units\":" << unsigned(offer.bundle_units) + << ",\"months\":" << unsigned(offer.months) << ",\"sponsor_id\":" << unsigned(offer.sponsor_id) + << ",\"present\":" << (offer.present ? "true" : "false") + << ",\"can_accept\":" << (offer.can_accept ? "true" : "false") << '}'; + } + out << "]}"; + } + out << ']'; + out << '}'; + return out.str(); +} + +AdvertisingScreen::AdvertisingScreen(const std::filesystem::path& data, AdvertisingState state, + uint64_t request_id_seed) + : state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))), + large_font_(load_font(asset_path(data / "F", "BMH2.FNT"))), + sprite_font_(data), + desktop_(load_vga(asset_path(data / "KB", "129.VGA"))), + art_(load_vga(asset_path(data / "KB", "4.VGA"))), + logos_(load_vga(asset_path(data / "KB", "34.VGA"))), + panel_(load_vga(asset_path(data / "KB", "56.VGA"))), + widgets_(load_vga(asset_path(data / "KB", "0.VGA"))), + calculator_(load_vga(asset_path(data / "KB", "6.VGA"))), + faces_(load_vga(asset_path(data / "KB", "26.VGA"))), next_request_id_(request_id_seed) { + if (state_.manager_slot < 0 || state_.manager_slot > 3 || state_.runtime_team_id < 0 || state_.boards.size() != kBoardCount || + desktop_.width != 320 || desktop_.height != 240 || art_.width < 320 || art_.height < 197 || + logos_.width < 110 || logos_.height < 231 || panel_.width < 314 || panel_.height < 203 || + widgets_.width != 77 || widgets_.height != 112 || calculator_.width < 113 || + calculator_.height < 150 || faces_.width < 228 || faces_.height < 76 || + request_id_seed == 0 || state_.manager_portrait < 0 || state_.manager_portrait > 11 || + state_.badge_sprite < 0 || state_.badge_sprite > 0x1ff) + throw FormatError("advertising screen: invalid owned state or original assets"); + (void)utf8_to_original(state_.title); + (void)utf8_to_original(state_.club_name); + (void)utf8_to_original(state_.manager_name); + (void)utf8_to_original(state_.notification_text); + (void)utf8_to_original(state_.notification_ack_label); + (void)utf8_to_original(state_.spending_blocked_text); + (void)utf8_to_original(state_.spending_funds_text); + (void)utf8_to_original(state_.merchandise_calculator_title); + (void)utf8_to_original(state_.budget_calculator_title); + if (source_badge_fallback(state_.runtime_team_id)) badge_atlas_ = widgets_; + else badge_atlas_ = load_vga(asset_path(data / "W", std::to_string(state_.badge_sprite >> 3) + ".VGA")); + for (const auto& value : {state_.finance_preview.income_text, + state_.finance_preview.expenses_text, + state_.finance_preview.balance_text}) + (void)utf8_to_original(value); + for (const auto& value : state_.finance_labels) (void)utf8_to_original(value); + for (const auto& value : state_.auxiliary_text) (void)utf8_to_original(value); + for (const auto& value : {state_.duration_label, state_.month_suffix, state_.option_label, + state_.terminable_label, state_.boards_label, state_.offer_label, + state_.bonus_label, state_.per_month_suffix, state_.no_offer_text, + state_.space_available_text, state_.cancel_label, state_.accept_label}) + (void)utf8_to_original(value); + for (const auto& value : state_.board_sponsor_names) (void)utf8_to_original(value); + for (const auto& value : state_.television_sponsor_names) (void)utf8_to_original(value); + for (const auto& value : state_.spending_labels) (void)utf8_to_original(value); + for (size_t i = 0; i < state_.spending.size(); ++i) { + const auto& view = state_.spending[i]; + if (view.manager != state_.manager_slot || view.target_slot != 16 + int(i)) + throw FormatError("advertising screen: invalid spending projection identity"); + } + for (size_t i = 0; i < state_.offers.size(); ++i) { + const auto& view = state_.offers[i]; + if (view.display_slot != int(i) || view.manager != state_.manager_slot || view.offers.empty()) + throw FormatError("advertising screen: invalid Original offer projection"); + if (view.contract_slot < 0 || view.contract_slot > 15 || + view.contract_bytes.size() != 12 || view.offers.size() != (i == 15 ? 5u : 10u)) + throw FormatError("advertising screen: malformed Original offer list"); + } + std::array seen{}; + const auto validate_contract = [](const AdvertisingContract& value, int slot) { + if (value.record_slot != slot || value.active != (value.monthly_amount != 0) || + (value.active && (value.sponsor_id < 0 || value.sponsor_id >= 10 || value.sponsor_name.empty()))) + throw FormatError("advertising screen: invalid owned contract identity"); + (void)utf8_to_original(value.sponsor_name); + (void)utf8_to_original(value.amount_text); + }; + for (const auto& value : state_.boards) { + if (value.record_slot < 0 || value.record_slot >= kBoardCount || seen[size_t(value.record_slot)]) + throw FormatError("advertising screen: duplicate or invalid board identity"); + seen[size_t(value.record_slot)] = true; + validate_contract(value, value.record_slot); + } + validate_contract(state_.shirt, 14); + validate_contract(state_.television, 15); +} + +void AdvertisingScreen::text(Image& image, int x, int baseline, std::string_view value, + uint8_t color, int max_width, bool use_gradient) const { + std::string bytes; + try { bytes = utf8_to_original(value); } + catch (const FormatError&) { + for (unsigned char c : value) bytes += c < 128 ? char(c) : '?'; + } + while (!bytes.empty() && font_.text_width(bytes) > max_width) bytes.pop_back(); + const int top = baseline - font_.baseline; + if (x < 0 || top < 0 || x + font_.text_width(bytes) > image.width || + top + font_.height > image.height) return; + if (!use_gradient || !state_.font_gradient || exe_.u8(::bmh::layout::TextGradientMode) != 2 || color == 0x40) { + font_.draw(image, x, top, bytes, color); + return; + } + // DrawnFirstBy -> Mask: preserve the FNT3 mask and fill each + // foreground scanline with the EXE lookup color; no shadow for param7=-1. + unsigned slot = 0; + while (slot < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + slot) != color) ++slot; + int pen_x = x; + for (unsigned char ch : bytes) { + const auto& glyph = font_.glyph(ch); + for (int row = 0; row < font_.height; ++row) { + const uint8_t ink = exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + slot * 6 + row); + if (!ink) continue; + for (int col = 0; col < glyph.bit_width; ++col) { + const int bit = glyph.bit_offset + col; + if (font_.bitmap[size_t(row) * font_.modulo + bit / 8] & (0x80 >> (bit % 8))) { + const int px = pen_x + col; + if (px >= 0 && px < image.width) image.at(px, top + row) = ink; + } + } + } + pen_x += glyph.advance; + } +} + +Image AdvertisingScreen::render() const { + Image image = state_.decorated_background ? desktop_ : Image(320, 240); + if (!state_.decorated_background) { + fill_rect(image, 0, 4, 320, 13, 0x44); + fill_rect(image, 1, 5, 318, 11, 0x39); + fill_rect(image, 0, 228, 320, 10, 0x44); + fill_rect(image, 1, 229, 318, 8, 0x39); + } + // CheckAdvertisingRenewal draws KB/4.VGA's 320x53 slot strip from source (0,0x90) to (0,0x13). + copy(image, art_, 0, 0x90, 0, 0x13, 0x140, 0x35); + // CheckAdvertisingRenewal restores the five fixed art panels from KB/4.VGA. + for (uint32_t i = 0; i < 5; ++i) + copy(image, art_, exe_.u8(::bmh::layout::Advertising_Render_RuntimeField5 + i), exe_.u8(::bmh::layout::Advertising_Render_RuntimeField6 + i), + exe_.u16(::bmh::layout::Advertising_Render_RuntimeField + i * 2), exe_.u16(::bmh::layout::Advertising_Render_RuntimeField2 + i * 2), + exe_.u16(::bmh::layout::Advertising_Render_RuntimeField3 + i * 2), exe_.u16(::bmh::layout::Advertising_Render_RuntimeField4 + i * 2)); + + // LoadGameEndTaxAnimationAssets draws its original panel from KB/56.VGA, or palette 0x42 + // when SolidPanelBackground is set. Border is retained through the original crop. + if (state_.original_panel) { + copy(image, panel_, 82, 130, 83, 150, 231, 73); + } else { + fill_rect(image, 82, 149, 232, 74, 0x42); + } + // PaintsFourBorderEdges orders left, top, bottom, right; the later dark edges + // overwrite their shared corners, including (82,223). + for (int y = 149; y <= 223; ++y) image.at(82, y) = 0x46; + for (int x = 82; x <= 314; ++x) image.at(x, 149) = 0x46; + for (int x = 82; x <= 314; ++x) image.at(x, 223) = 0x40; + for (int y = 149; y <= 223; ++y) image.at(314, y) = 0x40; + + const auto brand = [&](const AdvertisingContract& contract, bool television) + -> std::optional> { + if (!contract.active) return std::nullopt; + const int sx = television ? 32 : 0; + const int sy = contract.sponsor_id * 22; + if (sx + 32 <= logos_.width && sy + 22 <= logos_.height) + return std::pair{sx, sy}; + throw FormatError("advertising screen: sponsor logo outside KB/34.VGA"); + }; + const auto& exe = exe_; + for (int i = 0; i < kBoardCount; ++i) { + const auto& contract = state_.boards[size_t(i)]; + const int x = exe.u16(::bmh::layout::Advertising_Click_RuntimeField3 + uint32_t(i) * 2); + const int y = exe.u16(::bmh::layout::Advertising_Click_RuntimeField4 + uint32_t(i) * 2); + const int width = exe.u16(::bmh::layout::Advertising_Click_RuntimeField5 + uint32_t(i) * 2); + const int height = exe.u16(::bmh::layout::Advertising_Click_RuntimeField6 + uint32_t(i) * 2); + if (contract.active) { + const auto logo = brand(contract, false).value(); + copy(image, logos_, logo.first, logo.second, x, y, std::min(32, width), std::min(22, height)); + } else { + fill_rect(image, x, y, width, height, 0x57); // OriginalFinancePreview2: empty slot color + } + } + + // Lower source panels are distinct original layouts for jersey and TV rights. + // Their locations/asset crops are kept out of the board-index hitbox API because + // clicks there originally enter negotiation rather than merely select a record. + if (state_.shirt.active) { + const int id = state_.shirt.sponsor_id; + const int sx = id <= 2 ? 32 : 71; + const int sy = id <= 2 ? 0x6e + id * 0x1f : (id - 3) * 0x1f; + copy(image, logos_, sx, sy, exe.u16(::bmh::layout::Advertising_FormatError_RuntimeField), exe.u16(::bmh::layout::Advertising_FormatError_RuntimeField3), 36, 26); + } + if (state_.television.active) { + const auto logo = brand(state_.television, true).value(); + copy(image, logos_, logo.first, logo.second, exe.u16(::bmh::layout::Advertising_FormatError_RuntimeField2), exe.u16(::bmh::layout::Advertising_FormatError_RuntimeField4), 31, 22); + } + + // PlainWindowFrameUsedBy: Mode 5 for both title and managed club, restoring Mode 3 afterwards. + sprite_font_.draw(image, SpriteFont::centered_title_x(sprite_font_.text_width(state_.title)), 13, state_.title); + sprite_font_.draw(image, 5, 235, state_.club_name); + + // AdvertisingFromGame centers between the Original hitbox edges. Its index16 + // weeks label sits at y+16; currency labels 17/18 sit at y+8. + for (size_t i = 0; i < state_.auxiliary_text.size(); ++i) { + if (state_.auxiliary_text[i].empty()) continue; + const uint32_t at = uint32_t(16 + i) * 2; + const int left = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField3 + at), width = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField5 + at); + const auto bytes = utf8_to_original(state_.auxiliary_text[i]); + text(image, left + width / 2 - font_.text_width(bytes) / 2, + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField4 + at) + (i == 0 ? 16 : 8), state_.auxiliary_text[i], + i == 0 ? 0x5f : 0x6c, width); + } + + text(image, 95, 214, state_.finance_labels[0], 0x6c); + text(image, 137, 214, exe_.cstring(::bmh::layout::Advertising_FormatError_TextPointer), 0x6b); + text(image, 95, 222, state_.finance_labels[1], 0x6c); + text(image, 137, 222, exe_.cstring(::bmh::layout::Advertising_FormatError_TextPointer), 0x6b); + text(image, 219, 218, state_.finance_labels[2], 0x6c); + + // Utf8ToOriginal/Utf8ToOriginal2 right-align 0x188-formatted amounts to x=198 + // at baselines 214/222; the balance starts at x=254, baseline 218. + const auto draw_finance = [&](std::string_view value, int right, int baseline) { + std::string bytes; + try { bytes = utf8_to_original(value); } + catch (const FormatError&) { for (unsigned char c : value) bytes += c < 128 ? char(c) : '?'; } + text(image, right - font_.text_width(bytes), baseline, value, 0x6b, 198); + }; + draw_finance(state_.finance_preview.income_text, 198, 214); + draw_finance(state_.finance_preview.expenses_text, 198, 222); + text(image, 254, 218, state_.finance_preview.balance_text, 0x6b, 64); + + if (selected_contract_ >= 0) { + const auto& contract = selected_contract_ < kBoardCount + ? state_.boards[size_t(selected_contract_)] + : selected_contract_ == 14 ? state_.shirt : state_.television; + if (selected_contract_ < 16) { + const int i = selected_contract_; + rectangle(image, exe.u16(::bmh::layout::Advertising_Click_RuntimeField3 + uint32_t(i) * 2), exe.u16(::bmh::layout::Advertising_Click_RuntimeField4 + uint32_t(i) * 2), + exe.u16(::bmh::layout::Advertising_Click_RuntimeField5 + uint32_t(i) * 2), exe.u16(::bmh::layout::Advertising_Click_RuntimeField6 + uint32_t(i) * 2), 0x27); + } + const auto& offer_list = state_.offers[size_t(selected_contract_)]; + const bmh::AdvertisingOfferCandidate* offer = nullptr; + if (offer_open_ && selected_offer_ >= 0) + for (const auto& candidate : offer_list.offers) + if (candidate.raw_slot == selected_offer_) { offer = &candidate; break; } + const bool show_offer = offer && offer->present && offer->monthly_amount != 0; + const bool show_contract = !offer_open_ && contract.active; + int sponsor_id = show_offer ? int(offer->sponsor_id) : contract.sponsor_id; + std::string sponsor_name = show_offer + ? ((offer_list.pool_group == 2 ? state_.television_sponsor_names : state_.board_sponsor_names) + [size_t(std::clamp(sponsor_id, 0, 9))]) + : contract.sponsor_name; + if (show_offer || show_contract) { + text(image, 156, 159, sponsor_name, 0x5f, 154); + if (sponsor_id >= 0 && sponsor_id < 10) { + const int sx = offer_list.pool_group == 2 ? 32 : 0; + const int sy = sponsor_id * 22; + rectangle(image, 101, 160, 34, 24, 0x75); + copy(image, logos_, sx, sy, 102, 161, 32, 22); + if (offer_open_) rectangle(image, 101, 160, 34, 24, 0x27); + } + const int months = show_offer ? int(offer->months) : int(contract.months_remaining); + const uint8_t extension = show_offer ? uint8_t(offer->bytes[6] & 0x7f) : + uint8_t(contract.bytes[6] & 0x7f); + const std::string duration_value = original_to_utf8(exe_.cstring(::bmh::layout::Advertising_FormatError_ExecutableField)) + + original_two_digit(months) + + (extension != 0 ? original_to_utf8(exe_.cstring(::bmh::layout::Advertising_FormatError_ExecutableField2)) + + original_two_digit(months + extension) + : std::string()) + state_.month_suffix + + ((months > 1 || extension != 0) ? original_to_utf8(exe_.cstring(::bmh::layout::Advertising_String_ExecutableField)) : std::string()); + text(image, 156, 169, state_.duration_label, 0x6c, 34); + text(image, 191, 169, duration_value, 0x6c, 100); + if (offer_list.pool_group == 0) { + int board_count = show_offer ? int(offer->bundle_units) : 0; + if (show_contract) { + const uint8_t group_id = contract.bytes[4]; + for (const auto& board : state_.boards) + if (board.active && board.bytes[4] == group_id) ++board_count; + } + text(image, 156, 177, state_.boards_label, 0x6c, 34); + text(image, 191, 177, original_to_utf8(exe_.cstring(::bmh::layout::Advertising_FormatError_ExecutableField)) + original_two_digit(board_count), 0x6c, 100); + } + text(image, 156, 185, show_offer ? state_.offer_label : state_.bonus_label, 0x6c, 34); + text(image, 191, 185, original_to_utf8(exe_.cstring(::bmh::layout::Advertising_FormatError_ExecutableField)) + (show_offer + ? state_.offer_amount_text[size_t(selected_contract_)][size_t(selected_offer_)] + : contract.amount_text), 0x6c, 100); + if (!offer_open_ && contract.active && contract.months_remaining == 0 && + contract.extension_months != 0) + text(image, 275, 169, state_.option_label, 0x6c, 39); + else if (!offer_open_ && contract.active && contract.option_marker) + text(image, 275, 169, state_.terminable_label, 0x6c, 39); + } else if (offer_open_) { + text(image, 156, 169, state_.no_offer_text, 0x6c, 154); + if (offer && offer->sponsor_id < 10) { + const auto& names = offer_list.pool_group == 2 ? state_.television_sponsor_names : state_.board_sponsor_names; + text(image, 156, 159, names[offer->sponsor_id], 0x5f, 154); + copy(image, logos_, offer_list.pool_group == 2 ? 32 : 0, + int(offer->sponsor_id) * 22, 102, 161, 32, 22); + rectangle(image, 101, 160, 34, 24, 0x27); + } + } else if (!contract.active) { + text(image, 156, 169, state_.space_available_text, 0x6c, 154); + } + if (offer_open_) { + // OriginalFinancePreview3 copies the two original raw-slot arrows from KB/34.VGA. + copy(image, logos_, 32, 203, 138, 158, 11, 14); + + copy(image, logos_, 32, 217, 138, 174, 11, 14); + + button(image, 89, 191, 66, state_.cancel_label); + button(image, 164, 191, 66, state_.accept_label); + } + } + if (selected_spending_slot_ >= 16 && selected_spending_slot_ <= 18) { + const uint32_t i = uint32_t(selected_spending_slot_); + rectangle(image, exe_.u16(::bmh::layout::Advertising_Click_RuntimeField3 + i * 2), exe_.u16(::bmh::layout::Advertising_Click_RuntimeField4 + i * 2), + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField5 + i * 2), exe_.u16(::bmh::layout::Advertising_Click_RuntimeField6 + i * 2), 0x27); + } + if (spending_calculator_open_ && spending_backdrop_) image = *spending_backdrop_; + if (notification_open()) draw_notification(image); + else if (spending_calculator_open_) draw_spending_calculator(image); + return image; +} + +void AdvertisingScreen::button(Image& image, int x, int y, int width, std::string_view label) const { + // FormatError3's normal KB/0 bevel. Source promotes any wide button shorter + // than ten pixels to a ten-pixel button before tiling its centre. + constexpr int height = 10; + copy(image, widgets_, 24, 74, x, y, 31, height); + int used = 31; + while (width - used > 20) { + const int count = std::min(8, width - used - 20); + copy(image, widgets_, 24, 84, x + used, y, count, height); + used += count; + } + copy(image, widgets_, 45 - (width - used), 94, x + used, y, width - used, height); + if (!label.empty()) + sprite_font_.draw(image, x + width / 2 - sprite_font_.text_width(label) / 2, y + 7, + label, exe_.u8(::bmh::layout::Advertising_Button_RuntimeField)); +} + +void AdvertisingScreen::pattern_rect(Image& out, int x, int y, int width, int height) const { + for (int yy = 0; yy < height; ++yy) + for (int xx = 0; xx < width; ++xx) + out.at(x + xx, y + yy) = exe_.u8(::bmh::layout::Advertising_PatternRect_RuntimeField + size_t(yy & 15) * 16 + size_t(xx & 15)); +} + +void AdvertisingScreen::source_frame(Image& out, int x, int y, int width, int height, bool shadow) const { + if (shadow) { fill_rect(out, x + 2, y + height, width, 2, 0x40); fill_rect(out, x + width, y + 2, 2, height, 0x40); } + pattern_rect(out, x + 4, y + 4, width - 7, height - 7); + copy(out, widgets_, 0, 0, x, y, 4, 4); + copy(out, widgets_, 4, 0, x + width - 4, y, 4, 4); + copy(out, widgets_, 0, 4, x, y + height - 4, 4, 4); + copy(out, widgets_, 4, 4, x + width - 4, y + height - 4, 4, 4); + for (int at = 4; at < width - 4; at += 74) { + const int n = std::min(74, width - 4 - at); + copy(out, widgets_, 0, 104, x + at, y, n, 4); + copy(out, widgets_, 0, 108, x + at, y + height - 4, n, 4); + } + for (int at = 4; at < height - 4; at += 96) { + const int n = std::min(96, height - 4 - at); + copy(out, widgets_, 0, 8, x, y + at, 4, n); + copy(out, widgets_, 4, 8, x + width - 4, y + at, 4, n); + } +} + +void AdvertisingScreen::draw_spending_calculator(Image& out) const { + constexpr int x0 = 103, y0 = 55; + if (calculator_.width < 113 || calculator_.height < 150) return; + copy(out, calculator_, 0, 0, x0, y0, 113, 136); + fill_rect(out, x0 + 113, y0 + 2, 2, 136, 0x40); + fill_rect(out, x0 + 2, y0 + 136, 113, 2, 0x40); + const std::string& title = selected_spending_slot_ == 16 ? state_.merchandise_calculator_title : + state_.budget_calculator_title; + const std::string bytes = utf8_to_original(title); + const int title_width = font_.text_width(bytes); + text(out, x0 + 8 + (0x69 - 8) / 2 - title_width / 2, y0 + 14, title, 98, 98); + constexpr std::string_view keys = "0123456789DRCJN"; + for (int i = 0; i < 15; ++i) { + const int x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); + const int y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + copy(out, calculator_, 0, 136, x, y, 15, 14); + // Render calls the raw font renderer for key legends. + text(out, x + 5, y + 9, keys.substr(size_t(i), 1), 98, 15, false); + } + for (int i = 0; i < 8; ++i) { + const int x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i + 15) * 2); + const int y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i + 15)); + const std::string value = original_grouped_number(spending_presets_[size_t(i)]); + text(out, x + 47 - font_.text_width(utf8_to_original(value)), y + 12, value, 98, 53); + } + const std::string value = original_grouped_number(spending_input_); + text(out, x0 + 106 - font_.text_width(utf8_to_original(value)), y0 + 110, value, 0, 57); +} + +void AdvertisingScreen::draw_notification(Image& out) const { + TaxDialogProjection notice; + notice.manager_name=utf8_to_original(state_.manager_name); + notice.portrait=state_.manager_portrait; + notice.badge_sprite=state_.badge_sprite; + notice.badge_fallback=source_badge_fallback(state_.runtime_team_id); + notice.body=utf8_to_original(state_.notification_text); + notice.source_manager_flags=state_.notification_warning?0x40:0x80; + draw_source_dialog(out,{widgets_,faces_,badge_atlas_?&*badge_atlas_:nullptr, + font_,large_font_,exe_,sprite_font_,texts_},notice,state_.font_gradient); +} + +bool AdvertisingScreen::dismiss_notification() { + if (!notification_open()) return false; + notification_dismissed_ = true; + return true; +} + +void AdvertisingScreen::open_spending_calculator(int display_slot) { + if (display_slot < 16 || display_slot > 18) return; + const auto& view = state_.spending[size_t(display_slot - 16)]; + selected_spending_slot_ = display_slot; + if (!view.available) { + // Source reports the merchandise-delivery gate with its campaign + // notice. Other invalid projections have no evidenced user message. + if (display_slot == 16 && view.delivery_weeks != 0 && !state_.spending_blocked_text.empty()) { + state_.notification_text = state_.spending_blocked_text; + state_.notification_warning = true; + notification_dismissed_ = false; + } + return; + } + spending_maximum_ = view.maximum_amount; + // The original calculator's maximum-key path clamps a legacy stored value + // above the allowed range when it opens (BalanceFromGame). + spending_input_ = std::min(view.current_amount, spending_maximum_); + spending_initial_ = spending_input_; + if (display_slot == 16) { + for (size_t i = 0; i < 6; ++i) spending_presets_[i] = 50000u * uint32_t(i + 1); + } else { + for (size_t i = 0; i < 6; ++i) spending_presets_[i] = 5000u * uint32_t(i + 1); + } + spending_presets_[6] = 0; + spending_presets_[7] = view.maximum_amount; + spending_backdrop_ = render(); + spending_calculator_open_ = true; +} + +void AdvertisingScreen::close_spending_calculator() { + spending_calculator_open_ = false; + spending_backdrop_.reset(); +} + +bool AdvertisingScreen::accept_spending_calculator() { + if (!spending_calculator_open_ || pending_ || selected_spending_slot_ < 16 || selected_spending_slot_ > 18) + return false; + const auto& view = state_.spending[size_t(selected_spending_slot_ - 16)]; + if (!view.available || spending_input_ > spending_maximum_) return false; + if ((selected_spending_slot_ == 16 && spending_input_ == 0) || + (selected_spending_slot_ != 16 && spending_input_ == view.current_amount)) { + close_spending_calculator(); + return true; + } + if (next_request_id_ == 0 || next_request_id_ == UINT64_MAX) + throw FormatError("advertising: UI request id exhausted"); + AdvertisingRequest request; + request.request_id = next_request_id_++; + request.manager_slot = state_.manager_slot; + request.runtime_club = state_.runtime_team_id; + request.revision = state_.revision; + request.kind = AdvertisingActionKind::set_spending; + request.spending.manager = state_.manager_slot; + request.spending.target_slot = selected_spending_slot_; + request.spending.amount = spending_input_; + request.spending.expected_amount = view.current_amount; + request.spending.expected_delivery_weeks = view.delivery_weeks; + pending_ = request; + return true; +} + +bool AdvertisingScreen::text(std::string_view input) { + if (!spending_calculator_open_ || pending_) return false; + bool changed = false; + for (char c : input) { + if (c == '\b' || c == 127) { + spending_input_ /= 10; changed = true; + } else if (c >= '0' && c <= '9') { + const uint64_t digit = uint64_t(c - '0'); + spending_input_ = uint32_t(std::min(spending_maximum_, + uint64_t(spending_input_) * 10 + digit)); + changed = true; + } + } + return changed; +} + +void AdvertisingScreen::begin_offer_browser(int display_slot) { + selected_contract_ = display_slot; + offer_open_ = true; + selected_offer_ = -1; + const auto& offers = state_.offers[size_t(display_slot)].offers; + uint32_t highest = 0; + for (auto it = offers.rbegin(); it != offers.rend(); ++it) { + if (it->present && it->monthly_amount > highest) { + highest = it->monthly_amount; + selected_offer_ = it->raw_slot; + } + } + feedback_.clear(); +} + +bool AdvertisingScreen::open_offers(int display_slot) { + if (display_slot < 0 || display_slot >= 16 || pending_ || close_requested_) return false; + if (state_.offers[size_t(display_slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension) + return false; + const auto& offers = state_.offers[size_t(display_slot)].offers; + const bool any_offer = std::any_of(offers.begin(), offers.end(), [](const auto& candidate) { + return candidate.present && candidate.monthly_amount != 0; + }); + if (!any_offer) return false; + begin_offer_browser(display_slot); + return true; +} + +void AdvertisingScreen::submit_selected_offer() { + if (pending_ || !offer_open_ || selected_contract_ < 0 || selected_contract_ >= 16 || selected_offer_ < 0) + return; + const auto& view = state_.offers[size_t(selected_contract_)]; + const auto candidate = std::find_if(view.offers.begin(), view.offers.end(), [&](const auto& value) { + return value.raw_slot == selected_offer_; + }); + if (candidate == view.offers.end() || !candidate->present || !candidate->can_accept || + candidate->monthly_amount == 0 || view.contract_slot < 0 || view.contract_slot >= 16) return; + if (next_request_id_ == 0 || next_request_id_ == UINT64_MAX) + throw FormatError("advertising: UI request id exhausted"); + bmh::AdvertisingOfferRequest core; + core.manager = state_.manager_slot; + core.display_slot = selected_contract_; + core.contract_slot = view.contract_slot; + core.expected_contract = view.contract_bytes; + core.raw_slot = selected_offer_; + core.expected_offer = candidate->bytes; + AdvertisingRequest request; + request.request_id = next_request_id_++; + request.manager_slot = state_.manager_slot; + request.runtime_club = state_.runtime_team_id; + request.revision = state_.revision; + request.kind = AdvertisingActionKind::accept_offer; + request.offer = core; + pending_ = request; +} + +bool AdvertisingScreen::reject_action(std::string reason) { + if (!pending_ || reason.empty()) return false; + (void)utf8_to_original(reason); + if (pending_->kind == AdvertisingActionKind::set_spending) close_spending_calculator(); + pending_.reset(); + feedback_ = std::move(reason); + return true; +} + +bool AdvertisingScreen::click(int x, int y) { + if (close_requested_ || pending_ || x < 0 || y < 0 || x >= 320 || y >= 240) return false; + if (notification_open()) return dismiss_notification(); + if (spending_calculator_open_) { + constexpr int x0 = 103, y0 = 55; + for (int i = 0; i < 15; ++i) { + const int key_x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); + const int key_y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + if (x < key_x || x >= key_x + 16 || y < key_y || y >= key_y + 14) continue; + if (i < 10) return text(std::string(1, char('0' + i))); + if (i == 10) { spending_input_ /= 10; return true; } + if (i == 11) { spending_input_ = spending_initial_; return true; } + if (i == 12) { spending_input_ = 0; return true; } + if (i == 13) return accept_spending_calculator(); + if (i == 14) { close_spending_calculator(); return true; } + } + for (int i = 0; i < 8; ++i) { + const int preset_x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i + 15) * 2); + const int preset_y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i + 15)); + if (x >= preset_x && x < preset_x + 53 && y >= preset_y && y < preset_y + 14) { + spending_input_ = spending_presets_[size_t(i)]; + return true; + } + } + return false; + } + if (offer_open_) { + if (x >= 89 && x <= 154 && y >= 191 && y <= 200) { + offer_open_ = false; + selected_offer_ = -1; + feedback_.clear(); + return true; + } + if (x >= 164 && x <= 229 && y >= 191 && y <= 200) { + submit_selected_offer(); + return pending_.has_value(); + } + const int max_raw = state_.offers[size_t(selected_contract_)].pool_group == 2 ? 4 : 9; + if (x >= 137 && x <= 150) { + if (y >= 158 && y <= 171 && selected_offer_ > 0) { --selected_offer_; return true; } + if (y >= 174 && y <= 187 && selected_offer_ >= 0 && selected_offer_ < max_raw) { + ++selected_offer_; return true; + } + } + return false; + } + for (int i = 0; i < 16; ++i) { + const int left = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField3 + uint32_t(i) * 2); + const int top = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField4 + uint32_t(i) * 2); + const int right = left + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField5 + uint32_t(i) * 2); + const int bottom = top + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField6 + uint32_t(i) * 2); + if (x >= left && x < right && y >= top && y < bottom) { + const auto& projected = state_.offers[size_t(i)]; + const bool renewal_due = projected.contract_slot >= 0 && projected.contract_slot < 16 && + (projected.contract_bytes[6] & 0x7f) != 0 && projected.contract_bytes[5] == 0; + if (renewal_due) { + if (next_request_id_ == 0 || next_request_id_ == UINT64_MAX) + throw FormatError("advertising: UI request id exhausted"); + AdvertisingRequest request; + request.request_id = next_request_id_++; + request.manager_slot = state_.manager_slot; + request.runtime_club = state_.runtime_team_id; + request.revision = state_.revision; + request.kind = AdvertisingActionKind::check_renewal; + request.renewal_display_slot = i; + request.renewal_contract_slot = projected.contract_slot; + request.renewal_expected_contract = projected.contract_bytes; + pending_ = request; + } else if (!open_offers(i)) { + selected_contract_ = i; + selected_offer_ = -1; + offer_open_ = false; + } + return true; + } + } + for (int i = 16; i <= 18; ++i) { + const int left = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField3 + uint32_t(i) * 2); + const int top = exe_.u16(::bmh::layout::Advertising_Click_RuntimeField4 + uint32_t(i) * 2); + const int right = left + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField5 + uint32_t(i) * 2); + const int bottom = top + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField6 + uint32_t(i) * 2); + if (x >= left && x < right && y >= top && y < bottom) { + selected_contract_ = -1; + selected_spending_slot_ = i; + open_spending_calculator(i); + return true; + } + } + return false; +} + +bool AdvertisingScreen::key(std::string_view value) { + if (close_requested_ || pending_) return false; + if (notification_open()) { + if (value == "ENTER" || value == "ESC" || value == "KLICK") return dismiss_notification(); + return false; + } + if (spending_calculator_open_) { + if (value == "ENTER" || value == "J") return accept_spending_calculator(); + if (value == "ESC" || value == "N") { close_spending_calculator(); return true; } + if (value == "D" || value == "BACKSPACE") { spending_input_ /= 10; return true; } + if (value == "R") { spending_input_ = spending_initial_; return true; } + if (value == "C" || value == "CLEAR" || value == "SPACE") { spending_input_ = 0; return true; } + return text(value); + } + if (value == "ESC") { + if (offer_open_) { offer_open_ = false; selected_offer_ = -1; return true; } + close_requested_ = true; + return true; + } + return false; +} + +std::string AdvertisingScreen::state_json() const { + std::string result = advertising_state_json(state_, selected_contract_, close_requested_, selected_offer_, offer_open_); + if (!result.empty() && result.back() == '}') result.pop_back(); + result += ",\"spending_calculator_open\":" + + std::string(spending_calculator_open_ ? "true" : "false") + + ",\"selected_spending_slot\":" + std::to_string(selected_spending_slot_) + + ",\"spending_input\":" + std::to_string(spending_input_) + + ",\"notification_open\":" + std::string(notification_open() ? "true" : "false"); + result += ",\"pending_action\":"; + if (!pending_) result += "null"; + else { + const auto& req = *pending_; + result += "{\"request_id\":" + std::to_string(req.request_id) + + ",\"manager_slot\":" + std::to_string(req.manager_slot) + + ",\"runtime_club\":" + std::to_string(req.runtime_club) + + ",\"revision\":" + std::to_string(req.revision) + + ",\"kind\":" + std::to_string(unsigned(req.kind)); + if (req.kind == AdvertisingActionKind::check_renewal) { + result += ",\"display_slot\":" + std::to_string(req.renewal_display_slot) + + ",\"contract_slot\":" + std::to_string(req.renewal_contract_slot); + } else if (req.kind == AdvertisingActionKind::set_spending) { + result += ",\"target_slot\":" + std::to_string(req.spending.target_slot) + + ",\"amount\":" + std::to_string(req.spending.amount) + + ",\"expected_amount\":" + std::to_string(req.spending.expected_amount) + + ",\"expected_delivery_weeks\":" + std::to_string(req.spending.expected_delivery_weeks); + } else { + result += ",\"display_slot\":" + std::to_string(req.offer.display_slot) + + ",\"contract_slot\":" + std::to_string(req.offer.contract_slot) + + ",\"raw_slot\":" + std::to_string(req.offer.raw_slot); + } + result += '}'; + } + result += ",\"feedback\":" + (feedback_.empty() ? std::string("null") : json_quote(feedback_)) + '}'; + return result; +} + +} // namespace bmh::ui diff --git a/src/ui/advertising.hpp b/src/ui/advertising.hpp new file mode 100644 index 0000000..5a81fed --- /dev/null +++ b/src/ui/advertising.hpp @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/desk_actions.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh { struct GameState; } + +namespace bmh::ui { + +struct AdvertisingContract { + int record_slot = -1; // manager record +0xa34 + slot*0x0c + int sponsor_id = -1; // contract byte +7; indexes the original TEXTD/logo set + std::string sponsor_name; // owned UTF-8, from the matching TEXTD pointer table + std::string amount_text; // original FormatNumber(0x101) currency formatting, owned UTF-8 + int32_t monthly_amount = 0; // contract dword +0 + uint8_t months_remaining = 0; // byte +5 + uint8_t extension_months = 0; // byte +6, low seven bits + bool option_marker = false; // byte +6, high bit (shown by OriginalFinancePreview3) + bool active = false; + std::array bytes{}; +}; + +struct AdvertisingFinancePreview { + int32_t income = 0; // FinanceTotalsFromGame3(0), exact Original preview formula + int32_t expenses = 0; // OriginalFinancePreview(0), exact Original preview formula + int32_t balance = 0; // income - expenses, OriginalFinancePreview2 + std::string income_text; // FormatNumber(..., 0x188, AdvertisingRuntimeField2), owned UTF-8 + std::string expenses_text; + std::string balance_text; +}; + +// Read-only Source monthly preview shared by statistics page 5. +AdvertisingFinancePreview original_finance_preview(const bmh::GameState&, int manager); + +struct AdvertisingState { + int manager_slot = -1; + int runtime_team_id = -1; + uint64_t revision = 0; + std::string club_name; // owned UTF-8 + std::string title; // original TEXTD title (Werbung) + std::string manager_name; + int manager_portrait = -1; + int badge_sprite = -1; + std::string notification_text; + std::string notification_ack_label; + std::string spending_blocked_text; + std::string spending_funds_text; + bool notification_warning = false; + bool original_panel = true; // SolidPanelBackground clear selects KB/56 panel art + bool decorated_background = true; // PlainBackground clear selects KB/129 + bool font_gradient = true; // TextGradientDisabled clear selects six-row FNT3 foreground + std::vector boards; // visible order after AdBoardOrder (14 boards) + AdvertisingContract shirt; // contract slot 14, manual: Trikotwerbung + AdvertisingContract television; // contract slot 15, manual: TV-Rechte + AdvertisingFinancePreview finance_preview; + std::array finance_labels; // TEXTD Advertising_FormatError_TextPointer16/ae288/ae28c + std::array auxiliary_text; // AdvertisingFromGame, hitboxes 16..18 + std::array offers; + std::array spending; + std::array spending_labels; + std::string merchandise_calculator_title, budget_calculator_title; + std::array board_sponsor_names; + std::array television_sponsor_names; + std::array, 16> offer_amount_text; + std::string duration_label, month_suffix, option_label, terminable_label, boards_label; + std::string offer_label, bonus_label, per_month_suffix, no_offer_text, space_available_text; + std::string cancel_label, accept_label; +}; + +AdvertisingState advertising_from_game(const bmh::GameState&, int manager_slot, uint64_t revision = 0); +std::string advertising_state_json(const AdvertisingState&, int selected_contract = -1, + bool close_requested = false, int selected_offer = -1, + bool offer_open = false); + +enum class AdvertisingActionKind : uint8_t { accept_offer, set_spending, check_renewal }; + +struct AdvertisingRequest { + uint64_t request_id = 0; + int manager_slot = -1; + int runtime_club = -1; + uint64_t revision = 0; + AdvertisingActionKind kind = AdvertisingActionKind::accept_offer; + bmh::AdvertisingOfferRequest offer; + bmh::AdvertisingSpendingRequest spending; + int renewal_display_slot = -1; + int renewal_contract_slot = -1; + std::array renewal_expected_contract{}; + bool operator==(const AdvertisingRequest&) const = default; +}; + +class AdvertisingScreen { +public: + AdvertisingScreen(const std::filesystem::path& data, AdvertisingState state, + uint64_t request_id_seed = 1); + Image render() const; + bool click(int x, int y); + bool key(std::string_view key); + bool open_offers(int display_slot); + bool text(std::string_view input); + const std::optional& pending() const { return pending_; } + bool reject_action(std::string reason); + int selected_contract() const { return selected_contract_; } + int selected_offer() const { return selected_offer_; } + bool offer_open() const { return offer_open_; } + bool spending_calculator_open() const { return spending_calculator_open_; } + bool timed_notice_open() const { return notification_open() && state_.notification_warning; } + bool expire_timed_notice() { return timed_notice_open() && dismiss_notification(); } + bool notification_open() const { return !state_.notification_text.empty() && !notification_dismissed_; } + int selected_spending_slot() const { return selected_spending_slot_; } + uint32_t spending_input() const { return spending_input_; } + bool close_requested() const { return close_requested_; } + std::string state_json() const; +private: + AdvertisingState state_; + LeImage exe_; + TextDb texts_; + Font font_; + Font large_font_; + SpriteFont sprite_font_; + Image desktop_, art_, logos_, panel_; + Image widgets_; + Image calculator_; + Image faces_; + std::optional badge_atlas_; + std::optional spending_backdrop_; + int selected_contract_ = -1; + int selected_spending_slot_ = -1; + int selected_offer_ = -1; + uint64_t next_request_id_ = 1; + bool offer_open_ = false; + bool spending_calculator_open_ = false; + bool notification_dismissed_ = false; + bool close_requested_ = false; + uint32_t spending_input_ = 0; + uint32_t spending_initial_ = 0; + uint32_t spending_maximum_ = 0; + std::array spending_presets_{}; + std::string feedback_; + std::optional pending_; + void text(Image&, int x, int baseline, std::string_view, uint8_t color, + int max_width = 310, bool use_gradient = true) const; + void begin_offer_browser(int display_slot); + void submit_selected_offer(); + void open_spending_calculator(int display_slot); + bool accept_spending_calculator(); + void close_spending_calculator(); + bool dismiss_notification(); + void draw_spending_calculator(Image&) const; + void draw_notification(Image&) const; + void pattern_rect(Image&, int x, int y, int width, int height) const; + void source_frame(Image&, int x, int y, int width, int height, bool shadow = true) const; + void button(Image&, int x, int y, int width, std::string_view label) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/advertising_tests.cpp b/src/ui/advertising_tests.cpp new file mode 100644 index 0000000..6e2a5d1 --- /dev/null +++ b/src/ui/advertising_tests.cpp @@ -0,0 +1,474 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/advertising.hpp" +#include "ui/source_notice_test_helpers.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "app/career_session.hpp" +#include "formats/textd.hpp" +#include "game/messages.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +using namespace bmh; +using namespace bmh::ui; + +namespace { +void check(bool ok, const char* message) { + if (!ok) throw std::runtime_error(message); +} +void rejected(const std::function& action) { + try { action(); } catch (const FormatError&) { return; } + throw std::runtime_error("expected invalid advertising projection rejection"); +} +void put32(std::vector& bytes, size_t at, uint32_t value) { + for (int i = 0; i < 4; ++i) bytes.at(at + size_t(i)) = uint8_t(value >> (8 * i)); +} +void set_contract(GameState& game, int slot, uint32_t amount, uint8_t months, + uint8_t flags, uint8_t sponsor) { + const size_t at = 0xa34 + size_t(slot) * 0xc; + put32(game.manager_records, at, amount); + game.manager_records.at(at + 5) = months; + game.manager_records.at(at + 6) = flags; + game.manager_records.at(at + 7) = sponsor; +} +void set_offer(GameState& game, int group, int raw_slot, uint32_t amount, + uint8_t bundle, uint8_t months, uint8_t sponsor) { + const size_t at = 0x8cc + size_t(group) * 0x78 + size_t(raw_slot) * 0x0c; + put32(game.manager_records, at, amount); + game.manager_records.at(at + 4) = bundle; + game.manager_records.at(at + 5) = months; + game.manager_records.at(at + 7) = sponsor; +} +} + +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: ui_advertising_tests "); + const std::filesystem::path data(argv[1]); + app::CareerSession session(data, 9941); + SetupOptions options; + ManagerChoice choice; + choice.name = "SIM"; + choice.master_club = 0; + choice.strength = 2; + std::string error; + check(session.confirm_manager(options, choice, error), "engine manager setup failed"); + CareerInitializationResult initialized; + check(session.finish(initialized, error), "engine career initialization failed"); + GameState game = session.state(); + check(game.manager_records.size() >= 0xb0c && game.manager_teams.size() == 1, + "initialized manager record is available"); + + set_contract(game, 0, 25000, 12, 0, 0); + set_contract(game, 1, 8000, 7, 0x80, 1); + set_contract(game, 14, 5000, 10, 0x03, 2); + set_contract(game, 15, 12000, 11, 0x80, 3); + const auto records_before = game.manager_records; + const auto state = advertising_from_game(game, 0); + check(state.boards.size() == 14 && state.boards[0].record_slot == 0 && + state.boards[0].monthly_amount == 25000 && state.boards[0].sponsor_id == 0 && + state.boards[0].amount_text == original_to_utf8(format_number(game, 25000, 0x108)), + "the source ordering keeps regular active board deals ahead of options"); + check(state.boards[1].record_slot == 1 && state.boards[1].option_marker && + state.boards[1].months_remaining == 7, + "board contract flags and remaining months are projected without reinterpretation"); + check(state.shirt.record_slot == 14 && state.shirt.monthly_amount == 5000 && + state.shirt.extension_months == 3 && state.television.record_slot == 15 && + state.television.monthly_amount == 12000, + "shirt and TV contract groups use the two source-supported extra surface records"); + check(state.boards[0].sponsor_name == original_to_utf8(message_text(game, ::bmh::layout::Advertising_FormatError_ExecutableField3)) && + state.television.sponsor_name == original_to_utf8(message_text(game, ::bmh::layout::Advertising_FormatError_ExecutableField3 + 13 * 4)), + "sponsor labels resolve through the matching TEXTD pointer table"); + check(game.manager_records == records_before, + "projection reads advertising fields without changing the game record"); + check(state.finance_preview.balance == state.finance_preview.income - state.finance_preview.expenses, + "the owned financial preview follows the exact Original income-minus-expenses relationship"); + check(state.finance_preview.income_text == original_to_utf8( + format_number(game, state.finance_preview.income, 0x88) + " EU.") && + state.finance_preview.expenses_text == original_to_utf8( + format_number(game, state.finance_preview.expenses, 0x88) + " EU.") && + state.finance_preview.balance_text == original_to_utf8( + format_number(game, state.finance_preview.balance, 0x88) + " EU."), + "finance display strings use the Original 0x188 formatter and format field suffix"); + + // Controlled source fixture: zero all finance/ownership inputs, leave the + // 14 always-charged facility costs, and one 1,234 EU advertising contract. + GameState finance_fixture = game; + const size_t rec = 0; + for (int i = 0; i < 6; ++i) finance_fixture.manager_records[size_t(i)] = 0; + for (int i = 0x3c; i < 0x44; ++i) finance_fixture.manager_records[size_t(i)] = 0; + for (int i = 0; i < 16; ++i) put32(finance_fixture.manager_records, 0xa34 + size_t(i) * 0xc, 0); + put32(finance_fixture.manager_records, rec + 0x314, 0); + put32(finance_fixture.manager_records, rec + 0x318, 0); + put32(finance_fixture.manager_records, rec + 0x31c, 0); + put32(finance_fixture.manager_records, rec + 0x854, 0); + put32(finance_fixture.manager_records, rec + 0x858, 0); + put32(finance_fixture.manager_records, rec + 0x880, 0); + finance_fixture.manager_records.at(rec + 0x179) = 0; + put32(finance_fixture.manager_records, rec + 0x290, uint32_t(game.manager_teams[0])); + set_contract(finance_fixture, 0, 1234, 1, 0, 0); + for (size_t slot = 0; slot < 24; ++slot) + finance_fixture.tactics[slot * 0x58 + 0x3d] = 0xff; + finance_fixture.memory.set8(::bmh::layout::ManagerCount, 1); + for (int i = 0; i < 6; ++i) { + finance_fixture.memory.set32(::bmh::layout::FundBlock + uint32_t(i) * 0x1c, 0); + finance_fixture.memory.set16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(i) * 0x1c, 0); + finance_fixture.memory.set32(::bmh::layout::Spending + uint32_t(i) * 4, 0); + } + for (uint32_t at = ::bmh::layout::Loans; at < ::bmh::layout::FixtureAdvertisingWorkspaceEnd; ++at) + if (finance_fixture.memory.has(at)) finance_fixture.memory.set8(at, 0); + const auto finance_record_before = finance_fixture.manager_records; + const auto finance_tactics_before = finance_fixture.tactics; + auto finance_memory = [](const GameState& value) { + std::vector bytes; + for (const auto [first, last] : {std::pair{::bmh::layout::FundBlock,::bmh::layout::FixtureAdvertisingRatingsEnd}, + {::bmh::layout::Spending,::bmh::layout::FixtureAdvertisingCountersEnd}, {::bmh::layout::Loans,::bmh::layout::FixtureAdvertisingWorkspaceEnd}}) + for (uint32_t address = first; address < last; ++address) + if (value.memory.has(address)) bytes.push_back(value.memory.u8(address)); + return bytes; + }; + const auto finance_memory_before = finance_memory(finance_fixture); + const auto preview = advertising_from_game(finance_fixture, 0).finance_preview; + check(preview.income == 1234 && preview.expenses == 43400 && preview.balance == -42166, + "a controlled fixture matches Original contract income, fixed facility costs, and negative balance"); + check(finance_fixture.manager_records == finance_record_before && + finance_fixture.tactics == finance_tactics_before && finance_fixture.date == game.date && + finance_memory(finance_fixture) == finance_memory_before, + "the financial projection is readonly across records, board, date, and source cost/share blocks"); + GameState shares_fixture = finance_fixture; + shares_fixture.memory.set32(::bmh::layout::FundBlock, 10000); + shares_fixture.memory.set16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField, 2); + check(advertising_from_game(shares_fixture, 0).finance_preview.income == 1264, + "share income uses the saved share count and the Original 1.5-EU unit factor"); + GameState multi_share_fixture = finance_fixture; + multi_share_fixture.memory.set32(::bmh::layout::FundBlock, 10000); + multi_share_fixture.memory.set16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField, 2); // 15 EU * 2 + multi_share_fixture.memory.set32(::bmh::layout::FundBlock + 0x1c, 20000); + multi_share_fixture.memory.set16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + 0x1c, 3); // 36 EU * 3 + multi_share_fixture.memory.set32(::bmh::layout::FundBlock + 5 * 0x1c, 10000); + multi_share_fixture.memory.set16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + 5 * 0x1c, 2); // 30 EU * 2 + check(advertising_from_game(multi_share_fixture, 0).finance_preview.income == 1432, + "all six legacy routine rows use their 0x1c-byte record stride"); + GameState interest_fixture = shares_fixture; + interest_fixture.date = 0; // July; source day table factor 31. + put32(interest_fixture.manager_records, 0x314, 3650000); + check(advertising_from_game(interest_fixture, 0).finance_preview.income == 4364, + "the Original param-0 balance interest is projected with the current month-length factor"); + GameState cap_fixture = finance_fixture; + cap_fixture.memory.set32(::bmh::layout::Spending + 4, 99); + cap_fixture.memory.set32(::bmh::layout::Spending, 111); + cap_fixture.memory.set32(::bmh::layout::Spending + 8, 222); + check(advertising_from_game(cap_fixture, 0).finance_preview.expenses == 1543400, + "costs 0/2 stay zero while the youth-cost item uses the source league cap"); + put32(cap_fixture.manager_records, 0x880, 1500000); + const auto no_cap_preview = advertising_from_game(cap_fixture, 0).finance_preview; + check(no_cap_preview.expenses == 43400, + "the youth-cost item is suppressed once funds reach the strict source threshold"); + GameState ignored_cost_fixture = finance_fixture; + ignored_cost_fixture.memory.set32(::bmh::layout::Spending, 111); + ignored_cost_fixture.memory.set32(::bmh::layout::Spending + 8, 222); + check(advertising_from_game(ignored_cost_fixture, 0).finance_preview.expenses == 43400, + "legacy routine clears cost items zero and two regardless of their saved values"); + GameState loan_fixture = finance_fixture; + loan_fixture.memory.set32(::bmh::layout::Loans + 8, 100); + const auto loan_preview = advertising_from_game(loan_fixture, 0).finance_preview; + check(loan_preview.expenses == 43500, + "the Original preview adds the outstanding-share repayment to expenses"); + GameState min_loan_fixture = finance_fixture; + min_loan_fixture.memory.set32(::bmh::layout::Loans + 8, 0x80000000u); + check(advertising_from_game(min_loan_fixture, 0).finance_preview.expenses == 0, + "share repayment negation wraps definedly at INT_MIN before the Original zero clamp"); + GameState min_finance_fixture = finance_fixture; + put32(min_finance_fixture.manager_records, 0x314, 0x80000000u); + put32(min_finance_fixture.manager_records, 0x318, 0x80000000u); + put32(min_finance_fixture.manager_records, 0x31c, 0x80000000u); + (void)advertising_from_game(min_finance_fixture, 0); + const auto preview_json = advertising_state_json(advertising_from_game(finance_fixture, 0)); + check(preview_json.find("\"finance_preview\":{\"income\":1234,\"expenses\":43400,\"balance\":-42166") != std::string::npos && + preview_json.find("\"income_text\":") != std::string::npos, + "the owned UI report exposes original preview totals without creating actions"); + GameState invalid_manager_count = finance_fixture; + invalid_manager_count.memory.set8(::bmh::layout::ManagerCount, 5); + rejected([&] { (void)advertising_from_game(invalid_manager_count, 0); }); + + // Independent wrap example: 1234 * INT_MAX wraps to -1234, then /2. + GameState currency_fixture = finance_fixture; + currency_fixture.memory.add_block(::bmh::layout::CurrencyMultiplier, 8); + currency_fixture.memory.set32(::bmh::layout::CurrencyMultiplier, 0x7fffffffu); + currency_fixture.memory.set32(::bmh::layout::CurrencyDivisor, 2); + put32(currency_fixture.manager_records, 0x854, 4); + const auto currency_state = advertising_from_game(currency_fixture, 0); + check(currency_state.finance_preview.income_text == + original_to_utf8(format_number(currency_fixture, -617, 0x88) + " EU.") && + currency_state.boards[0].amount_text == + original_to_utf8(format_number(currency_fixture, -617, 0x08) + " EU") && + currency_state.auxiliary_text[1] == + original_to_utf8(format_number(currency_fixture, -2, 0x81) + " EU."), + "currency conversion preserves Original signed wrap in totals, contracts and spending bars"); + currency_fixture.memory.set32(::bmh::layout::CurrencyDivisor, 0); + rejected([&] { (void)advertising_from_game(currency_fixture, 0); }); + currency_fixture.memory.set32(::bmh::layout::CurrencyMultiplier, 0x80000000u); + currency_fixture.memory.set32(::bmh::layout::CurrencyDivisor, 0xffffffffu); + set_contract(currency_fixture, 0, 1235, 1, 0, 0); + rejected([&] { (void)advertising_from_game(currency_fixture, 0); }); + + GameState tied = game; + for (int slot = 0; slot < 14; ++slot) + set_contract(tied, slot, 25000, 12, 0, uint8_t(slot % 10)); + const auto tied_records = tied.manager_records; + const auto tied_state = advertising_from_game(tied, 0); + constexpr std::array source_tie_order{9, 7, 8, 12, 13, 10, 11, + 2, 0, 1, 5, 6, 3, 4}; + for (size_t i = 0; i < source_tie_order.size(); ++i) + check(tied_state.boards[i].record_slot == source_tie_order[i], + "equal keys follow the Original midpoint-partition swap order"); + check(tied.manager_records == tied_records, + "Original ordering rearranges only the owned projection, not manager records"); + + auto invalid_manager = [&] { (void)advertising_from_game(game, -1); }; + rejected(invalid_manager); + GameState invalid = game; + invalid.manager_records[0xa34 + 7] = 0xff; + rejected([&] { (void)advertising_from_game(invalid, 0); }); + + AdvertisingScreen screen(data, state); + auto duplicate = state; + duplicate.boards[1].record_slot = duplicate.boards[0].record_slot; + rejected([&] { AdvertisingScreen invalid(data, duplicate); }); + auto corrupt = state; + corrupt.shirt.sponsor_id = 10; + rejected([&] { AdvertisingScreen invalid(data, corrupt); }); + corrupt = state; + corrupt.television.record_slot = 14; + rejected([&] { AdvertisingScreen invalid(data, corrupt); }); + auto invalid_text = state; + invalid_text.finance_labels[0] = std::string(1, char(0xff)); + rejected([&] { AdvertisingScreen bad(data, invalid_text); }); + invalid_text = state; + invalid_text.finance_preview.income_text = std::string(1, char(0xff)); + rejected([&] { AdvertisingScreen bad(data, invalid_text); }); + invalid_text = state; + invalid_text.auxiliary_text[1] = std::string(1, char(0xff)); + rejected([&] { AdvertisingScreen bad(data, invalid_text); }); + const auto first = screen.render(); + check(first.width == 320 && first.height == 240 && first.pixels == screen.render().pixels, + "original-asset advertising view renders deterministically at native resolution"); + const auto exe = load_le(asset_path(data, "BMH.exe")); + const auto art = load_vga(asset_path(data / "KB", "4.VGA")); + const auto logos = load_vga(asset_path(data / "KB", "34.VGA")); + auto pixel = [](const Image& image, int x, int y) { return image.pixels[size_t(y) * image.width + x]; }; + check(pixel(first, 0, 19) == pixel(art, 0, 0x90), + "the upper sponsor-board strip is cropped from KB/4 at legacy routine coordinates"); + auto plain_state = state; + plain_state.decorated_background = false; + AdvertisingScreen plain(data, plain_state); + const auto plain_image = plain.render(); + check(pixel(plain_image, 0, 4) == 0x44 && pixel(plain_image, 1, 5) == 0x39 && + pixel(plain_image, 0, 228) == 0x44 && pixel(plain_image, 1, 229) == 0x39 && + pixel(plain_image, 319, 239) == 0, + "plain_background uses the Original plain header/footer instead of KB129"); + for (int y = 0; y < 22; ++y) + for (int x = 0; x < 32; ++x) + check(pixel(first, exe.u16(::bmh::layout::Advertising_Click_RuntimeField3) + x, exe.u16(::bmh::layout::Advertising_Click_RuntimeField4) + y) == + pixel(logos, x, y), + "active board logos use the original KB/34 partner sprite and hitbox coordinates"); + check(screen.click(exe.u16(::bmh::layout::Advertising_Click_RuntimeField3) + 1, exe.u16(::bmh::layout::Advertising_Click_RuntimeField4) + 1) && + screen.selected_contract() == 0, + "a board click selects a local read-only details panel"); + const auto selected_json = screen.state_json(); + check(selected_json.find("\"selected_contract\":0") != std::string::npos && + selected_json.find(state.club_name) != std::string::npos, + "owned screen state retains selection and UTF-8 club text"); + check(!screen.click(319, 239) && screen.selected_contract() == 0, + "unsupported areas do not create an action request or clear the local selection"); + if (screen.offer_open()) { + check(screen.key("ESC") && !screen.close_requested() && !screen.offer_open() && + screen.key("ESC") && screen.close_requested() && !screen.key("LEFT"), + "ESC closes an existing offer browser before the screen"); + } else { + check(screen.key("ESC") && screen.close_requested() && !screen.key("LEFT"), + "without a saved offer, ESC closes the contract details directly"); + } + + // Existing saved offer pool: raw slot 5 is the highest amount, but an + // empty lower raw slot remains an explicit stop when paging backward. + GameState offer_game = game; + for (size_t i = 0; i < 10 * 0x0c; ++i) offer_game.manager_records[0x8cc + i] = 0; + set_offer(offer_game, 0, 0, 8000, 1, 24, 1); + set_offer(offer_game, 0, 5, 10904, 1, 24, 2); + const auto offer_records_before = offer_game.manager_records; + const auto offer_state = advertising_from_game(offer_game, 0, 41); + check(offer_state.offers[0].offers.size() == 10 && + offer_state.offers[0].offers[5].present && + offer_state.offers[0].offers[5].monthly_amount == 10904 && + offer_state.offers[0].offers[5].can_accept, + "the owned view projects a saved raw-pool offer without generating one"); + check(offer_game.manager_records == offer_records_before, + "offer projection leaves manager contracts and raw pool bytes unchanged"); + AdvertisingScreen offers(data, offer_state, 0x200000001ULL); + const bool opened = offers.open_offers(0); + check(opened && offers.offer_open() && offers.selected_offer() == 5, + "opening the source offer browser selects the highest saved raw offer"); + check(offers.click(140, 164) && offers.selected_offer() == 4 && + !offers.click(190, 195) && !offers.pending(), + "an empty raw slot cannot create an acceptance request"); + check(offers.click(140, 164) && offers.selected_offer() == 3, + "raw-slot browsing steps across empty rows without skipping them"); + check(offers.click(140, 180) && offers.selected_offer() == 4 && + offers.click(140, 180) && offers.selected_offer() == 5, + "the opposite source control returns through the same raw slots"); + for (int i = 0; i < 5; ++i) check(offers.click(140, 164), "page raw slot toward zero"); + check(offers.selected_offer() == 0 && !offers.click(140, 164) && offers.selected_offer() == 0, + "raw-slot navigation does not underflow below slot zero"); + for (int i = 0; i < 5; ++i) check(offers.click(140, 180), "restore selected raw slot"); + check(offers.selected_offer() == 5, "selected raw slot is restored before submission"); + check(offers.click(190, 195) && offers.pending().has_value(), + "accept creates a request envelope rather than mutating GameState"); + const auto request = *offers.pending(); + check(request.request_id == 0x200000001ULL && request.manager_slot == 0 && + request.runtime_club == offer_state.runtime_team_id && request.revision == 41 && + request.offer.manager == 0 && request.offer.display_slot == 0 && + request.offer.contract_slot == offer_state.offers[0].contract_slot && + request.offer.raw_slot == 5 && + request.offer.expected_contract == offer_state.offers[0].contract_bytes && + request.offer.expected_offer == offer_state.offers[0].offers[5].bytes, + "request binds manager, revision, visible/physical row, raw slot and full byte identities"); + check(offer_game.manager_records == offer_records_before && !offers.click(190, 195), + "pending request cannot be replayed by clicking and has no engine-side write"); + check(offers.reject_action("veraltete Ansicht") && !offers.pending() && + offers.state_json().find("veraltete Ansicht") != std::string::npos, + "controller rejection clears the pending request and exposes owned feedback"); + check(offers.click(110, 195) && !offers.offer_open() && offers.key("ESC") && + offers.close_requested(), + "cancel closes the offer browser first; a second ESC closes the screen"); + + // The three source spending controls open the original calculator. All + // editing remains local; only J/Enter on a changed value creates a + // manager/revision-bound request for the app controller. + GameState spending_game = game; + put32(spending_game.manager_records, 0x850, 0); + put32(spending_game.manager_records, 0x854, 10000); + put32(spending_game.manager_records, 0x858, 15000); + spending_game.manager_records.at(0x287) = 0; + const auto spending_records = spending_game.manager_records; + const auto spending_state = advertising_from_game(spending_game, 0, 73); + check(spending_state.spending[0].target_slot == 16 && spending_state.spending[0].available && + spending_state.spending[0].maximum_amount == 350000 && + spending_state.spending[1].target_slot == 17 && spending_state.spending[1].current_amount == 10000 && + spending_state.spending[1].maximum_amount == 35000 && + spending_state.spending[2].current_amount == 15000, + "the three read-only spend projections use the source record values and limits"); + check(spending_state.notification_ack_label == original_to_utf8(message_text(spending_game, ::bmh::layout::Advertising_FormatError_TextPointer17)), + "the Original manager modal button label resolves from its actual EXE text pointer"); + AdvertisingScreen merchandise(data, spending_state, 0x300000001ULL); + const int merchandise_x = exe.u16(::bmh::layout::Advertising_Click_RuntimeField3 + 16 * 2) + 1; + const int merchandise_y = exe.u16(::bmh::layout::Advertising_Click_RuntimeField4 + 16 * 2) + 1; + check(merchandise.click(merchandise_x, merchandise_y) && merchandise.spending_calculator_open() && + merchandise.selected_spending_slot() == 16 && merchandise.spending_input() == 0, + "the original merchandise hitbox opens its calculator with the saved value"); + const auto calculator_art = load_vga(asset_path(data / "KB", "6.VGA")); + const auto calculator_image = merchandise.render(); + check(calculator_image.pixels[size_t(55) * 320 + 103] == calculator_art.pixels[0], + "the calculator opens over the original advertising screen using KB/6 at source coordinates"); + check(merchandise.text("200000") && merchandise.spending_input() == 200000 && + merchandise.key("ENTER") && merchandise.pending().has_value(), + "calculator text entry and Enter create one merchandise request"); + const auto spend_request = *merchandise.pending(); + check(spend_request.kind == AdvertisingActionKind::set_spending && + spend_request.request_id == 0x300000001ULL && spend_request.manager_slot == 0 && + spend_request.runtime_club == spending_state.runtime_team_id && spend_request.revision == 73 && + spend_request.spending.manager == 0 && spend_request.spending.target_slot == 16 && + spend_request.spending.amount == 200000 && spend_request.spending.expected_amount == 0 && + spend_request.spending.expected_delivery_weeks == 0, + "merchandise request carries manager, revision, target, chosen amount and stale guards"); + check(spending_game.manager_records == spending_records && + !merchandise.text("1") && !merchandise.key("ESC") && + !merchandise.click(merchandise_x, merchandise_y), + "editing/request display is read-only and a pending request cannot be changed or replayed"); + check(merchandise.reject_action("veraltete Ansicht") && !merchandise.pending() && + !merchandise.spending_calculator_open(), + "a controller rejection clears the request and dismisses the calculator"); + + AdvertisingScreen clamped_input(data, spending_state); + check(clamped_input.click(merchandise_x, merchandise_y) && clamped_input.text("9999999") && + clamped_input.spending_input() == 350000 && clamped_input.key("SPACE") && + clamped_input.spending_input() == 0 && clamped_input.key("ESC") && !clamped_input.pending(), + "typed digits clamp at the source maximum and SPACE clears the calculator without booking"); + + AdvertisingScreen unchanged_budget(data, spending_state, 0x300000010ULL); + const int budget_x = exe.u16(::bmh::layout::Advertising_Click_RuntimeField3 + 17 * 2) + 1; + const int budget_y = exe.u16(::bmh::layout::Advertising_Click_RuntimeField4 + 17 * 2) + 1; + check(unchanged_budget.click(budget_x, budget_y) && unchanged_budget.spending_calculator_open() && + unchanged_budget.spending_input() == 10000 && unchanged_budget.key("J") && + !unchanged_budget.pending() && !unchanged_budget.spending_calculator_open(), + "accepting an unchanged monthly budget closes locally without an engine request"); + + AdvertisingScreen preset_budget(data, spending_state, 0x300000018ULL); + const int preset0_x = 103 + exe.u16(::bmh::layout::Advertising_Click_RuntimeField + 15 * 2); + const int preset0_y = 55 + exe.u8(::bmh::layout::Advertising_Click_RuntimeField2 + 15); + check(preset_budget.click(budget_x, budget_y) && + preset_budget.click(preset0_x + 2, preset0_y + 2) && + preset_budget.spending_input() == 5000 && preset_budget.key("J") && + preset_budget.pending() && preset_budget.pending()->spending.amount == 5000 && + preset_budget.pending()->spending.expected_amount == 10000, + "the first monthly-budget preset uses the original executable hitbox and value"); + + AdvertisingScreen clear_budget(data, spending_state, 0x300000020ULL); + check(clear_budget.click(budget_x, budget_y) && clear_budget.key("C") && + clear_budget.spending_input() == 0 && clear_budget.key("J") && clear_budget.pending() && + clear_budget.pending()->spending.target_slot == 17 && clear_budget.pending()->spending.amount == 0 && + clear_budget.pending()->spending.expected_amount == 10000, + "clearing a monthly budget creates a request bound to the previous amount"); + + AdvertisingScreen empty_merchandise(data, spending_state, 0x300000030ULL); + check(empty_merchandise.click(merchandise_x, merchandise_y) && empty_merchandise.key("C") && + empty_merchandise.key("J") && !empty_merchandise.pending() && + !empty_merchandise.spending_calculator_open(), + "zero merchandise spending is a local no-op and does not ask the engine to purchase"); + + GameState delivery_pending = spending_game; + delivery_pending.manager_records.at(0x287) = 3; + const auto blocked_state = advertising_from_game(delivery_pending, 0, 74); + check(!blocked_state.spending[0].available && blocked_state.spending[0].delivery_weeks == 3, + "a saved delivery countdown makes the merchandise target unavailable"); + AdvertisingScreen blocked_merchandise(data, blocked_state); + check(blocked_merchandise.click(merchandise_x, merchandise_y) && + blocked_merchandise.notification_open() && !blocked_merchandise.spending_calculator_open() && + blocked_merchandise.state_json().find(blocked_state.spending_blocked_text) != std::string::npos && + blocked_merchandise.click(10, 10) && !blocked_merchandise.notification_open() && + !blocked_merchandise.close_requested(), + "a blocked delivery shows the owned source warning and dismisses without closing the desk"); + AdvertisingScreen timed_merchandise(data,blocked_state); + check(timed_merchandise.click(merchandise_x,merchandise_y)&&timed_merchandise.timed_notice_open(), + "delivery warning uses Source timed mode"); + bmh::ui::test::expect_notice_symbols(timed_merchandise.render(),load_vga(asset_path(data/"KB","0.VGA"))); + check(timed_merchandise.expire_timed_notice()&&!timed_merchandise.notification_open()&& + !timed_merchandise.pending()&&!timed_merchandise.close_requested(),"timed delivery notice expires locally"); + GameState malformed_budget = spending_game; + put32(malformed_budget.manager_records, 0x854, 36000); + const auto malformed_budget_state = advertising_from_game(malformed_budget, 0, 75); + AdvertisingScreen invalid_budget(data, malformed_budget_state); + check(malformed_budget_state.spending[1].available && + malformed_budget_state.spending[1].current_amount == 36000, + "a legacy monthly value above the new maximum remains available to the source calculator"); + check(invalid_budget.click(budget_x, budget_y) && invalid_budget.spending_calculator_open() && + invalid_budget.spending_input() == 35000 && invalid_budget.key("J") && + invalid_budget.pending() && invalid_budget.pending()->spending.amount == 35000 && + invalid_budget.pending()->spending.expected_amount == 36000, + "the calculator's maximum clamps a legacy value and binds its old value in the request"); + std::cout << "Advertising projection, request binding and source offer navigation passed.\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/src/ui/alltime_table.cpp b/src/ui/alltime_table.cpp new file mode 100644 index 0000000..37e5eb2 --- /dev/null +++ b/src/ui/alltime_table.cpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "alltime_table.hpp" +#include +#include "game/table.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" +namespace bmh::ui { namespace { +constexpr uint32_t kFirst=::bmh::layout::First, kLeague=::bmh::layout::AlltimeTable_Layout_ExecutableField; +std::string original_text(const TextDb& t,uint32_t at){if(at<::bmh::layout::TextPointerTable||((at-::bmh::layout::TextPointerTable)&3U))throw FormatError("alltime: invalid TEXTD address");return original_to_utf8(t[(at-::bmh::layout::TextPointerTable)/4]);} +void fill(Image&o,int x,int y,int w,int h,uint8_t c){for(int j=0;js.width||sy+h>s.height||x+w>o.width||y+h>o.height)throw FormatError("alltime: Original asset bounds");for(int j=0;j3; + unsigned separators=0; + if(grouped){for(size_t p=digits.size();p>3;p-=3){digits.insert(p-3,1,'.');++separators;}} + const unsigned groups=grouped?(width-1)/3:0;const unsigned field=width+separators; + if(digits.size()separators)digits.insert(0,groups-separators,' ');return digits; +} +uint8_t team_color(const GameState&g,int team){size_t count=std::min(g.manager_teams.size(),4);int active=g.memory.has(::bmh::layout::ActiveManager)?g.memory.u8(::bmh::layout::ActiveManager):-1;int managers=g.memory.has(::bmh::layout::ManagerCount)?g.memory.u8(::bmh::layout::ManagerCount):int(count);bool current=g.memory.has(::bmh::layout::DeskPosition)&&g.memory.u8(::bmh::layout::DeskPosition)=g.manager_records.size()||g.manager_records[at]==0)continue;if(g.manager_teams[slot]==team)return int(slot)==active&¤t?0x7a:0x75;}if(g.memory.has(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)&&g.memory.u16(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)==team)return 0xf7;return 0x5f;} +void button(Image&out,const Image&a,const SpriteFont&spr,const LeImage&exe,int x,int y,std::string_view label,bool selected){constexpr int width=96,height=10;int dx=x+(selected?2:0),dy=y+(selected?2:0);if(selected){auto bg=out.at(x,y+height);fill(out,x,y,width+1,2,bg);fill(out,x,y,2,height+1,bg);}else{fill(out,x+2,y+height,width-1,2,0x40);fill(out,x+width,y+2,2,height-2,0x40);}int sy=selected?44:74;copy(out,a,24,sy,dx,dy,31,height,0xc0);int used=31;while(width-used>20){int count=std::min(8,width-used-20);copy(out,a,24,sy+height,dx+used,dy,count,height,0xc0);used+=count;}int tail=width-used;copy(out,a,45-tail,sy+2*height,dx+used,dy,tail,height,0xc0);spr.draw(out,dx+width/2-spr.text_width(label)/2,dy+height/2+2,label,exe.u8(::bmh::layout::Advertising_Button_RuntimeField + uint32_t(selected)));} +} +AllTimeTableState alltime_table_from_game(const GameState&g,const LeImage&exe,DeskRequest owner,const Image&underlay,int nation,bool relative){ + if(nation<0||nation>4)throw FormatError("alltime: nation outside 0..4");if(underlay.width!=320||underlay.height!=240)throw FormatError("alltime: parent underlay must be 320x240");AllTimeTableState s;s.owner=owner;s.underlay=underlay;s.nation=nation;s.relative=relative;s.mask=uint8_t((1U<=168)continue;const auto&r=s.records[size_t(team)];int played=int(r.wins)+r.draws+r.losses;if(!played)continue;uint32_t p=r.points,gf=r.goals_for,ga=r.goals_against;if(relative){p=p*full*10U/uint32_t(played);gf=gf*full*10U/uint32_t(played);ga=ga*full*10U/uint32_t(played);}AllTimeRow row;row.team=team;row.played=played;row.points=p;row.goals_for=gf;row.goals_against=ga;row.points_key=p*0x10001U+0x7d000000U;row.goal_key=gf*0x10001U-ga*0x10000U+0x7d000000U;s.rows.push_back(row);}} + std::stable_sort(s.rows.begin(),s.rows.end(),[](const auto&a,const auto&b){if(a.points_key!=b.points_key)return a.points_key>b.points_key;return a.goal_key>b.goal_key;});if(s.rows.size()>24)s.rows.resize(24);return s; +} +AllTimeTableScreen::AllTimeTableScreen(const std::filesystem::path&data,AllTimeTableState s):state_(std::move(s)),data_(data),exe_(load_le(asset_path(data,"BMH.exe"))),font_(load_font(asset_path(data/"F","BMH3.FNT"))),header_(load_font(asset_path(data/"F","BMH2.FNT"))),sprite_(data),window_(load_vga(asset_path(data/"KB","56.VGA"))),buttons_(load_vga(asset_path(data/"KB","0.VGA"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))){if(state_.underlay.width!=320||state_.underlay.height!=240)throw FormatError("alltime: invalid parent frame");} +Image AllTimeTableScreen::render()const{Image out=state_.underlay; + if(state_.has_data){int spacing=state_.rows.size()<15?8:state_.rows.size()>19?6:7;for(size_t i=0;i=bx&&x<=bx+96&&y>=by&&y<=by+10){pressed_=i;return true;}}return false;} +bool AllTimeTableScreen::release(int x,int y){if(pending_)return false;int i=pressed_;pressed_=-1;if(i<0)return false;int bx=12+(i%3)*99,by=177+(i/3)*12;if(xbx+96||yby+10)return true;if(i<5){state_.mask=uint8_t((state_.mask&0x20)^(1U< +#include +#include +#include +#include +#include +#include "formats/le.hpp" +#include "formats/font.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/state.hpp" +#include "ui/desktop.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { +struct AllTimeRecord { uint16_t points=0, goals_for=0, goals_against=0, wins=0, draws=0, losses=0; }; +struct AllTimeRow { int team=-1, played=0; uint32_t points_key=0, goal_key=0; uint32_t points=0, goals_for=0, goals_against=0; }; +struct AllTimeTableState { + DeskRequest owner{}; + Image underlay; + std::vector records; + std::array nation_names{}; + std::array club_names{}; + std::array club_name_colors{}; + std::vector rows; + int nation=0; + uint8_t mask=1; + bool relative=false; + bool has_data=false; +}; +enum class AllTimeRequestKind : uint8_t { none, close, select_nation, toggle_relative }; +struct AllTimeRequest { AllTimeRequestKind kind=AllTimeRequestKind::none; DeskRequest owner{}; int nation=0; bool relative=false; }; +AllTimeTableState alltime_table_from_game(const GameState&, const LeImage&, DeskRequest owner, + const Image& underlay, int nation=0, bool relative=false); +class AllTimeTableScreen { +public: + AllTimeTableScreen(const std::filesystem::path&, AllTimeTableState); + Image render() const; + bool pointer_down(int x,int y,bool right=false); + bool release(int x,int y); + const std::optional& pending() const { return pending_; } + const AllTimeTableState& state() const { return state_; } +private: + AllTimeTableState state_; std::filesystem::path data_; LeImage exe_; Font font_,header_; SpriteFont sprite_; Image window_,buttons_; TextDb texts_; + int pressed_=-1; std::optional pending_; +}; +} diff --git a/src/ui/alltime_table_tests.cpp b/src/ui/alltime_table_tests.cpp new file mode 100644 index 0000000..7864b68 --- /dev/null +++ b/src/ui/alltime_table_tests.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "alltime_table.hpp" +#include "game/table.hpp" +#include "game/messages.hpp" +#include "ui/manager.hpp" +#include +#include +namespace { +void check(bool ok,const char* why){if(!ok)throw std::runtime_error(why);} +void put16(bmh::Bytes& b,uint32_t base,uint32_t a,uint16_t x){b.at(a-base)=uint8_t(x);b.at(a-base+1)=uint8_t(x>>8);} +void rec(bmh::GameState&g,int team,uint16_t points,uint16_t gf,uint16_t ga,uint16_t w,uint16_t d,uint16_t l){size_t p=size_t(team)*0x4a+0x1e;for(auto [o,v]:{std::pair{0,points},std::pair{2,gf},std::pair{4,ga},std::pair{6,w},std::pair{8,d},std::pair{10,l}}){g.club_table[p+o]=uint8_t(v);g.club_table[p+o+1]=uint8_t(v>>8);}} +} +int main(int argc,char**argv){ + constexpr uint32_t base=::bmh::layout::GermanDataSegmentBegin; bmh::Bytes bytes(0x5000);auto set=[&](uint32_t a,uint16_t v){put16(bytes,base,a,v);};bytes[::bmh::layout::AlltimeTable_Layout_ExecutableField-base]=0;set(::bmh::layout::First,0);set(::bmh::layout::AlltimeTable_AlltimeTableFromGame_RuntimeField,4);set(::bmh::layout::FixtureAllTimeAppearanceColumn,4);set(::bmh::layout::FixtureAllTimePointsColumn,4); + auto exe=bmh::LeImage::from_bytes(base,std::move(bytes));bmh::GameState g;g.club_table.resize(168*0x4a);g.club_ids.resize(0x16a);g.club_names={'A',0,'B',0,'C',0,'D',0};g.club_ids[0]=0;g.club_ids[1]=2;g.club_ids[2]=4;g.club_ids[3]=6;g.club_ids[0x165]=0; + rec(g,0,10,8,3,2,1,1);rec(g,1,10,8,3,2,1,1);rec(g,2,11,9,2,3,1,0);rec(g,3,0,0,0,0,0,0); + auto owner=bmh::ui::DeskRequest{};auto abs=bmh::ui::alltime_table_from_game(g,exe,owner,bmh::Image(320,240));check(abs.has_data&&abs.rows.size()==3,"played rows are projected");check(abs.rows[0].team==2,"points order is descending");check(abs.rows[1].team==0&&abs.rows[2].team==1,"ties preserve scan order");check(abs.records[0].points==10,"record points are decoded"); + auto rel=bmh::ui::alltime_table_from_game(g,exe,owner,bmh::Image(320,240),0,true);check(rel.rows.size()==3,"relative rows are projected");check(rel.rows[0].points==uint32_t(11)*bmh::league_matchdays(0)*10/4,"relative points use full season scale");check(rel.rows[0].goals_for==uint32_t(9)*bmh::league_matchdays(0)*10/4,"relative goals use full season scale"); + auto empty=g;empty.club_table.clear();auto absent=bmh::ui::alltime_table_from_game(empty,exe,owner,bmh::Image(320,240));check(!absent.has_data&&absent.rows.empty(),"missing optional table remains empty"); + if(argc>1&&argv[1][0]){ + bmh::ui::AllTimeTableScreen screen(argv[1],abs);auto absolute_frame=screen.render(); + const auto original_exe=bmh::load_le(bmh::ui::asset_path(argv[1],"BMH.exe")); + const auto font=bmh::load_font(bmh::ui::asset_path(std::filesystem::path(argv[1])/"F","BMH3.FNT")); + bmh::ui::AllTimeTableScreen relative_screen(argv[1],rel); + auto relative_frame=relative_screen.render(); + auto expected=rel.underlay; + const auto& first=rel.rows.front();const auto& record=rel.records[size_t(first.team)]; + std::string stats=bmh::format_number(g,first.played,0xc4)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField); + for(auto value:{record.wins,record.draws,record.losses}) + stats+=bmh::format_number(g,value,0x44)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField); + stats+=original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField3); + stats+=bmh::format_number(g,first.points/10,7)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField4)+ + bmh::format_number(g,first.points%10,1)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField5); + stats+=bmh::format_number(g,first.goals_for/10,5)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField4)+ + bmh::format_number(g,first.goals_for%10,1)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField7); + stats+=bmh::format_number(g,first.goals_against/10,3)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField4)+ + bmh::format_number(g,first.goals_against%10,1)+original_exe.cstring(::bmh::layout::AlltimeTable_Render_ExecutableField8); + font.draw(expected,0x67,38-font.baseline,stats,rel.club_name_colors[size_t(first.team)]); + for(int y=38-font.baseline;y<38-font.baseline+font.height;++y) + for(int x=0x67;x<320;++x) + check(relative_frame.at(x,y)==expected.at(x,y), + "relative numeric row preserves Source spaces reserved for unused grouping dots"); + check(!screen.state().relative&&screen.pointer_down(210,189)&&screen.release(210,189),"relative control accepts its Source hitbox"); + check(screen.state().relative&&screen.pending()&&screen.pending()->kind==bmh::ui::AllTimeRequestKind::toggle_relative&&screen.pending()->relative,"relative hit requests relative mode, not absolute"); + check(screen.render().pixels!=absolute_frame.pixels,"toggling relative mode changes the table and selected control rendering"); + std::cout<<"all-time projection and original-renderer checks passed\n"; + }else std::cout<<"all-time projection checks passed; original-renderer check skipped (no BMH_DATA)\n"; +} diff --git a/src/ui/analytics.cpp b/src/ui/analytics.cpp new file mode 100644 index 0000000..d299d52 --- /dev/null +++ b/src/ui/analytics.cpp @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/analytics.hpp" + +#include +#include +#include +#include + +#include "ui/setup.hpp" +#include "ui/manager.hpp" +#include "game/schedule.hpp" + +namespace bmh::ui { +namespace { +constexpr size_t kManagerRecord = 0xb0c; +constexpr size_t kFlags = ::bmh::layout::Flags; +constexpr int kSeriesCount = 6; +constexpr int kSourcePointLimit = 52; // local_1d8[52] in CopyOpaqueSlice. + +uint32_t read32(const std::vector& bytes, size_t at) { + if (at + 3 >= bytes.size()) throw FormatError("analytics: truncated Source manager record"); + return uint32_t(bytes[at]) | uint32_t(bytes[at + 1]) << 8 | + uint32_t(bytes[at + 2]) << 16 | uint32_t(bytes[at + 3]) << 24; +} +uint16_t read16(const std::vector& bytes, size_t at) { + if (at + 1 >= bytes.size()) throw FormatError("analytics: truncated Source word"); + return uint16_t(bytes[at]) | uint16_t(bytes[at + 1]) << 8; +} +int32_t source_asset_mask_1e(const GameState& game, int manager) { + const size_t rec = size_t(manager) * kManagerRecord; + uint32_t sum = read32(game.manager_records, rec + 0x318); // HighscoreScore mask bit 1. + for (uint32_t k = 0; k < 6; ++k) { + const uint32_t quantity = game.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + k * 0x1c); + const uint32_t value = game.memory.u32(::bmh::layout::FundBlock + k * 0x1c); + sum += quantity * value; // bit 2, 32-bit Source arithmetic. + } + for (uint32_t k = 0; k < 12; ++k) { + const size_t at = size_t(k) * 0x5c; + const uint32_t held = read16(game.stocks, at + 0x50 + size_t(manager) * 2); + const uint32_t price = read16(game.stocks, at + 0x4e); + sum += held * price; // bit 3. + } + for (uint32_t k = 0; k < 5; ++k) + sum -= game.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(manager) * 0x78 + k * 0x18); // bit 4. + return int32_t(sum); +} +int source_manager_league(const GameState& game, const LeImage& exe, int manager) { + const int team = game.manager_teams.at(size_t(manager)); + if (team > 0x164) return 0; // TeamLeague2 special-team early return. + int cumulative = 0; + for (int league = 0; league < 9; ++league) { + cumulative += exe.u8(::bmh::layout::LeagueSizes + uint32_t(league)); + if (team < cumulative) return league; + } + return 9; // TeamLeague2 return for the remaining club IDs. +} +void line(Image& out, int x0, int y0, int x1, int y1, uint8_t color) { + const int dx = std::abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + const int dy = std::abs(y1 - y0), sy = y0 < y1 ? 1 : -1; + int err = dx - dy; + for (;;) { + if (x0 >= 0 && x0 < out.width && y0 >= 0 && y0 < out.height) out.at(x0, y0) = color; + if (x0 == x1 && y0 == y1) break; + const int e2 = 2 * err; + if (e2 > -dy) err -= dy, x0 += sx; + if (e2 < dx) err += dx, y0 += sy; + } +} +void copy_opaque_slice(Image& out, const Image& src, int sx, int sy, int dx, int dy, int w, int h) { + if (sx < 0 || sy < 0 || dx < 0 || dy < 0 || sx + w > src.width || sy + h > src.height) + throw FormatError("analytics: Source tab-button slice bounds"); + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { + if (dx + x >= out.width || dy + y >= out.height) continue; + const uint8_t c = src.pixels[size_t(sy + y) * size_t(src.width) + size_t(sx + x)]; + if (c != 0xc0) out.at(dx + x, dy + y) = c; + } +} +} // namespace + +AnalyticsState analytics_from_game(const GameState& game, const LeImage& exe, int manager_slot, + const Image& underlay) { + if (manager_slot < 0 || manager_slot >= 4 || + size_t(manager_slot + 1) * kManagerRecord > game.manager_records.size()) + throw FormatError("analytics: missing manager record"); + if (!game.memory.has(kFlags + size_t(manager_slot) * 3)) + throw FormatError("analytics: missing Source view flags Flags"); + if (underlay.width != 320 || underlay.height != 240) + throw FormatError("analytics: expected accepted 320x240 parent underlay"); + + AnalyticsState out; + out.manager_slot = manager_slot; + out.source_flags = game.memory.u8(uint32_t(kFlags + size_t(manager_slot) * 3)); + out.underlay = underlay; + const size_t rec = size_t(manager_slot) * kManagerRecord; + for (int i = 0; i < kSeriesCount; ++i) { + auto& s = out.series[size_t(i)]; + s.label = exe.string_at_pointer(::bmh::layout::Analytics_FormatError_ExecutableField + uint32_t(i) * 4); + s.color = exe.u8(::bmh::layout::Analytics_FormatError_RuntimeField + uint32_t(i)); + const uint8_t field = exe.u8(::bmh::layout::Analytics_FormatError_RuntimeField2 + uint32_t(i)); + const size_t count_at = rec + 0x283 + field; + if (count_at >= game.manager_records.size()) throw FormatError("analytics: missing Source series count"); + const size_t count = game.manager_records[count_at]; + if (count > kSourcePointLimit) throw FormatError("analytics: Source point count exceeds local_1d8[52]"); + + // CopyOpaqueSlice first uses Analytics_FormatError_RuntimeField2[metric] only to select one of the four + // count bytes at manager-record +0x283..0x286. The data source itself + // is selected by metric index (switch at LAB1f652), not by that count class. + switch (i) { + case 0: // Source case 0: byte series at record +0x248. + for (size_t n = 0; n < count; ++n) s.values.push_back(game.manager_records.at(rec + 0x248 + n)); + break; + case 1: // Source case 1: byte series at +0x222, multiplied by 1000. + for (size_t n = 0; n < count; ++n) s.values.push_back(int32_t(game.manager_records.at(rec + 0x222 + n)) * 1000); + break; + case 2: // Source case 2: byte at +0x270 times corresponding dword +0x340. + for (size_t n = 0; n < count; ++n) + s.values.push_back(int32_t(uint32_t(game.manager_records.at(rec + 0x270 + n)) * + read32(game.manager_records, rec + 0x340 + n * 4))); + break; + case 3: // Source case 3: dword series at +0x4a8. + for (size_t n = 0; n < count; ++n) s.values.push_back(int32_t(read32(game.manager_records, rec + 0x4a8 + n * 4))); + break; + case 4: // Source case 4: dword series at +0x578. + for (size_t n = 0; n < count; ++n) s.values.push_back(int32_t(read32(game.manager_records, rec + 0x578 + n * 4))); + break; + case 5: // Source case 5: dword series at +0x3d8. + for (size_t n = 0; n < count; ++n) s.values.push_back(int32_t(read32(game.manager_records, rec + 0x3d8 + n * 4))); + break; + default: throw FormatError("analytics: unsupported Source metric"); + } + s.absolute_min = int32_t(exe.u32(::bmh::layout::Analytics_FormatError_RuntimeField3 + uint32_t(i) * 4)); + s.absolute_max = int32_t(exe.u32(::bmh::layout::Analytics_FormatError_RuntimeField4 + uint32_t(i) * 4)); + if (s.label.empty()) throw FormatError("analytics: missing Source label"); + } + // CopyOpaqueSlice(param2=0) rewrites exactly Analytics_FormatError_RuntimeField4[0,2,4,5] before drawing. + // Mirror these read-only axis values from the same live owner data; do not + // mutate EXE bytes or draw/random hooks from the renderer. + const int league = source_manager_league(game, exe, manager_slot); + out.series[0].absolute_max = exe.u8(::bmh::layout::LeagueSizes + uint32_t(league)); + out.series[2].absolute_max = int32_t(game.manager_records.at(rec + 0x5c)) * 25000; + const int32_t money = int32_t(read32(game.manager_records, rec + 0x314)); + out.series[4].absolute_max = (money / 1000000 + 1) * 1000000; + const int32_t assets = source_asset_mask_1e(game, manager_slot); + out.series[5].absolute_max = (assets / 1000000 + 1) * 1000000; + return out; +} + +AnalyticsScreen::AnalyticsScreen(const std::filesystem::path& data, AnalyticsState state) + : state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), + buttons_(load_vga(asset_path(data / "KB", "0.VGA"))), sprite_(data), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))) { + if (state_.manager_slot < 0 || state_.manager_slot >= 4 || state_.underlay.width != 320 || + state_.underlay.height != 240 || buttons_.width < 76 || buttons_.height < 84) + throw FormatError("analytics: incomplete Source projection/assets"); +} + +Image AnalyticsScreen::render() const { + Image out = state_.underlay; + // CopyOpaqueSlice draws its four configured graph-frame edges from Analytics_Render_RuntimeField3/Analytics_Render_RuntimeField2. + for (int edge = 0; edge < 4; ++edge) + line(out, exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3 + uint32_t(edge) * 4 + 2), exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 + uint32_t(edge) * 2 + 1), + exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3 + uint32_t(edge) * 4), exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 + uint32_t(edge) * 2), + exe_.u8(::bmh::layout::Analytics_Render_RuntimeField + uint32_t(edge))); + // DrawsLegendSampleBeforeDbChecksEnabled adds each enabled metric's source-colored legend sample. + for (int i = 0; i < kSeriesCount; ++i) { + const auto& s = state_.series[size_t(i)]; + const int tab_x = 27 + (i % 2) * 120, tab_y = 142 + (i / 2) * 11; + // DrawsLegendSampleBeforeDbChecksEnabled draws the legend sample before CopyOpaqueSlice checks the enabled + // flag, so it remains visible even when that metric's curve is off. + for (int y = tab_y + 3; y <= tab_y + 6; ++y) + for (int x = tab_x - 7; x <= tab_x - 3; ++x) + if (x >= 0 && x < out.width && y >= 0 && y < out.height) out.at(x,y)=s.color; + line(out, tab_x - 8, tab_y + 2, tab_x - 2, tab_y + 2, 0x68); + line(out, tab_x - 8, tab_y + 2, tab_x - 8, tab_y + 7, 0x68); + line(out, tab_x - 2, tab_y + 3, tab_x - 2, tab_y + 7, 0x62); + line(out, tab_x - 8, tab_y + 7, tab_x - 2, tab_y + 7, 0x62); + if ((state_.source_flags & (1u << i)) == 0) continue; + const size_t n = s.values.size(); + if (n == 0) continue; + const auto [min_it, max_it] = std::minmax_element(s.values.begin(), s.values.end()); + const int64_t low = (state_.source_flags & 0x40) ? s.absolute_min : *min_it; + const int64_t high = (state_.source_flags & 0x40) ? s.absolute_max : *max_it; + const int64_t range = std::llabs(high - low); + // PlotsEachPointThrough uses max(point_count, 0x22) for case 0 and + // max(point_count, 0x11) for the other Source series cases. Its x + // coordinate is index*0x12a/that_denominator + 0x0d. Keep the + // historical spacing even when a series has only a few observations. + const int source_denominator = int(std::max(n, + exe_.u8(::bmh::layout::Analytics_FormatError_RuntimeField2 + uint32_t(i)) == 0 ? 0x22 : 0x11)); + int px0 = 0, py0 = 0; + for (size_t j = 0; j < n; ++j) { + int height = 41; + if (!(state_.source_flags & 0x40) && high == 0) { + // CopyOpaqueSlice only subtracts min from max when max is nonzero; + // otherwise it writes normalized value 50 for every sample. + height = int((50 * 83 + 50) / 100); + } else if (range != 0) { + // ClampInteger applies its lower bound, then upper bound (even + // when an Original table contains the -1 sentinel maximum). + int64_t v = s.values[j]; + if (v < low) v = low; + if (high < v) v = high; + const int64_t distance = std::llabs(v - low); + if (state_.source_flags & 0x40) + height = int((distance * 83 + range / 2) / range); + else { + const int64_t scaled = distance * 100 / range; + height = int((scaled * 83 + 50) / 100); + } + } + const int x = int(j * 0x12a / source_denominator) + 0x0d; + const int y = 53 + (i == 0 ? height : 83 - height); + if (j != 0) line(out, px0, py0, x, y, s.color); + // PlotsEachPointThrough plots each point through Fill3(x-1,y-1,x+1,y+1), + // a filled inclusive 3x3 marker, not a single pixel. + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + if (x + dx >= 0 && x + dx < out.width && y + dy >= 0 && y + dy < out.height) + out.at(x + dx, y + dy) = s.color; + px0 = x; py0 = y; + } + } + // Original six labels and button hit regions: two columns by three rows, + // as CopyOpaqueSlice advances x by 0x78 then wraps after x>200. + for (int i = 0; i < kSeriesCount; ++i) { + const int x = 27 + (i % 2) * 120, y = 142 + (i / 2) * 11; + const int source_y = (state_.source_flags & (1u << i)) ? 44 : 74; + copy_opaque_slice(out, buttons_, 24, source_y, x, y, 31, 10); + int written = 31; + while (96 - written > 20) { + const int take = std::min(8, 96 - written - 20); + copy_opaque_slice(out, buttons_, 24, source_y + 10, x + written, y, take, 10); + written += take; + } + const int tail = 96 - written; + copy_opaque_slice(out, buttons_, 45 - tail, source_y + 20, x + written, y, tail, 10); + const auto label = original_to_utf8(exe_.string_at_pointer(::bmh::layout::Analytics_FormatError_ExecutableField + uint32_t(i) * 4)); + const int mode = exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + uint32_t((state_.source_flags & (1u << i)) != 0)); + sprite_.draw(out, x + (96 - sprite_.text_width(label)) / 2, y + 7, label, mode); + } + for (int i = 0; i < 2; ++i) { + // Source CopyOpaqueSlice passes x=0x109, y=0x92+4+i*0x0b, + // width=0x1e, height=9 for param2=0. + const int x = 0x109, y = 0x92 + 4 + i * 0x0b; + const int source_y = (state_.source_flags & (1u << (i + 6))) ? 44 : 74; + copy_opaque_slice(out, buttons_, 24, source_y, x, y, 30, 9); + const auto label = original_to_utf8(texts_.strings.at(54 + size_t(i))); + const int mode = exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + uint32_t((state_.source_flags & (1u << (i + 6))) != 0)); + sprite_.draw(out, x + (30 - sprite_.text_width(label)) / 2, y + 7, label, mode); + } + return out; +} + +bool AnalyticsScreen::toggle_metric(int index) { + if (index < 0 || index >= kSeriesCount || pending_) return false; + pending_ = AnalyticsRequest{state_.owner, AnalyticsRequestKind::toggle_metric, + state_.manager_slot, index, state_.source_flags, + uint8_t(state_.source_flags ^ uint8_t(1u << index))}; + return true; +} +bool AnalyticsScreen::click(int x, int y) { + for (int i = 0; i < kSeriesCount; ++i) { + const int bx = 27 + (i % 2) * 120, by = 142 + (i / 2) * 11; + if (x >= bx && x <= bx + 0x60 && y >= by && y <= by + 9) + return toggle_metric(i); + } + // CopyOpaqueSlice passes scale controls at x=0x109, y=0x92+4 and + // y=0x92+4+0x0b, each 30x9. Either original click flips both flags. + if (x >= 0x109 && x <= 0x109 + 0x1e && + ((y >= 0x92 + 4 && y <= 0x92 + 4 + 9) || + (y >= 0x92 + 4 + 0x0b && y <= 0x92 + 4 + 0x0b + 9))) + return toggle_absolute_scale(); + return false; +} +bool AnalyticsScreen::toggle_absolute_scale() { + if (pending_) return false; + pending_ = AnalyticsRequest{state_.owner, AnalyticsRequestKind::toggle_absolute_scale, + state_.manager_slot, -1, state_.source_flags, uint8_t(state_.source_flags ^ 0xc0)}; + return true; +} +bool AnalyticsScreen::pointer_down(int x, int y, bool right) { + if (pending_) return false; + if (right) { + pending_ = AnalyticsRequest{state_.owner, AnalyticsRequestKind::close, + state_.manager_slot, -1, state_.source_flags, state_.source_flags}; + return true; + } + return click(x, y); +} +void AnalyticsScreen::acknowledge(uint8_t accepted_flags, DeskRequest accepted_owner) { + if (!pending_ || accepted_owner != state_.owner || accepted_owner.kind != DeskRequestKind::open_menu || + accepted_owner.menu_kind != 23 || accepted_owner.manager_slot != state_.manager_slot || + (accepted_flags != pending_->expected_flags && accepted_flags != pending_->target_flags)) + throw FormatError("analytics: mismatched accepted Source preference"); + state_.source_flags = accepted_flags; + state_.owner = accepted_owner; + pending_.reset(); +} + +} // namespace bmh::ui diff --git a/src/ui/analytics.hpp b/src/ui/analytics.hpp new file mode 100644 index 0000000..0e772e7 --- /dev/null +++ b/src/ui/analytics.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/state.hpp" +#include "ui/sprite_font.hpp" +#include "ui/desktop.hpp" + +namespace bmh::ui { + +// Case 2 of StatisticsMenuScreen opens CopyOpaqueSlice(board, 0): the German +// “Analytics” page, with six Source series. Values are copied, never simulated. +struct AnalyticsSeries { + std::string label; + uint8_t color = 0; + int32_t absolute_min = 0; + int32_t absolute_max = 0; + std::vector values; + bool operator==(const AnalyticsSeries&) const = default; +}; + +struct AnalyticsState { + DeskRequest owner; + int manager_slot = -1; + uint8_t source_flags = 0; // Flags[manager*3], param2=0. + std::array series; + Image underlay; // supplied by the accepted statistics-parent render. +}; + +enum class AnalyticsRequestKind : uint8_t { toggle_metric, toggle_absolute_scale, close }; +struct AnalyticsRequest { + DeskRequest owner; + AnalyticsRequestKind kind = AnalyticsRequestKind::toggle_metric; + int manager_slot = -1; + int metric = -1; + uint8_t expected_flags = 0; + uint8_t target_flags = 0; + bool operator==(const AnalyticsRequest&) const = default; +}; + +AnalyticsState analytics_from_game(const GameState&, const LeImage&, int manager_slot, + const Image& accepted_parent_underlay); + +class AnalyticsScreen { +public: + AnalyticsScreen(const std::filesystem::path& data, AnalyticsState); + Image render() const; + bool click(int x, int y); + bool pointer_down(int x, int y, bool right = false); + const std::optional& pending() const { return pending_; } + void acknowledge(uint8_t accepted_flags, DeskRequest accepted_owner); + void reject() { pending_.reset(); } + // Local display preference only. The containing owner must persist/ack + // source_flags through its normal statistics-session contract. + bool toggle_metric(int index); + bool toggle_absolute_scale(); + const AnalyticsState& state() const { return state_; } +private: + AnalyticsState state_; + LeImage exe_; + Image buttons_; + SpriteFont sprite_; + TextDb texts_; + std::optional pending_; + int pressed_metric_ = -1; + bool pressed_absolute_ = false; +}; + +} // namespace bmh::ui diff --git a/src/ui/analytics_tests.cpp b/src/ui/analytics_tests.cpp new file mode 100644 index 0000000..d316ba6 --- /dev/null +++ b/src/ui/analytics_tests.cpp @@ -0,0 +1,88 @@ +#include "../../tests/test_inputs.hpp" +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/analytics.hpp" + +#include +#include + +namespace { +void check(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); } +void put32(std::vector& b, size_t at, uint32_t v) { + for (int i = 0; i < 4; ++i) b.at(at + size_t(i)) = uint8_t(v >> (i * 8)); +} +} +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: analytics_tests "); + const std::filesystem::path data(argv[1]); + const auto exe = bmh::load_le(data / "BMH.exe"); + const auto textd = bmh::load_textd(data / "TEXTD.BLK"); + check(textd[65] == "Analytics", "Source statistics index 2 label"); + bmh::GameState game; game.manager_records.assign(4 * 0xb0c, 0); + game.manager_teams = {0, 1, 2, 3}; game.stocks.assign(12 * 0x5c, 0); + game.memory.add_block(::bmh::layout::Flags, 12); game.memory.set8(::bmh::layout::Flags, 0x7f); + game.memory.add_block(::bmh::layout::FundBlock, 6 * 0x1c); + game.memory.add_block(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField, 4 * 0x78); + auto& m = game.manager_records; + m[0x283]=2; m[0x284]=2; m[0x285]=2; m[0x286]=2; m[0x222]=4; m[0x223]=7; + m[0x5c]=2; put32(m,0x314,1'500'000); + m[0x248]=11; m[0x249]=14; m[0x270]=2; m[0x271]=3; + put32(m,0x340,1000); put32(m,0x344,2000); + put32(m,0x4a8,30); put32(m,0x4ac,31); + put32(m,0x578,40); put32(m,0x57c,41); + put32(m,0x3d8,50); put32(m,0x3dc,51); + bmh::ui::DeskRequest owner; owner.kind=bmh::ui::DeskRequestKind::open_menu; + owner.menu_kind=23; owner.manager_slot=0; owner.revision=9; + const bmh::Image underlay(320,240,0x40); + auto state=bmh::ui::analytics_from_game(game,exe,0,underlay); state.owner=owner; + check(state.series[0].label==bmh::test::expected_text("analytics_tests-external-2").c_str() && state.series[1].label==bmh::test::expected_text("analytics_tests-external-1").c_str() && + state.series[2].label==bmh::test::expected_text("analytics_tests-external-3").c_str(), "Original EXE labels"); + check(state.series[0].values==std::vector({11,14}) && + state.series[1].values==std::vector({4000,7000}) && + state.series[2].values==std::vector({2000,6000}) && + state.series[3].values==std::vector({30,31}) && + state.series[4].values==std::vector({40,41}) && + state.series[5].values==std::vector({50,51}), "all six distinct Source manager-record series"); + check(state.series[0].absolute_max==exe.u8(::bmh::layout::LeagueSizes) && + state.series[2].absolute_max==50000 && state.series[4].absolute_max==2000000 && + state.series[5].absolute_max==1000000, "legacy routine live axis maxima"); + auto plot_state=state; plot_state.source_flags=1; + bmh::ui::AnalyticsScreen plot_screen(data,plot_state); const auto plotted=plot_screen.render(); + const uint8_t source_color=plot_state.series[0].color; + auto legend_state=state; legend_state.source_flags=0; + bmh::ui::AnalyticsScreen legend_screen(data,legend_state); + check(legend_screen.render().at(21,145)==legend_state.series[0].color, + "Source legend sample remains visible when the metric is disabled"); + // legacy routine: denominator=max(count,0x22) for source case0, else + // max(count,0x11); legacy routine paints an inclusive 3x3 marker. + const int denominator=std::max(2,exe.u8(::bmh::layout::Analytics_FormatError_RuntimeField2)==0?0x22:0x11); + const int expected_x=13+298/denominator; + for(int y=135;y<=137;++y)for(int x=expected_x-1;x<=expected_x+1;++x) + check(plotted.pixels[size_t(y)*size_t(plotted.width)+size_t(x)]==source_color, + "Source curve x-spacing and 3x3 point marker"); + auto zero_max_state=plot_state; + zero_max_state.series[0].values={-2,0}; + bmh::ui::AnalyticsScreen zero_max_screen(data,zero_max_state); + const auto zero_max_plot=zero_max_screen.render(); + const int zero_max_x=13+298/denominator; + check(zero_max_plot.pixels[size_t(94)*320+13]==source_color && + zero_max_plot.pixels[size_t(94)*320+size_t(zero_max_x)]==source_color, + "Source relative scaling maps every point to 50 when the maximum is zero"); + bmh::ui::AnalyticsScreen screen(data,state); const auto before=screen.render(); + check(screen.pointer_down(30,145),"metric request"); + const auto first=screen.pending(); check(first&&first->target_flags==0x7e,"typed single-metric target"); + check(screen.state().source_flags==0x7f&&screen.render().pixels==before.pixels,"no optimistic preference write"); + screen.acknowledge(first->target_flags,owner); + check(screen.state().source_flags==0x7e&&screen.render().pixels!=before.pixels,"preference changes only after ACK"); + check(screen.pointer_down(270,150),"absolute request"); + const auto second=screen.pending(); check(second&&second->target_flags==0xbe,"paired absolute preference target"); + screen.acknowledge(second->target_flags,owner); + check(screen.state().source_flags==0xbe,"absolute preference ACK"); + check(screen.pointer_down(10,10,true),"typed parent close"); + check(screen.pending()&&screen.pending()->kind==bmh::ui::AnalyticsRequestKind::close, + "one right-click emits typed close"); + std::cout<<"Analytics: Source projection, flags, ACK, and close controls passed\n"; + return 0; + } catch(const std::exception& e) { std::cerr< +#include +#include +#include + +#include "game/messages.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +constexpr uint32_t kTextBase=::bmh::layout::TextPointerTable; +constexpr std::string_view kKeys="0123456789DRCJN"; +std::string_view at(const TextDb& t,uint32_t a){if(a=x0&&x<=x1&&y>=y0&&y<=y1;} +void copy(Image& o,const Image& s,int sx,int sy,int x,int y,int w,int h,int transparent=-1){ + if(sx<0||sy<0||x<0||y<0||w<0||h<0||sx+w>s.width||sy+h>s.height||x+w>o.width||y+h>o.height)throw FormatError("balance: sprite bounds "+std::to_string(sx)+","+std::to_string(sy)+" "+std::to_string(w)+"x"+std::to_string(h)+" source "+std::to_string(s.width)+"x"+std::to_string(s.height)+" dest "+std::to_string(o.width)+"x"+std::to_string(o.height)); + for(int yy=0;yy3||id.manager_slot!=d.manager)throw FormatError("balance: manager identity mismatch"); + BalanceState s;s.identity=id;s.draft=d;s.underlay=underlay;s.club_name=std::string(g.club_name(g.manager_teams.at(size_t(d.manager)))); + s.currency_numerator=g.memory.has(::bmh::layout::CurrencyMultiplier)?g.memory.u32(::bmh::layout::CurrencyMultiplier):exe.u32(::bmh::layout::CurrencyMultiplier);s.currency_denominator=g.memory.has(::bmh::layout::CurrencyDivisor)?g.memory.u32(::bmh::layout::CurrencyDivisor):exe.u32(::bmh::layout::CurrencyDivisor); + for(int row=0;row=0;p.minimum=0;p.maximum=row_max<0?0:uint32_t(row_max);p.initial=uint32_t(std::clamp(d.rows[size_t(row)],0,p.maximum));p.source_text_address=::bmh::layout::BalancePlan_BalanceFromGame_ExecutableField; + uint32_t first=p.maximum/10,step=p.maximum/5; + int64_t first_signed=first;uint32_t advance=step; + if(row==20){ + const size_t rec=size_t(d.manager)*0xb0c;const uint32_t attendance=rec+0x5c1){scale/=10;delta=scale*((value/scale)/10);}first_signed=int64_t(base)-int64_t(3)*delta;advance=delta;}} + } + for(size_t i=0;i<6;++i){first_signed=std::max(0,first_signed);if(uint64_t(first_signed)<=p.maximum)p.presets[i]=uint32_t(first_signed);if(uint64_t(first_signed)>p.maximum)p.presets[i].reset();first_signed+=advance;} + p.presets[6]=0;p.presets[7]=p.maximum; + } + const size_t rec=size_t(d.manager)*0xb0c; + for(size_t n=0;n<30&&rec+0xa8+n14)throw FormatError("balance: invalid Source manager portrait"); + const int team=g.manager_teams[size_t(d.manager)]; + const bool fallback=team==0x0fff||(team>89&&team<138)||(team>167&&team<357); + int badge=0;if(!fallback){if(team<0||size_t(team)*2+2>g.club_heap_78.size())throw FormatError("balance: missing Source badge selector");badge=(int(g.club_heap_78[size_t(team)*2])|int(g.club_heap_78[size_t(team)*2+1])<<8)&0x1ff;} + const uint8_t compact_dialog_frame=g.memory.has(::bmh::layout::CompactDialogFrame)?g.memory.u8(::bmh::layout::CompactDialogFrame):exe.u8(::bmh::layout::CompactDialogFrame); + for(auto* projection:{&s.read_only_notice,&s.close_notice}){projection->portrait=portrait;projection->badge_fallback=fallback;projection->badge_sprite=badge;projection->compact_dialog_frame=compact_dialog_frame!=0;} + const uint8_t notice_gate_disabled=g.memory.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2)?g.memory.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2):exe.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField2); + const uint8_t presentation_blocked=g.memory.has(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField)?g.memory.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField):exe.u8(::bmh::layout::BalancePlan_BalanceFromGame_RuntimeField); + s.read_only_notice_enabled=notice_gate_disabled==0&&(compact_dialog_frame!=0||presentation_blocked==0); + return s; +} + +BalanceScreen::BalanceScreen(const std::filesystem::path& d,BalanceState s):state_(std::move(s)),data_(d),exe_(load_le(asset_path(d,"BMH.exe"))),texts_(load_textd(asset_path(d,"TEXTD.BLK"))),body_(load_font(asset_path(d/"F","BMH3.FNT"))),heading_(load_font(asset_path(d/"F","BMH2.FNT"))),calculator_art_(load_vga(asset_path(d/"KB","6.VGA"))),button_art_(load_vga(asset_path(d/"KB","0.VGA"))),panel_art_(load_vga(asset_path(d/"KB","56.VGA"))),frame_art_(load_vga(asset_path(d/"KB","129.VGA"))),sprite_(d){ + if(state_.identity.manager_slot<0||state_.identity.manager_slot>3||state_.identity.manager_slot!=state_.draft.manager||state_.underlay.width!=320||state_.underlay.height!=240||calculator_art_.width<113||calculator_art_.height<150)throw FormatError("balance: incomplete Source projection"); + state_.calculator_x=std::clamp(state_.calculator_x,0,207);state_.calculator_y=std::clamp(state_.calculator_y,0,104); + format_state_.memory.add_block(::bmh::layout::CurrencyMultiplier,8);format_state_.memory.set32(::bmh::layout::CurrencyMultiplier,state_.currency_numerator);format_state_.memory.set32(::bmh::layout::CurrencyDivisor,state_.currency_denominator); + close_notice_visible_=state_.pending_close;(void)render(); +} +void BalanceScreen::draw_panels(Image& o)const{ + if(!state_.cached_backdrop&&!state_.decorated){fill(o,0,4,320,13,0x44);fill(o,1,5,318,11,0x39);fill(o,0,228,320,10,0x44);fill(o,1,229,318,8,0x39);} + for(auto r:{std::array{0,28,159,153},std::array{161,28,319,153}}){ + if(state_.original_panel)copy(o,panel_art_,r[0],9,r[0]+1,r[1]+1,r[2]-r[0]-1,r[3]-r[1]-1); + else fill(o,r[0],r[1],r[2]-r[0]+1,r[3]-r[1]+1,0x42); + fill(o,r[0],r[1],r[2]-r[0]+1,1,0x46);fill(o,r[0],r[1],1,r[3]-r[1]+1,0x46);fill(o,r[0],r[3],r[2]-r[0]+1,1,0x40);fill(o,r[2],r[1],1,r[3]-r[1]+1,0x40); + } + const auto title=original_to_utf8(at(texts_,::bmh::layout::BalancePlan_Fill_TextPointer));sprite_.draw(o,172+55-sprite_.text_width(title)/2,13,title);sprite_.draw(o,5,235,original_to_utf8(state_.club_name)); +} +void BalanceScreen::draw_rows(Image& o)const{ + auto text=[&](int x,int y,std::string_view v,uint8_t c){int top=y-body_.baseline,w=body_.text_width(v);if(v.empty()||x<0||x+w>o.width||top<0||top+body_.height>o.height)return;Image mask(std::max(1,w),body_.height);body_.draw(mask,0,0,v,1);int index=0;while(index<32&&exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2+uint32_t(index))!=c)++index;for(int yy=0;yy=7;const int i=exp?row-7:row,x=exp?165:3,vx=exp?262:100,y=44+i*9;const auto label=at(texts_,::bmh::layout::BalancePlan_DrawRows_TextPointer5+uint32_t(row)*4);text(x,y,label,colors[exp]);const int32_t value=std::max(0,state_.draft.rows[size_t(row)]);auto val=source_money(value);text(vx,y,val,colors[exp]);total+=double(value)*(exp?-1.0:1.0);} + const double dep_display=-double(state_.draft.depreciation);const bool dep_right=state_.draft.depreciation>0;auto dep=source_money(int32_t(std::clamp(std::abs(dep_display),0,99999999)));text(dep_right?165:3,143,at(texts_,::bmh::layout::BalancePlan_DrawRows_TextPointer6),colors[dep_right?1:0]);text(dep_right?262:100,143,dep,colors[dep_right?1:0]);total=state_.draft.total; + const bool profit=total>=0;auto result=source_money(int32_t(std::clamp(std::abs(total),0,99999999)));text(profit?165:3,152,at(texts_,profit?::bmh::layout::BalancePlan_DrawRows_TextPointer8: ::bmh::layout::BalancePlan_DrawRows_TextPointer7),colors[profit?0:1]);text(profit?262:100,152,result,colors[profit?0:1]); + text(12,162,exe_.cstring(::bmh::layout::BalancePlan_DrawRows_TextPointer),0x40);text(10,160,exe_.cstring(::bmh::layout::BalancePlan_DrawRows_TextPointer),0x5f); + constexpr std::array suffix_id{15,16,17}; + for(int i=0;i<6;++i){int row=18+i,y=160+i*9;auto label=at(texts_,::bmh::layout::BalancePlan_DrawRows_TextPointer4+uint32_t(i)*4);text(22,y+2,label,0x40);text(20,y,label,0x5f);const int selector=exe_.u8(::bmh::layout::BalancePlan_DrawRows_TextPointer2+uint32_t(i));auto val=format_number(GameState{},state_.draft.rows[size_t(row)],0x89)+std::string(texts_[size_t(suffix_id[std::clamp(selector,0,2)])]);text(192,y+2,val,0x40);text(190,y,val,0x5f);} +} +std::string BalanceScreen::source_money(int32_t value)const{return format_number(format_state_,value,0x188);} +BalanceRequest BalanceScreen::request(BalanceAction kind,int row,int32_t value)const{BalanceRequest r;r.identity=state_.identity;r.kind=kind;r.row=row;r.value=value;return r;} +void BalanceScreen::draw_buttons(Image& o)const{ + auto button=[&](int x,int width,std::string_view raw,int id){const bool down=pressed_main_button_==id&&main_button_armed_;int y=214,dx=x+(down?2:0),dy=y+(down?2:0),sy=down?44:74;if(down){fill(o,x,y,width+1,2,o.at(x,y+10));fill(o,x,y,2,11,o.at(x,y+10));}else{fill(o,x+2,y+10,width+1,2,0x40);fill(o,x+width,y+2,2,10,0x40);}copy(o,button_art_,24,sy,dx,dy,31,10);int used=31;while(width-used>20){int n=std::min(8,width-used-20);copy(o,button_art_,24,sy+10,dx+used,dy,n,10);used+=n;}int tail=width-used;copy(o,button_art_,45-tail,sy+20,dx+used,dy,tail,10);auto label=original_to_utf8(raw);sprite_.draw(o,dx+width/2-sprite_.text_width(label)/2,dy+7,label,exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + uint32_t(down)));}; + button(170,63,at(texts_,::bmh::layout::BalancePlan_DrawButtons_TextPointer+uint32_t(state_.draft.view)*4),0);button(245,63,at(texts_,::bmh::layout::BalancePlan_DrawButtons_TextPointer2),1); +} +void BalanceScreen::draw_calculator(Image& o)const{ + if(!calculator_open_)return;const int cx=state_.calculator_x,cy=state_.calculator_y;copy(o,calculator_art_,0,0,cx,cy,113,136); + fill(o,cx+113,cy+2,2,136,0x40);fill(o,cx+2,cy+136,113,2,0x40); + auto draw=[&](int x,int baseline,std::string_view raw,uint8_t color,bool gradient=true){const int w=body_.text_width(raw),top=baseline-body_.baseline;if(x<0||top<0||x+w>o.width||top+body_.height>o.height)return;if(!gradient||!state_.gradient){body_.draw(o,x,top,raw,color);return;}Image mask(std::max(1,w),body_.height);body_.draw(mask,0,0,raw,1);int idx=0;while(idx<32&&exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2+uint32_t(idx))!=color)++idx;for(int yy=0;yy=22)return; + const bool editable=(row<=2)||(row>=4&&row<=17)||(row>=19&&row<=21); + if(!editable)return; + if(state_.draft.view==BalanceView::so_far){notice_visible_=state_.read_only_notice_enabled;notice_consumed_=false;notice_clock_started_=false;return;} + active_row_=row;active_profile_=state_.calculators[size_t(row)];if(!active_profile_.supported)return; + calculator_value_=active_profile_.initial;numeric_text_=std::to_string(calculator_value_);calculator_value_edited_=false;calculator_open_=true; +} +bool BalanceScreen::commit_calculator(bool accepted){ + if(!calculator_open_)return false;const int row=active_row_;calculator_open_=false;numeric_text_.clear(); + if(accepted)pending_=request(BalanceAction::edit_row,row,int32_t(std::min(calculator_value_,active_profile_.maximum))); + return true; +} +bool BalanceScreen::handle_calculator_key(std::string_view key){ + if(key.size()==1&&key[0]>='0'&&key[0]<='9')return text(key); + if(key=="D"){calculator_value_/=10;numeric_text_=std::to_string(calculator_value_);calculator_value_edited_=true;return true;} + if(key=="R"){calculator_value_=active_profile_.initial;numeric_text_=std::to_string(calculator_value_);calculator_value_edited_=true;return true;} + if(key=="C"){calculator_value_=0;numeric_text_="0";calculator_value_edited_=true;return true;} + if(key=="J"){calculator_deferred_accept_=true;return true;} + if(key=="N"){calculator_open_=false;numeric_text_.clear();calculator_cancel_waiting_=true;calculator_cancel_started_=false;return true;} + return false; +} +bool BalanceScreen::pointer_down(int x,int y,bool right){ + if(pending_||calculator_cancel_waiting_||(flash_calculator_control_>=0&¤t_milliseconds_=0||pressed_main_button_>=0;if(dragging_calculator_){dragging_calculator_=false;}else if(pressed_calculator_control_>=0){pressed_calculator_control_=-1;}else if(pressed_main_button_>=0){const int id=pressed_main_button_;const bool activate=main_button_armed_&&in(x,y,id==0?170:245,214,id==0?233:308,224);pressed_main_button_=-1;main_button_armed_=false;if(activate)pending_=request(id==0?BalanceAction::cycle_view:BalanceAction::take_actuals);}else if(calculator_open_){/* no release action for unpressed calculator area */}pointer_x_=pointer_y_=-1;return handled;} +bool BalanceScreen::move(int x,int y){if(pointer_x_<0)return false;if(dragging_calculator_){state_.calculator_x=std::clamp(x-drag_offset_x_,0,207);state_.calculator_y=std::clamp(y-drag_offset_y_,0,104);}if(pressed_main_button_>=0&&main_button_armed_&&!in(x,y,pressed_main_button_==0?170:245,214,pressed_main_button_==0?233:308,224))main_button_armed_=false;pointer_x_=x;pointer_y_=y;return true;} +bool BalanceScreen::key(std::string_view k){ + if(pending_||calculator_cancel_waiting_||(flash_calculator_control_>=0&¤t_milliseconds_='0'&&k[0]<='9')return text(k);if(k=="BACKSPACE"){calculator_value_/=10;numeric_text_=std::to_string(calculator_value_);calculator_value_edited_=true;pressed_calculator_control_=flash_calculator_control_=10;calculator_flash_until_=current_milliseconds_+80;return true;}if(k=="SPACE"){calculator_value_=0;numeric_text_="0";calculator_value_edited_=true;pressed_calculator_control_=flash_calculator_control_=12;calculator_flash_until_=current_milliseconds_+80;return true;}if(k=="ENTER"||k=="RETURN"){pressed_calculator_control_=flash_calculator_control_=13;calculator_flash_until_=current_milliseconds_+80;calculator_deferred_accept_=true;return true;}if(k=="ESC"||k=="ESCAPE")return commit_calculator(false);return false;} + if(k=="ESC"||k=="ESCAPE"){pending_=request(BalanceAction::close);return true;} + return false; +} +bool BalanceScreen::process_timer_expired(){ + // BalanceFromGame2 event8 closes through the existing typed draft/warning owner. + // BalanceFromGame returns ffffffff first; its N-key wait, held buttons and pending + // edits keep their own completion. PresentManagerDialog notices have their own wait. + if(pending_||notice_open()||calculator_cancel_waiting_||dragging_calculator_|| + pressed_main_button_>=0||pressed_calculator_control_>=0|| + (flash_calculator_control_>=0&¤t_milliseconds_=0&¤t_milliseconds_'9')return false; + std::string candidate=(numeric_text_=="0"?std::string{}:numeric_text_)+std::string(s);if(candidate.size()>10)return false;uint64_t v=0;auto [end,ec]=std::from_chars(candidate.data(),candidate.data()+candidate.size(),v);if(ec!=std::errc{}||end!=candidate.data()+candidate.size())return false; + calculator_value_=uint32_t(std::min(v,active_profile_.maximum));numeric_text_=std::to_string(calculator_value_);calculator_value_edited_=true;const int digit=s.back()-'0';pressed_calculator_control_=flash_calculator_control_=digit;calculator_flash_until_=current_milliseconds_+80;return true; +} +bool BalanceScreen::tick_source_milliseconds(uint64_t now){ + current_milliseconds_=now;bool changed=false; + if(flash_calculator_control_>=0&&now>=calculator_flash_until_){flash_calculator_control_=-1;pressed_calculator_control_=-1;changed=true;if(calculator_deferred_accept_){calculator_deferred_accept_=false;changed=commit_calculator(true)||changed;}} + if(calculator_cancel_waiting_&&calculator_cancel_started_&&now>=calculator_cancel_until_){calculator_cancel_waiting_=false;calculator_cancel_started_=false;changed=true;} + if(!close_notice_visible_&&!notice_visible_)return changed;if(!notice_clock_started_)return changed; + // PresentManagerDialog waits 70 times for 3 Original ticks; at 50 Hz this is 4.2 s. + // The owner supplies a monotonic millisecond clock to retain that fraction. + if(nowkind==BalanceAction::confirm_close;pending_.reset();if(retry_close){close_notice_visible_=true;notice_clock_started_=false;return;}calculator_open_=false;notice_visible_=false;} +bool BalanceScreen::calculator_open()const{return calculator_open_;} +bool BalanceScreen::notice_open()const{return notice_visible_||close_notice_visible_;} +std::string BalanceScreen::state_json()const{ + std::ostringstream o;o<<"{\"manager_slot\":"<kind)<<",\"row\":"<row<<",\"value\":"<value<<"}";}o<<'}';return o.str(); +} +} // namespace bmh::ui diff --git a/src/ui/balance_plan.hpp b/src/ui/balance_plan.hpp new file mode 100644 index 0000000..7bcc0eb --- /dev/null +++ b/src/ui/balance_plan.hpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/balance_plan.hpp" +#include "ui/game_end.hpp" +#include "ui/outgoing_transfer.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { +struct BalanceIdentity { + int manager_slot=-1, runtime_club=-1, club_identity=-1; + uint32_t day_counter=0; + uint64_t revision=0, scope=0, sequence=0; + bool operator==(const BalanceIdentity&) const=default; +}; +enum class BalanceAction : uint8_t { open, edit_row, cycle_view, take_actuals, close, confirm_close }; +struct BalanceRequest { + BalanceIdentity identity; + BalanceAction kind=BalanceAction::open; + int row=-1; + int32_t value=0; + bool operator==(const BalanceRequest&) const=default; +}; +struct BalanceState { + BalanceIdentity identity; + BalancePlanDraft draft; + Image underlay; // Captured accepted desktop; BalanceFromGame2 draws over this frame. + std::string club_name; // Original ISO646-DE bytes. + std::array calculators{}; + uint32_t currency_numerator=1, currency_denominator=1; + TaxDialogProjection read_only_notice, close_notice; + bool read_only_notice_enabled=true; // PresentManagerDialog BalancePlan_BalanceFromGame_RuntimeField2/CompactDialogFrame/BalancePlan_BalanceFromGame_RuntimeField visibility gate, resolved by owner. + bool pending_close=false; // Core close staged once; warning precedes live publish. + bool decorated=true, original_panel=true, gradient=true, cached_backdrop=false; + int calculator_x=100, calculator_y=80; // BalanceFromGame persisted caller origin. +}; +BalanceState balance_from_game(const GameState&,const BalancePlanDraft&,const LeImage&, + BalanceIdentity,const Image& underlay); + +class BalanceScreen { +public: + BalanceScreen(const std::filesystem::path&,BalanceState); + Image render() const; + bool pointer_down(int x,int y,bool right=false); + bool release(int x,int y); + bool move(int x,int y); + bool key(std::string_view); + bool process_timer_expired(); + bool text(std::string_view); + bool tick_source_milliseconds(uint64_t now); + void mark_presented_source_milliseconds(uint64_t now); + void reject_action(std::string reason); + const BalanceState& state() const { return state_; } + const std::optional& pending() const { return pending_; } + bool calculator_open() const; + bool notice_open() const; + std::string state_json() const; +private: + BalanceState state_; + GameState format_state_; + std::optional pending_; + std::filesystem::path data_; + LeImage exe_; + TextDb texts_; + Font body_; + Font heading_; + Image calculator_art_, button_art_, panel_art_, frame_art_; + SpriteFont sprite_; + OutgoingTransferCalculatorProfile active_profile_; + int active_row_=-1, pointer_x_=-1, pointer_y_=-1; + int drag_offset_x_=0, drag_offset_y_=0; + int pressed_calculator_control_=-1, flash_calculator_control_=-1, pressed_main_button_=-1; + bool dragging_calculator_=false, main_button_armed_=false; + bool calculator_value_edited_=false, calculator_cancel_waiting_=false; + bool calculator_cancel_started_=false, calculator_deferred_accept_=false; + uint32_t calculator_value_=0; + std::string numeric_text_; + bool calculator_open_=false, notice_visible_=false, close_notice_visible_=false; + uint64_t notice_started_=0, current_milliseconds_=0, calculator_flash_until_=0, calculator_cancel_until_=0; + bool notice_clock_started_=false; + bool close_notice_finishes_=false; + bool notice_consumed_=false; + void open_calculator(int row); + bool handle_calculator_key(std::string_view key); + bool commit_calculator(bool accepted); + void draw_panels(Image&) const; + void draw_rows(Image&) const; + void draw_calculator(Image&) const; + void draw_buttons(Image&) const; + void draw_notice(Image&) const; + std::string source_money(int32_t value) const; + BalanceRequest request(BalanceAction, int row=-1, int32_t value=0) const; +}; +} // namespace bmh::ui diff --git a/src/ui/balance_plan_tests.cpp b/src/ui/balance_plan_tests.cpp new file mode 100644 index 0000000..702baeb --- /dev/null +++ b/src/ui/balance_plan_tests.cpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/balance_plan.hpp" +#include "ui/setup.hpp" + +#include +#include + +using namespace bmh; +using namespace bmh::ui; +namespace { int failures=0; void check(bool ok,const char* m){if(!ok){std::fprintf(stderr,"FAIL: %s\n",m);++failures;}} } + +static BalanceState fixture(){ + BalanceState s;s.identity.manager_slot=0;s.identity.runtime_club=1;s.identity.club_identity=1;s.identity.revision=7;s.identity.scope=10;s.identity.sequence=2; + s.draft.manager=0;s.draft.view=BalanceView::future;s.draft.rows[0]=5000;s.draft.rows[7]=1200;s.draft.total=3800;s.underlay=Image(320,240,0x22);s.club_name="UNITFC"; + for(int i=0;ikind==BalanceAction::close,"next outer poll emits the normal draft close"); + const auto closing=timed.state_json();check(!timed.process_timer_expired()&&timed.state_json()==closing,"expiry cannot replace a pending draft close"); + BalanceScreen accepted(data,fixture());accepted.pointer_down(0,38);accepted.key("RETURN"); + check(!accepted.process_timer_expired(),"expiry cannot cancel the deferred accepted calculator");accepted.tick_source_milliseconds(80); + const auto edit=accepted.state_json();check(accepted.pending()&&!accepted.process_timer_expired()&&accepted.state_json()==edit,"accepted edit keeps its typed ACK"); + BalanceScreen held(data,fixture());held.pointer_down(200,219); + check(!held.process_timer_expired(),"expiry preserves the held view selector");held.release(200,219); + check(held.pending()&&held.pending()->kind==BalanceAction::cycle_view&&!held.process_timer_expired(),"held selector releases its own cycle request"); + auto notice=fixture();notice.draft.view=BalanceView::so_far;BalanceScreen waiting(data,notice);waiting.pointer_down(0,38);waiting.mark_presented_source_milliseconds(100); + check(waiting.notice_open()&&!waiting.process_timer_expired(),"expiry retains the Original read-only notice wait");waiting.tick_source_milliseconds(4300); + check(waiting.process_timer_expired()&&waiting.pending()->kind==BalanceAction::close,"notice completion resumes the outer expiry poll"); + auto warning=fixture();warning.pending_close=true;BalanceScreen staged(data,warning);staged.mark_presented_source_milliseconds(100); + check(staged.notice_open()&&!staged.process_timer_expired(),"expiry leaves the staged DFB warning with its Source wait");staged.tick_source_milliseconds(4300); + check(staged.pending()&&staged.pending()->kind==BalanceAction::confirm_close&&!staged.process_timer_expired(),"DFB warning completes through its existing publish ACK"); + BalanceScreen cancel_wait(data,fixture());cancel_wait.pointer_down(0,38); + cancel_wait.pointer_down(100+exe.u16(::bmh::layout::Advertising_Click_RuntimeField+14*2)+1,80+exe.u8(::bmh::layout::Advertising_Click_RuntimeField2+14)+1); + check(!cancel_wait.process_timer_expired(),"expiry preserves the calculator N-key wait"); + cancel_wait.mark_presented_source_milliseconds(100);cancel_wait.tick_source_milliseconds(1099); + check(!cancel_wait.process_timer_expired(),"N-key cancellation owns its full Source one-second wait");cancel_wait.tick_source_milliseconds(1100); + check(cancel_wait.process_timer_expired()&&cancel_wait.pending()->kind==BalanceAction::close,"N-key wait completion resumes the close owner"); + BalanceScreen drag(data,fixture());drag.pointer_down(0,38);drag.pointer_down(105,85); + check(!drag.process_timer_expired(),"expiry leaves calculator dragging with its physical release");drag.release(105,85); + check(drag.process_timer_expired()&&!drag.calculator_open(),"released calculator can cancel on the next expiry poll"); + } + check(!screen.pointer_down(0,37),"row top outside source hitbox is ignored"); + check(screen.pointer_down(0,38)&&screen.calculator_open(),"inclusive first income hitbox opens KB6 calculator"); + check(screen.key("SPACE"),"Source Space clears calculator");screen.tick_source_milliseconds(80);check(screen.text("9999999999"),"numeric input clamps at the true row maximum after Source flash");check(screen.state_json().find("\"calculator_open\":true")!=std::string::npos,"calculator state is observable"); + check(!screen.key("SPACE"),"next key is blocked during Source key flash");screen.tick_source_milliseconds(160);check(screen.key("SPACE"),"Space clears after the prior key flash");screen.tick_source_milliseconds(240);check(screen.key("RETURN")&&!screen.pending(),"Return starts an 80 ms pressed phase before commit");screen.tick_source_milliseconds(319);check(!screen.pending(),"typed accept remains deferred before 80 ms");screen.tick_source_milliseconds(320);auto req=screen.pending();check(req&&req->kind==BalanceAction::edit_row&&req->row==0&&req->value==0&&req->identity.scope==10,"typed edit commits after Source flash with row, value and owner identity"); + screen.reject_action("reproject");check(!screen.pending(),"reprojection clears the prior request"); + BalanceScreen append(argv[1],fixture());append.pointer_down(0,38);check(append.text("5")&&!append.key("RETURN"),"Source calculator appends digits and blocks Return during key flash");append.tick_source_milliseconds(80);check(append.key("RETURN")&&!append.pending(),"keyboard Return defers request through its flash");append.tick_source_milliseconds(160);check(append.pending()&&append.pending()->value==50005,"Source calculator appends digits to initial value and commits after 80 ms"); + auto right=fixture();right.calculators[20].presets[0]=9000;BalanceScreen gate(argv[1],right);gate.pointer_down(319,172);check(gate.calculator_open(),"inclusive right-panel expense/summary geometry reaches row 20");gate.key("ESC");gate.pointer_down(233,224);check(!gate.pending(),"bottom-left button waits for release");gate.move(240,230);gate.move(233,224);gate.release(233,224);check(!gate.pending(),"leaving button once latches cancel through re-entry");gate.pointer_down(233,224);gate.release(233,224);check(gate.pending()&&gate.pending()->kind==BalanceAction::cycle_view,"inclusive bottom-left release emits cycle"); + auto view0=fixture();view0.draft.view=BalanceView::so_far;BalanceScreen read_only(argv[1],view0);read_only.pointer_down(3,38);check(read_only.notice_open()&&!read_only.pending()&&!read_only.calculator_open(),"so-far editable click shows a read-only notice without owner mutation");check(!read_only.key("SPACE")&&read_only.notice_open(),"non-Source key does not dismiss the Source notice");read_only.pointer_down(3,38);check(!read_only.notice_open()&&!read_only.pending(),"Source click dismisses local read-only notice"); + BalanceScreen digit8(argv[1],fixture());digit8.pointer_down(0,38);check(digit8.key("8")&&!digit8.key("RETURN"),"physical digit 8 edits calculator value instead of acting as Escape and starts a flash");digit8.tick_source_milliseconds(80);check(digit8.key("RETURN")&&!digit8.pending(),"Return after digit flash defers accept");digit8.tick_source_milliseconds(160);check(digit8.pending()&&digit8.pending()->value==50008,"physical digit 8 remains a typed value"); + auto plain=view0;plain.decorated=false;plain.gradient=false;BalanceScreen styled_notice(argv[1],view0),plain_notice(argv[1],plain);styled_notice.pointer_down(3,38);plain_notice.pointer_down(3,38);check(plain_notice.render().pixels!=styled_notice.render().pixels,"tax notice respects resolved undecorated and disabled-gradient flags"); + auto closing=fixture();closing.pending_close=true;BalanceScreen warning(argv[1],closing);check(warning.notice_open(),"pending close starts the timed Source DFB notice");warning.mark_presented_source_milliseconds(1000);check(!warning.tick_source_milliseconds(5199),"warning waits for Source 4.2 second timeout");check(warning.tick_source_milliseconds(5200)&&warning.pending()&&warning.pending()->kind==BalanceAction::confirm_close,"timeout sends typed confirmation only after warning"); + warning.reject_action("next state");check(warning.notice_open(),"failed confirm restores the timed close warning for retry");warning.key("ESC");check(warning.pending()&&warning.pending()->kind==BalanceAction::confirm_close,"Source escape retries the typed close confirmation"); + BalanceScreen drag(argv[1],fixture());drag.pointer_down(0,38);drag.release(0,38);drag.pointer_down(105,81);drag.move(1000,1000);drag.release(1000,1000);check(drag.state().calculator_x==207&&drag.state().calculator_y==104,"calculator drag clamps to Source maximum origin"); + BalanceScreen flash(argv[1],fixture());flash.tick_source_milliseconds(1000);flash.pointer_down(0,38);const int dx=flash.state().calculator_x+exe.u16(::bmh::layout::Advertising_Click_RuntimeField)+16,dy=flash.state().calculator_y+exe.u8(::bmh::layout::Advertising_Click_RuntimeField2)+14;flash.pointer_down(dx,dy);flash.release(dx,dy);check(!flash.tick_source_milliseconds(1079)&&flash.tick_source_milliseconds(1080),"calculator key redraw flash expires after 80 ms"); + BalanceScreen mouse_accept(argv[1],fixture());mouse_accept.tick_source_milliseconds(1000);mouse_accept.pointer_down(0,38);const int jx=mouse_accept.state().calculator_x+exe.u16(::bmh::layout::Advertising_Click_RuntimeField+13*2)+16,jy=mouse_accept.state().calculator_y+exe.u8(::bmh::layout::Advertising_Click_RuntimeField2+13)+14;mouse_accept.pointer_down(jx,jy);check(!mouse_accept.pending()&&mouse_accept.calculator_open(),"mouse J does not dispatch before its pressed frame");mouse_accept.release(jx,jy);mouse_accept.tick_source_milliseconds(1079);check(!mouse_accept.pending(),"mouse J stays deferred at 79 ms");mouse_accept.tick_source_milliseconds(1080);check(mouse_accept.pending()&&mouse_accept.pending()->kind==BalanceAction::edit_row,"mouse J dispatches after its 80 ms flash"); + BalanceScreen leave(argv[1],fixture());leave.key("8");check(!leave.pending(),"literal key 8 is not an Escape alias");leave.key("ESC");check(leave.pending()&&leave.pending()->kind==BalanceAction::close,"Escape requests close through typed owner path"); + BalanceScreen cancel(argv[1],fixture());cancel.tick_source_milliseconds(10000);cancel.pointer_down(0,38);const int nx=cancel.state().calculator_x+exe.u16(::bmh::layout::Advertising_Click_RuntimeField+14*2)+16,ny=cancel.state().calculator_y+exe.u8(::bmh::layout::Advertising_Click_RuntimeField2+14)+14;check(cancel.pointer_down(nx,ny)&&!cancel.calculator_open(),"inclusive Source N hitbox starts mouse-cancel delay");cancel.mark_presented_source_milliseconds(10000);check(!cancel.pointer_down(10,50)&&!cancel.key("ESC"),"Source N wait blocks further input until the restored frame timer expires");cancel.tick_source_milliseconds(10080);check(!cancel.tick_source_milliseconds(10999)&&cancel.tick_source_milliseconds(11000),"mouse N waits one Source second after presentation"); + }catch(const std::exception& e){std::fprintf(stderr,"EXCEPTION: %s\n",e.what());++failures;} + return failures?1:0; +} diff --git a/src/ui/bank.cpp b/src/ui/bank.cpp new file mode 100644 index 0000000..aaf1d39 --- /dev/null +++ b/src/ui/bank.cpp @@ -0,0 +1,1393 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/bank.hpp" +#include "ui/game_end.hpp" + +#include +#include +#include +#include +#include + +#include "formats/vga.hpp" +#include "game/desk_actions.hpp" +#include "game/messages.hpp" +#include "game/state.hpp" +#include "ui/setup.hpp" + +namespace bmh::ui { +namespace { +std::string money(int64_t value) { + const bool negative = value < 0; + std::string result = std::to_string(negative ? -value : value); + for (int pos = int(result.size()) - 3; pos > 0; pos -= 3) result.insert(size_t(pos), "."); + if (negative) result.insert(result.begin(), '-'); + return result; +} +void rect(Image& image, int x, int y, int w, int h, uint8_t color) { + for (int yy = std::max(0, y); yy < std::min(image.height, y + h); ++yy) + for (int xx = std::max(0, x); xx < std::min(image.width, x + w); ++xx) image.at(xx, yy) = color; +} +void line(Image& image, int x0, int y0, int x1, int y1, uint8_t color) { + int dx = std::abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + int dy = -std::abs(y1 - y0), sy = y0 < y1 ? 1 : -1, err = dx + dy; + for (;;) { + if (x0 >= 0 && y0 >= 0 && x0 < image.width && y0 < image.height) image.at(x0, y0) = color; + if (x0 == x1 && y0 == y1) break; + const int twice = 2 * err; + if (twice >= dy) { err += dy; x0 += sx; } + if (twice <= dx) { err += dx; y0 += sy; } + } +} +uint16_t rd16(const std::vector& v, size_t at) { + return uint16_t(v.at(at) | uint16_t(v.at(at + 1)) << 8); +} +int32_t rd32(const std::vector& v, size_t at) { + return int32_t(uint32_t(v.at(at)) | uint32_t(v.at(at + 1)) << 8 | uint32_t(v.at(at + 2)) << 16 | + uint32_t(v.at(at + 3)) << 24); +} +int32_t wrap_i32(uint32_t value) { return std::bit_cast(value); } +int32_t wrap_sum(int32_t a, int32_t b) { return wrap_i32(uint32_t(a) + uint32_t(b)); } +void copy_region(Image& target, const Image& source, int sx, int sy, int x, int y, + int width, int height, bool transparent = false) { + for (int yy = 0; yy < height; ++yy) for (int xx = 0; xx < width; ++xx) { + const int tx = x + xx, ty = y + yy, px = sx + xx, py = sy + yy; + if (tx < 0 || ty < 0 || tx >= target.width || ty >= target.height || + px < 0 || py < 0 || px >= source.width || py >= source.height) continue; + const uint8_t color = source.pixels[size_t(py) * size_t(source.width) + size_t(px)]; + if (!transparent || color != 0xff) target.at(tx, ty) = color; + } +} +} + +BankState bank_from_game(const GameState& g, const LeImage& exe, uint64_t revision) { + const int manager = int(g.memory.u8(::bmh::layout::ActiveManager)); + if (manager < 0 || size_t(manager) >= g.manager_teams.size()) throw FormatError("bank: invalid active manager"); + const size_t record = size_t(manager) * 0xb0c; + if (record + 0x328 > g.manager_records.size()) throw FormatError("bank: truncated manager record"); + BankState state; + state.manager_slot = manager; + state.runtime_club = g.manager_teams.at(size_t(manager)); + state.revision = revision; + state.gradient_text = g.memory.u8(::bmh::layout::TextGradientDisabled) == 0; + const auto read = [&](size_t at) { + return int32_t(uint32_t(g.manager_records.at(at)) | uint32_t(g.manager_records.at(at + 1)) << 8 | + uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24); + }; + state.balance = read(record + 0x314); state.deposit = read(record + 0x318); + state.credit_line = read(record + 0x31c); state.investment_balance = read(record + 0x324); + state.credit = bank_credit_context(g, exe, manager); + // MaxSharesToBuy iterates the configured human-manager count (ManagerCount), + // not the larger live vector which may include the hidden national coach. + if (!g.memory.has(::bmh::layout::ManagerCount)) throw FormatError("bank: missing configured manager count"); + const int configured_managers = int(g.memory.u8(::bmh::layout::ManagerCount)); + if (configured_managers < 1 || configured_managers > 4 || + size_t(configured_managers) > g.manager_teams.size() || manager >= configured_managers) + throw FormatError("bank: unsupported configured manager count"); + for (int slot = 0; slot < configured_managers && state.credit_lenders.size() < 3; ++slot) { + if (slot == manager) continue; + const size_t lender_record = size_t(slot) * 0xb0c; + if (lender_record + 0x314 > g.manager_records.size()) + throw FormatError("bank: truncated lender manager record"); + const auto lender_end = std::find(g.manager_records.begin() + lender_record + 0xa8, + g.manager_records.begin() + lender_record + 0xa8 + 26, uint8_t(0)); + BankState::CreditLender lender; + lender.manager_slot = slot; + lender.counterparty = slot + 1; + lender.manager_name.assign(g.manager_records.begin() + lender_record + 0xa8, lender_end); + lender.credit = bank_credit_context(g, exe, manager, lender.counterparty); + state.credit_lenders.push_back(std::move(lender)); + } + state.credit_currency = {g.memory.has(::bmh::layout::CurrencyMultiplier) ? int32_t(g.memory.u32(::bmh::layout::CurrencyMultiplier)) : 1, + g.memory.has(::bmh::layout::CurrencyDivisor) ? int32_t(g.memory.u32(::bmh::layout::CurrencyDivisor)) : 1}; + const auto currency = [&](int32_t amount, int flags) { + std::string value = format_number(g, amount, flags); + // FormatNumber appends currency (CurrencySuffixText) and the caller's Bank_FormatError_ExecutableField suffix. + value += exe.cstring(::bmh::layout::Bank_FormatError_ExecutableField); + return original_to_utf8(value); + }; + state.balance_text = currency(state.balance, 0x188); + state.deposit_text = currency(state.deposit, 0x188); + state.account_text = currency(state.balance, 0x101); + if (g.stocks.size() < 12u * 0x5c) throw FormatError("bank: truncated stock table"); + for (size_t i = 0; i < state.stocks.size(); ++i) { + const size_t at = i * 0x5c; + auto& stock = state.stocks[i]; + stock.long_term_value = rd32(g.stocks, at); + stock.paid = rd32(g.stocks, at + 4 + size_t(manager) * 4); + stock.price = rd16(g.stocks, at + 0x4e); + stock.previous_price = rd16(g.stocks, at + 0x4c); + stock.max_to_buy = stock.price == 0 ? 0 : max_shares_to_buy(g, manager, int(i)); + stock.owned = rd16(g.stocks, at + 0x50 + size_t(manager) * 2); + stock.trend = g.stocks.at(at + 0x16); + stock.trend_age = g.stocks.at(at + 0x59); + for (size_t day = 0; day < stock.history.size(); ++day) + stock.history[day] = rd16(g.stocks, at + 0x14 + day * 2); + uint16_t maximum = 0, minimum = 2000; + for (const uint16_t value : stock.history) { + maximum = std::max(maximum, value); + minimum = std::min(minimum, value); + } + stock.market_text = {original_to_utf8(format_number(g, stock.price, 0x44)), + original_to_utf8(format_number(g, stock.previous_price, 0x44)), + original_to_utf8(format_number(g, maximum, 0x44)), + original_to_utf8(format_number(g, minimum, 0x44))}; + } + for (size_t i = 0; i < state.funds.size(); ++i) { + const uint32_t at = ::bmh::layout::FundBlock + uint32_t(i) * 0x1c; + auto& fund = state.funds[i]; + fund.price = g.memory.u32(at); + fund.paid = g.memory.u32(at + 4 + uint32_t(manager) * 4); + fund.owned = g.memory.u16(at + 0x14 + uint32_t(manager) * 2); + fund.max_to_buy = fund.price == 0 ? 0 : max_fund_units(g, manager, int(i)); + fund.name = original_to_utf8(message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer3 + uint32_t(i) * 4)); + fund.unit_price_text = currency(wrap_i32(fund.price), 0x108); + fund.average_paid_text = currency(fund.owned ? wrap_i32(fund.paid / fund.owned) : 0, 0x108); + fund.quantity_text = original_to_utf8(format_number(g, fund.owned, 0x82) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2)); + fund.one_quantity_text = original_to_utf8(format_number(g, 1, 0x82) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2)); + const uint32_t suffix = exe.u32(::bmh::layout::Bank_OriginalToUtf8_RuntimeField + uint32_t(i) * 8); + fund.singular_suffix = original_to_utf8(exe.cstring(suffix)); + fund.plural_suffix = original_to_utf8(exe.cstring(exe.u32(::bmh::layout::Bank_OriginalToUtf8_RuntimeField + uint32_t(i) * 8 + 4))); + } + // MaxSharesToBuy case 1 / HighscoreScore. The seven rows are account, + // passbook, investment holdings, shares, outstanding borrowing, net worth, + // and the separate overdraft limit. All inputs are copied/read-only. + state.finance_values[0] = state.balance; + state.finance_values[1] = state.deposit; + int32_t investment_value = 0, investment_gain = 0; + for (size_t i = 0; i < state.funds.size(); ++i) { + const uint32_t price = g.memory.u32(::bmh::layout::FundBlock + uint32_t(i) * 0x1c); + const uint32_t held = g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(manager) * 2 + uint32_t(i) * 0x1c); + const int32_t value = wrap_i32(price * held); + investment_value = wrap_sum(investment_value, value); + const int32_t paid = wrap_i32(g.memory.u32(::bmh::layout::Bank_OriginalToUtf8_RuntimeField5 + uint32_t(i) * 0x1c + uint32_t(manager) * 4)); + if (held) investment_gain = wrap_sum(investment_gain, wrap_i32(uint32_t(value) - uint32_t(paid))); + } + state.finance_values[2] = investment_value; + state.finance_gains[0] = investment_gain; + int32_t stock_value = 0, stock_gain = 0; + for (size_t i = 0; i < state.stocks.size(); ++i) { + const int32_t value = wrap_i32(uint32_t(state.stocks[i].price) * state.stocks[i].owned); + stock_value = wrap_sum(stock_value, value); + if (state.stocks[i].owned) stock_gain = wrap_sum(stock_gain, wrap_i32(uint32_t(value) - uint32_t(state.stocks[i].paid))); + } + state.finance_values[3] = stock_value; + state.finance_gains[1] = stock_gain; + int32_t debts = 0, debt_assets = 0; + for (uint32_t loan = 0; loan < 5; ++loan) { + const uint32_t at = ::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(manager) * 0x78 + loan * 0x18; + const uint32_t borrowed = g.memory.u32(at); + const uint32_t repaid = g.memory.u32(at + 0x10); + debts = wrap_sum(debts, wrap_i32(borrowed - repaid)); + debt_assets = wrap_sum(debt_assets, wrap_i32(borrowed)); + } + state.finance_values[4] = debts; + int32_t net = state.balance; + net = wrap_sum(net, state.deposit); + net = wrap_sum(net, investment_value); + net = wrap_sum(net, stock_value); + net = wrap_sum(net, wrap_i32(0u - uint32_t(debt_assets))); + state.finance_values[5] = net; + state.finance_values[6] = state.credit_line; + for (size_t i = 0; i < state.finance_value_text.size(); ++i) + state.finance_value_text[i] = currency(state.finance_values[i], 0x188); + for (size_t i = 0; i < state.finance_gains.size(); ++i) { + const int32_t gain = state.finance_gains[i]; + const uint32_t sign_address = gain < 0 ? ::bmh::layout::Bank_OriginalToUtf8_ExecutableField5 : gain > 0 ? ::bmh::layout::Bank_OriginalToUtf8_ExecutableField6 : ::bmh::layout::Bank_OriginalToUtf8_ExecutableField7; + const int32_t magnitude = gain < 0 ? wrap_i32(0u - uint32_t(gain)) : gain; + state.finance_gain_text[i] = original_to_utf8(exe.cstring(sign_address) + + format_number(g, magnitude, 0x101) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField3)); + // 0x101 appends; Source preserves market value and adds signed gain in parentheses. + if (state.finance_values[i + 2] != 0) + state.finance_value_text[i + 2] += original_to_utf8(exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField4)) + state.finance_gain_text[i]; + } + const auto initial_credit = bank_credit_draft(state.credit); + for (size_t i = 0; i < state.credit_values.size(); ++i) + state.credit_values[i] = wrap_i32(initial_credit.values[i]); + state.credit_values[0] = wrap_i32(initial_credit.values[0] - initial_credit.values[6]); + state.credit_values[4] = wrap_i32(state.credit.saved[3] - state.credit.saved[4]); + state.credit_values[5] = wrap_i32(state.credit.saved[5]); + for (size_t i = 0; i < state.credit_values.size(); ++i) { + state.credit_labels[i] = original_to_utf8(message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer4 + uint32_t(i) * 4)); + std::string value = exe.cstring(::bmh::layout::Bank_OriginalToUtf8_TextPointer2); + value += format_number(g, state.credit_values[i], 8); + value += exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2); + if (i == 3 || i == 4) { + value += message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer7); + if (state.credit_values[i] != 1) value += exe.cstring(::bmh::layout::Bank_OriginalToUtf8_TextPointer); + } else { + value += message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer6); + } + state.credit_value_text[i] = original_to_utf8(value); + } + for (size_t i = 0; i < state.funds.size(); ++i) { + const auto& fund = state.funds[i]; + if (!fund.owned) continue; + state.finance_fund_labels[i] = original_to_utf8(format_number(g, fund.owned, 0x82) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2) + + message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer3 + uint32_t(i) * 4) + + exe.cstring(exe.u32(::bmh::layout::Bank_OriginalToUtf8_RuntimeField + uint32_t(i) * 8 + (fund.owned > 1 ? 4 : 0)))); + state.finance_fund_prices[i] = original_to_utf8("(" + format_number(g, wrap_i32(fund.price), 0x108) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField3)); + } + for (size_t i = 0; i < state.stocks.size(); ++i) { + const auto& stock = state.stocks[i]; + if (!stock.owned) continue; + state.finance_stock_labels[i] = original_to_utf8(format_number(g, stock.owned, 0x84) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2) + + message_text(g, ::bmh::layout::Bank_FormatError_ExecutableField2 + uint32_t(i) * 4)); + state.finance_stock_prices[i] = original_to_utf8("(" + format_number(g, stock.price, 4) + exe.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField3)); + } + const auto record_end = std::find(g.manager_records.begin() + record + 0xa8, + g.manager_records.begin() + record + 0xa8 + 26, uint8_t(0)); + state.manager_name.assign(g.manager_records.begin() + record + 0xa8, record_end); + if (state.runtime_club < 0 || size_t(state.runtime_club) >= g.club_ids.size()) throw FormatError("bank: invalid runtime club"); + const size_t name_at = g.club_ids.at(size_t(state.runtime_club)); + if (name_at >= g.club_names.size()) throw FormatError("bank: invalid club name offset"); + const auto name_end = std::find(g.club_names.begin() + name_at, g.club_names.end(), uint8_t(0)); + state.club_name.assign(g.club_names.begin() + name_at, name_end); + state.manager_portrait = g.manager_records.at(record + 0x221); + state.badge_sprite = rd16(g.club_heap_78, size_t(state.runtime_club) * 2) & 0x1ff; + state.investment_limit_text = original_to_utf8(message_text(g, ::bmh::layout::Bank_OriginalToUtf8_TextPointer8)); + state.source = "engine_projection"; + return state; +} + +std::string bank_state_json(const BankState& s) { + std::ostringstream out; + out << "{\"screen\":\"bank\",\"source\":" << json_quote(s.source) + << ",\"manager_slot\":" << s.manager_slot << ",\"runtime_club\":" << s.runtime_club + << ",\"manager_name\":" << json_quote(original_to_utf8(s.manager_name)) + << ",\"club_name\":" << json_quote(original_to_utf8(s.club_name)) + << ",\"revision\":" << s.revision << ",\"balance\":" << s.balance + << ",\"deposit\":" << s.deposit << ",\"credit_line\":" << s.credit_line + << ",\"investment_balance\":" << s.investment_balance << ",\"finance_values\":["; + for (size_t i = 0; i < s.finance_values.size(); ++i) { if (i) out << ','; out << s.finance_values[i]; } + out << "],\"finance_gains\":[" << s.finance_gains[0] << ',' << s.finance_gains[1] + << "],\"credit_values\":["; + for (size_t i = 0; i < s.credit_values.size(); ++i) { if (i) out << ','; out << s.credit_values[i]; } + out << "],\"credit_available\":" << (s.credit.available ? "true" : "false") + << ",\"credit_counterparty\":" << s.credit_counterparty << ",\"credit_lenders\":["; + for (size_t i = 0; i < s.credit_lenders.size(); ++i) { + if (i) out << ','; + const auto& lender = s.credit_lenders[i]; + out << "{\"manager_slot\":" << lender.manager_slot << ",\"counterparty\":" << lender.counterparty + << ",\"manager_name\":" << json_quote(original_to_utf8(lender.manager_name)) + << ",\"available\":" << (lender.credit.available ? "true" : "false") << '}'; + } + out << "],\"credit_saved\":["; + for (size_t i = 0; i < s.credit.saved.size(); ++i) { if (i) out << ','; out << s.credit.saved[i]; } + out << "],\"stocks\":["; + for (size_t i = 0; i < s.stocks.size(); ++i) { + if (i) out << ','; + const auto& stock = s.stocks[i]; + out << "{\"long_term_value\":" << stock.long_term_value << ",\"paid\":" << stock.paid + << ",\"price\":" << stock.price << ",\"owned\":" << stock.owned + << ",\"max_to_buy\":" << stock.max_to_buy << ",\"trend\":" << stock.trend + << ",\"trend_age\":" << stock.trend_age << '}'; + } + out << "],\"funds\":["; + for (size_t i = 0; i < s.funds.size(); ++i) { + if (i) out << ','; + const auto& fund = s.funds[i]; + out << "{\"price\":" << fund.price << ",\"paid\":" << fund.paid << ",\"owned\":" << fund.owned + << ",\"max_to_buy\":" << fund.max_to_buy << ",\"name\":" << json_quote(fund.name) + << ",\"unit_price_text\":" << json_quote(fund.unit_price_text) + << ",\"average_paid_text\":" << json_quote(fund.average_paid_text) + << ",\"quantity_text\":" << json_quote(fund.quantity_text) + << ",\"one_quantity_text\":" << json_quote(fund.one_quantity_text) << '}'; + } + out << "],\"property_notice\":"; + if (s.property_notice) { + out << "{\"asset_index\":" << s.property_notice->asset_index + << ",\"additional_cost\":" << s.property_notice->additional_cost + << ",\"text\":" << json_quote(s.property_notice->text) << '}'; + } else out << "null"; + out << ",\"credit_notice\":"; + if (s.credit_notice) out << "{\"refund\":" << s.credit_notice->refund << ",\"text\":" + << json_quote(s.credit_notice->text) << '}'; + else out << "null"; + out << ",\"last_tip\":" << (s.last_tip ? std::to_string(*s.last_tip) : "null") << '}'; + return out.str(); +} +std::string bank_request_json(const BankRequest& r) { + std::ostringstream out; + const char* kind = r.kind == BankRequestKind::move_to_deposit ? "move_to_deposit" : + r.kind == BankRequestKind::buy_shares ? "buy_shares" : r.kind == BankRequestKind::sell_shares ? "sell_shares" : + r.kind == BankRequestKind::stock_tip ? "stock_tip" : r.kind == BankRequestKind::buy_fund ? "buy_fund" : + r.kind == BankRequestKind::sell_fund ? "sell_fund" : + r.kind == BankRequestKind::bank_credit ? "bank_credit" : "none"; + out << "{\"kind\":\"" << kind + << "\",\"manager_slot\":" << r.manager_slot << ",\"runtime_club\":" << r.runtime_club + << ",\"revision\":" << r.revision << ",\"amount\":" << r.amount + << ",\"asset_index\":" << r.asset_index << ",\"count\":" << r.count; + if (r.kind == BankRequestKind::bank_credit) { + out << ",\"expected_credit\":["; + for (size_t i = 0; i < r.expected_credit.size(); ++i) { if (i) out << ','; out << r.expected_credit[i]; } + out << "],\"credit_edits\":["; + for (size_t i = 0; i < r.credit_edits.size(); ++i) { + if (i) out << ','; + out << "{\"field\":" << r.credit_edits[i].field << ",\"value\":" << r.credit_edits[i].value << '}'; + } + out << "],\"accept_credit_fees\":" << (r.accept_credit_fees ? "true" : "false") + << ",\"credit_counterparty\":" << r.credit_counterparty; + } + out << '}'; + return out.str(); +} + +BankScreen::BankScreen(const std::filesystem::path& data, BankState state) + : state_(std::move(state)), background_(load_vga(asset_path(data / "KB", "23.VGA"))), + deposit_frame_(load_vga(asset_path(data / "KB", "65.VGA"))), + finance_frame_(load_vga(asset_path(data / "KB", "5.VGA"))), + credit_lender_frame_(load_vga(asset_path(data / "KB", "64.VGA"))), + property_art_(load_vga(asset_path(data / "KB", "7.VGA"))), + calculator_art_(load_vga(asset_path(data / "KB", "6.VGA"))), + widgets_(load_vga(asset_path(data / "KB", "0.VGA"))), + faces_(load_vga(asset_path(data / "KB", "26.VGA"))), + exe_(load_le(asset_path(data, "BMH.exe"))), texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))), + large_font_(load_font(asset_path(data / "F", "BMH2.FNT"))), sprite_font_(data) { + if (background_.width != 320 || background_.height != 240 || state_.manager_slot < 0 || state_.manager_slot > 3) + throw FormatError("bank: unsupported background or state"); + if (state_.credit_counterparty != 0 || state_.credit_lenders.size() > 3) + throw FormatError("bank: invalid initial credit lender state"); + int previous_slot = -1; + for (const auto& lender : state_.credit_lenders) { + if (lender.manager_slot <= previous_slot || lender.manager_slot < 0 || lender.manager_slot > 3 || + lender.manager_slot == state_.manager_slot || lender.counterparty != lender.manager_slot + 1 || + lender.credit.counterparty != lender.counterparty) + throw FormatError("bank: invalid Source-ordered credit lender alternative"); + previous_slot = lender.manager_slot; + } + if (state_.credit.counterparty != 0) + throw FormatError("bank: initial editor context must be the bank counterparty"); + // MaxSharesToBuy patches the KB/5 offscreen buffer once per available + // lender. Subviews restore this frame; the room itself only receives the + // first KB/64 pass below. + if (!state_.credit_lenders.empty()) { + if (credit_lender_frame_.width < 249 || credit_lender_frame_.height < 160 || + finance_frame_.width < 212 || finance_frame_.height < 142) + throw FormatError("bank: truncated credit lender assets"); + for (size_t ordinal = 0; ordinal < state_.credit_lenders.size(); ++ordinal) { + const size_t table = ordinal; + const int sx = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField5 + table), sy = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField6 + table); + const int dx = int(exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField9 + table)) - 0x31; + const int dy = int(exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField10 + table)) - 0x2d; + const int width = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField13 + table), height = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField14 + table); + copy_region(finance_frame_, credit_lender_frame_, sx, sy, dx, dy, width, height); + } + } + bank_credit_ = state_.credit; + if (state_.manager_portrait < 0 || state_.manager_portrait > 11 || state_.badge_sprite < 0 || state_.badge_sprite > 0x1ff) + throw FormatError("bank: invalid manager portrait or badge"); + if (source_badge_fallback(state_.runtime_club)) badge_atlas_ = widgets_; + else badge_atlas_ = load_vga(asset_path(data / "W", std::to_string(state_.badge_sprite >> 3) + ".VGA")); + // A retained notice belongs to the last transaction checkpoint; only the + // matching buy_fund ACK may surface it in this screen instance. + property_notice_open_ = false; +} +void BankScreen::restore_bank_credit() { + state_.credit = bank_credit_; + state_.credit_counterparty = 0; + credit_draft_ = bank_credit_draft(state_.credit); + refresh_credit_rows(); +} +void BankScreen::text_at(Image& out, int x, int y, std::string_view value, uint8_t color) const { + if (x < 0 || y < 0 || y + 6 > out.height || x + font_.text_width(value) > out.width) return; + font_.draw(out, x, y, value, color); +} +void BankScreen::original_text(Image& out, int x, int baseline, std::string_view value, uint8_t color) const { + const std::string bytes = utf8_to_original(value); + const int top = baseline - large_font_.baseline; + if (x < 0 || top < 0 || top + large_font_.height > out.height || + x + large_font_.text_width(bytes) > out.width) return; + large_font_.draw(out, x, top, bytes, color); +} +void BankScreen::body_baseline(Image& out, int x, int baseline, std::string_view value, uint8_t color) const { + body_baseline_raw(out, x, baseline, utf8_to_original(value), color, true); +} +void BankScreen::body_baseline_raw(Image& out, int x, int baseline, std::string_view bytes, + uint8_t color, bool gradient) const { + const std::string owned(bytes); + const int top = baseline - font_.baseline; + if (x < 0 || top < 0 || top + font_.height > out.height || + x + font_.text_width(owned) > out.width) return; + if (!gradient || !state_.gradient_text || exe_.u8(::bmh::layout::TextGradientMode) != 2 || color == 0x40) { + font_.draw(out, x, top, owned, color); + return; + } + unsigned slot = 0; + while (slot < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + slot) != color) ++slot; + if (slot == 32) { font_.draw(out, x, top, owned, color); return; } + int pen_x = x; + for (unsigned char ch : owned) { + const auto& glyph = font_.glyph(ch); + for (int row = 0; row < font_.height; ++row) { + const uint8_t ink = exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + slot * 6 + size_t(row)); + if (!ink) continue; + for (int col = 0; col < glyph.bit_width; ++col) { + const int bit = glyph.bit_offset + col; + if (font_.bitmap[size_t(row) * font_.modulo + size_t(bit / 8)] & (0x80 >> (bit % 8))) { + const int px = pen_x + col; + if (px >= 0 && px < out.width) out.at(px, top + row) = ink; + } + } + } + pen_x += glyph.advance; + } +} +void BankScreen::open_calculator(bool withdrawing) { + calculator_stock_count_ = false; + calculator_property_count_ = false; + withdrawing_ = withdrawing; + calculator_backdrop_ = render(); + calculator_open_ = true; + calculator_max_ = uint32_t(std::clamp( + withdrawing ? int64_t(state_.deposit) : int64_t(state_.balance), 0, 99999999)); + calculator_value_ = calculator_initial_ = 0; + calculator_presets_ = {10, 100, 1000, 10000, 100000, 1000000, 0, calculator_max_}; + for (size_t i = 0; i < 6; ++i) + if (calculator_presets_[i] > calculator_max_) calculator_presets_[i] = UINT32_MAX; +} +void BankScreen::open_stock_calculator(bool selling) { + const auto& selected = state_.stocks.at(size_t(selected_stock_)); + if ((selling ? int(selected.owned) : selected.max_to_buy) <= 0) return; + withdrawing_ = selling; + calculator_backdrop_ = render(); + calculator_open_ = true; + calculator_stock_count_ = true; + calculator_property_count_ = false; + const auto& stock = state_.stocks.at(size_t(selected_stock_)); + calculator_max_ = uint32_t(std::max(0, selling ? int(stock.owned) : stock.max_to_buy)); + calculator_initial_ = selling ? stock.owned : 0; + calculator_value_ = calculator_initial_; + calculator_presets_ = {20, 40, 60, 80, 100, 120, 0, calculator_max_}; + for (size_t i = 0; i < 6; ++i) + if (calculator_presets_[i] > calculator_max_) calculator_presets_[i] = UINT32_MAX; +} +void BankScreen::open_property_calculator(bool selling) { + const auto& selected = state_.funds.at(size_t(selling ? std::max(0, selected_owned_fund_) : selected_fund_)); + const int maximum = selling ? int(selected.owned) : selected.max_to_buy; + if (maximum <= 0) return; + withdrawing_ = selling; + calculator_backdrop_ = render(); + calculator_open_ = true; + calculator_stock_count_ = false; + calculator_property_count_ = true; + calculator_max_ = uint32_t(maximum); + calculator_initial_ = 0; + calculator_value_ = 0; + calculator_presets_ = {1, 2, 3, 4, 5, 6, 0, calculator_max_}; + for (size_t i = 0; i < 6; ++i) + if (calculator_presets_[i] > calculator_max_) calculator_presets_[i] = UINT32_MAX; +} +void BankScreen::open_credit_calculator(int field) { + const auto bounds = bank_credit_bounds(state_.credit, credit_draft_, field); + if (!bounds.available || bounds.maximum < bounds.minimum) return; + calculator_stock_count_ = false; + calculator_property_count_ = false; + calculator_credit_field_ = field; + calculator_minimum_ = bounds.minimum; + calculator_backdrop_ = render(); + calculator_open_ = true; + calculator_max_ = bounds.maximum; + calculator_initial_ = std::min(bounds.initial, bounds.maximum); + calculator_value_ = calculator_initial_; + if (field == 3) { + calculator_presets_ = {6, 12, 18, 24, 30, 36, bounds.minimum, bounds.maximum}; + } else if (field == 2) { + // Source BalanceFromGame's -1 mode centres six presets around the + // annuity (floor to the selected step, then three increments either + // side). Source retains one running value: it clamps that value to + // the minimum before each cell, stores it, then increments the + // clamped value. For small repayments the step is one; otherwise it + // is 1000. + const uint32_t step = calculator_minimum_ < 100000 ? 1u : 1000u; + const uint32_t center = (calculator_initial_ / step) * step; + const uint32_t increment = ((calculator_initial_ / step) / 10) * step; + int64_t running = int64_t(center) - int64_t(3) * increment; + for (size_t i = 0; i < 6; ++i) { + running = std::max(running, calculator_minimum_); + calculator_presets_[i] = running > calculator_max_ ? UINT32_MAX : uint32_t(running); + running += increment; + } + calculator_presets_[6] = calculator_minimum_; + calculator_presets_[7] = calculator_max_; + } else if (field == 0 || field == 6) { + const uint32_t span = calculator_max_ >= calculator_minimum_ ? calculator_max_ - calculator_minimum_ : 0; + const uint32_t step7 = span / 7; + uint32_t factor = 1; + while (factor <= step7 / 10) factor *= 10; + const uint32_t step = (step7 / factor) * factor; + const uint32_t midpoint = calculator_minimum_ + step7; + const uint32_t first = ((midpoint + factor / 2) / factor) * factor; + for (size_t i = 0; i < 6; ++i) { + const uint64_t preset = uint64_t(first) + uint64_t(i) * step; + calculator_presets_[i] = preset > UINT32_MAX ? UINT32_MAX : uint32_t(preset); + } + calculator_presets_[6] = calculator_minimum_; + calculator_presets_[7] = calculator_max_; + } else { + calculator_presets_ = {10, 100, 1000, 10000, 100000, 1000000, calculator_minimum_, calculator_max_}; + } + for (size_t i = 0; i < 6; ++i) + if (calculator_presets_[i] < calculator_minimum_ || calculator_presets_[i] > calculator_max_) + calculator_presets_[i] = UINT32_MAX; +} +void BankScreen::refresh_credit_rows() { + const auto& v = credit_draft_.values; + state_.credit_values[0] = wrap_i32(v[0] - v[6]); + state_.credit_values[1] = wrap_i32(v[1]); + state_.credit_values[2] = wrap_i32(v[2]); + state_.credit_values[3] = wrap_i32(v[3]); + state_.credit_values[4] = credit_draft_.initial_display + ? wrap_i32(state_.credit.saved[3] - state_.credit.saved[4]) : wrap_i32(v[3]); + state_.credit_values[5] = credit_draft_.initial_display + ? wrap_i32(state_.credit.saved[5]) : wrap_i32(v[5]); + state_.credit_values[6] = wrap_i32(v[6]); + state_.credit_values[7] = wrap_i32(v[7]); + for (size_t i = 0; i < state_.credit_values.size(); ++i) { + std::string value = exe_.cstring(::bmh::layout::Bank_OriginalToUtf8_TextPointer2) + format_number(GameState{}, state_.credit_values[i], 8); + value += exe_.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField2); + if (i == 3 || i == 4) { + value += texts_[text_id(::bmh::layout::Bank_OriginalToUtf8_TextPointer7)]; + if (state_.credit_values[i] != 1) value += exe_.cstring(::bmh::layout::Bank_OriginalToUtf8_TextPointer); + } else value += texts_[text_id(::bmh::layout::Bank_OriginalToUtf8_TextPointer6)]; + state_.credit_value_text[i] = original_to_utf8(value); + } +} +BankRequest BankScreen::finish_credit() { + if (!credit_open_ || pending_) return {}; + if (credit_draft_.edits.empty()) { + credit_open_ = false; + restore_bank_credit(); + credit_fee_confirmation_open_ = false; + feedback_.clear(); + return {}; + } + if (state_.credit.counterparty == 0 && + wrap_sum(credit_draft_.fees, credit_draft_.interest_adjustment) != 0 && !credit_fees_accepted_) { + credit_fee_confirmation_open_ = true; + return {}; + } + BankRequest request; + request.kind = BankRequestKind::bank_credit; + request.manager_slot = state_.manager_slot; + request.runtime_club = state_.runtime_club; + request.revision = state_.revision; + request.expected_credit = state_.credit.saved; + request.credit_edits = credit_draft_.edits; + request.accept_credit_fees = credit_fees_accepted_; + request.credit_counterparty = state_.credit_counterparty; + pending_ = request; + feedback_.clear(); + return request; +} +void BankScreen::draw_calculator(Image& out) const { + // BalanceFromGame uses the 113x136 source crop from KB6 at the caller's + // a449d/a449f origin, then draws the source text and 23 calculator cells. + copy_region(out, calculator_art_, 0, 0, 103, 55, 113, 136); + rect(out, 105, 191, 113, 2, 0x40); + rect(out, 216, 57, 2, 136, 0x40); + std::string title = texts_.strings.size() > 838 ? texts_[838] : std::string{}; + title += state_.account_text.empty() ? money(state_.balance) : state_.account_text; + const int title_width = font_.text_width(title); + body_baseline_raw(out, 103 + 8 + (105 - 8) / 2 - title_width / 2, + 55 + 14, title, 0x62, true); + for (int i = 0; i < 15; ++i) { + const int x = 103 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); + const int y = 55 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + copy_region(out, calculator_art_, 0, 136, x, y, 15, 14); + body_baseline_raw(out, x + 5, y + 9, std::string(1, "0123456789DRCJN"[i]), 0x62, false); + } + for (int i = 0; i < 8; ++i) { + if (calculator_presets_[size_t(i)] == UINT32_MAX) continue; + const int x = 103 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i + 15) * 2); + const int y = 55 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i + 15)); + const std::string value = money(calculator_presets_[size_t(i)]); + const int width = font_.text_width(value); + body_baseline_raw(out, x + 47 - width, y + 12, value, 0x62, true); + } + const std::string value = money(calculator_value_); + const int value_width = font_.text_width(value); + body_baseline_raw(out, 103 + 106 - value_width, 55 + 110, value, 0x00, true); +} +void BankScreen::draw_manager_dialog(Image& out, std::string_view message, bool with_ack_button) const { + TaxDialogProjection notice; + notice.manager_name=state_.manager_name; + notice.portrait=state_.manager_portrait; + notice.badge_sprite=state_.badge_sprite; + notice.badge_fallback=source_badge_fallback(state_.runtime_club); + notice.body=utf8_to_original(message); + notice.source_manager_flags=with_ack_button?0x80:0x40; + if(credit_fee_confirmation_open_&&!with_ack_button)notice.kind=TaxDialogKind::question; + draw_source_dialog(out,{widgets_,faces_,badge_atlas_?&*badge_atlas_:nullptr, + font_,large_font_,exe_,sprite_font_,texts_},notice,state_.gradient_text); +} +void BankScreen::draw_investment_warning(Image& out) const { + draw_manager_dialog(out, state_.investment_limit_text, false); +} +void BankScreen::draw_property_notice(Image& out) const { + if (state_.property_notice) draw_manager_dialog(out, state_.property_notice->text, true); +} +void BankScreen::draw_credit_notice(Image& out) const { + if (state_.credit_notice) draw_manager_dialog(out, state_.credit_notice->text, true); +} +void BankScreen::draw_credit_fee_confirmation(Image& out) const { + const auto textd = [&](uint32_t address) { + if (address < ::bmh::layout::TextPointerTable || (address - ::bmh::layout::TextPointerTable) % 4) return std::string{}; + const size_t index = (address - ::bmh::layout::TextPointerTable) / 4; + return index < texts_.strings.size() ? original_to_utf8(texts_[index]) : std::string{}; + }; + const int32_t total = wrap_sum(credit_draft_.fees, credit_draft_.interest_adjustment); + GameState formatting; + formatting.memory.add_block(::bmh::layout::CurrencyMultiplier, 8); + formatting.memory.set32(::bmh::layout::CurrencyMultiplier, uint32_t(state_.credit_currency[0])); + formatting.memory.set32(::bmh::layout::CurrencyDivisor, uint32_t(state_.credit_currency[1])); + const std::string amount = format_number(formatting, total, 0x101); + draw_manager_dialog(out, textd(::bmh::layout::Bank_DrawCreditFeeConfirmation_ExecutableField) + amount + textd(::bmh::layout::Bank_DrawCreditFeeConfirmation_ExecutableField2), false); + +} +void BankScreen::draw_credit_lender_selector(Image& out) const { + if (state_.credit_lenders.size() > 3 || + (!state_.credit_lenders.empty() && + (credit_lender_frame_.width < 249 || credit_lender_frame_.height < 160))) + throw FormatError("bank: truncated credit lender assets"); + for (size_t ordinal = 0; ordinal < state_.credit_lenders.size(); ++ordinal) { + const size_t table = ordinal; + const int sx1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField3 + table), sy1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField4 + table); + const int dx1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField7 + table), dy1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField8 + table); + const int w1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField11 + table), h1 = exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField12 + table); + // FormatError2 routes the 0xc0 argument through the opaque VGA blit; + // the final 0xff is the destination plane mask, not a transparent key. + copy_region(out, credit_lender_frame_, sx1, sy1, dx1, dy1, w1, h1); + } +} +void BankScreen::draw_property_card(Image& out, int property, int y, bool owned) const { + if (property < 0 || property >= int(state_.funds.size())) return; + const auto& item = state_.funds[size_t(property)]; + const int count = owned ? int(item.owned) : 1; + if (owned && count <= 0) return; + const int source_y = (property / 2) * 0x29; + const int source_x = (property % 2) * 0x43; + if (property_art_.width >= source_x + 0x43 && property_art_.height >= source_y + 0x29) + copy_region(out, property_art_, source_x, source_y, 0xae, y - 8, 0x43, 0x29); + const std::string suffix = count > 1 ? item.plural_suffix : item.singular_suffix; + const std::string quantity = count == 1 ? (item.one_quantity_text.empty() ? "1." : item.one_quantity_text) : + (item.quantity_text.empty() ? std::to_string(count) + "." : item.quantity_text); + body_baseline(out, 0x37, y + 6, quantity + item.name + suffix, 0x6a); + const auto address_text = [&](uint32_t address) { + if (address < ::bmh::layout::TextPointerTable || (address - ::bmh::layout::TextPointerTable) % 4) return std::string{}; + const size_t index = (address - ::bmh::layout::TextPointerTable) / 4; + return index < texts_.strings.size() ? original_to_utf8(texts_[index]) : std::string{}; + }; + const std::string price = owned ? item.average_paid_text : item.unit_price_text; + body_baseline(out, 0x37, y + 15, address_text(::bmh::layout::Bank_DrawPropertyCard_TextPointer2) + price, 0x6a); + body_baseline(out, 0x37, y + 24, address_text(::bmh::layout::Bank_DrawPropertyCard_TextPointer3), 0x6a); + body_baseline_raw(out, 0x5f, y + 24, exe_.cstring(::bmh::layout::Bank_DrawPropertyCard_TextPointer) + utf8_to_original(item.unit_price_text), 0x6a, true); +} +uint32_t BankScreen::accept_calculator() { + const uint32_t value = (credit_open_ && calculator_credit_field_ >= 0) + ? std::max(calculator_minimum_, calculator_value_) : calculator_value_; + calculator_open_ = false; + calculator_backdrop_.reset(); + if (credit_open_ && calculator_credit_field_ >= 0) { + if (!edit_bank_credit(state_.credit, credit_draft_, calculator_credit_field_, value)) { + calculator_credit_field_ = -1; + return value; + } + credit_draft_.initial_display = false; + credit_selected_row_ = calculator_credit_field_ == 0 ? 0 : calculator_credit_field_ == 1 ? 1 : + calculator_credit_field_ == 2 ? 2 : calculator_credit_field_ == 3 ? 3 : 6; + refresh_credit_rows(); + calculator_credit_field_ = -1; + return value; + } + amount_text_ = value ? std::to_string(value) : std::string{}; + return value; +} +Image BankScreen::render() const { + Image out = calculator_open_ && calculator_backdrop_ ? *calculator_backdrop_ : background_; + if (!(calculator_open_ && calculator_backdrop_)) { + // PlainWindowFrameUsedBy (bank room): title in KB/54 mode 5 and active manager + // name in the lower title strip. KB/23 contains only the backdrop. + const std::string title = texts_.strings.size() > 1272 ? original_to_utf8(texts_[1272]) : std::string{}; + sprite_font_.draw(out, SpriteFont::centered_title_x(sprite_font_.text_width(title)), 13, title, 5); + sprite_font_.draw(out, 5, 235, original_to_utf8(state_.manager_name), 5); + // MaxSharesToBuy's first KB/64 pass is part of the bank-room base. The + // modal overlays are drawn afterward, leaving the crop's visible + // outer edges around each subview. A calculator instead restores its + // captured backdrop, which already contains this pass. + draw_credit_lender_selector(out); + } + if (calculator_open_) { draw_calculator(out); return out; } + if (finance_open_) { + if (finance_frame_.width < 212 || finance_frame_.height < 142) throw FormatError("bank: truncated finance view asset"); + copy_region(out, finance_frame_, 0, 0, 49, 45, 212, 142); + const auto db = [&](uint32_t address) -> std::string { + if (address < ::bmh::layout::TextPointerTable || (address - ::bmh::layout::TextPointerTable) % 4) return {}; + const size_t index = (address - ::bmh::layout::TextPointerTable) / 4; + if (index >= texts_.strings.size()) return {}; + return original_to_utf8(texts_[index]); + }; + original_text(out, 111, 54, db(::bmh::layout::Bank_OriginalToUtf8_TextPointer5), 0x6a); + // MaxSharesToBuy case 1: the thin rule follows the title at y=0x37. + line(out, 51, 55, 258, 55, 0x6a); + int held_row = 0; + for (size_t i = 0; i < state_.funds.size(); ++i) if (state_.funds[i].owned) { + body_baseline(out, 53, 85 + held_row * 6, state_.finance_fund_labels[i], 0x6a); + body_baseline(out, 169, 85 + held_row * 6, state_.finance_fund_prices[i], 0x6a); + ++held_row; + } + held_row = 0; + for (size_t i = 0; i < state_.stocks.size(); ++i) if (state_.stocks[i].owned) { + const int x = held_row < 6 ? 53 : 156; + const int y = 131 + (held_row % 6) * 6; + body_baseline(out, x, y, state_.finance_stock_labels[i], 0x6a); + body_baseline(out, x + 70, y, state_.finance_stock_prices[i], 0x6a); + ++held_row; + } + for (int i = 0; i < 7; ++i) { + const int x = exe_.u8(::bmh::layout::Bank_OriginalToUtf8_RuntimeField2 + size_t(i)); + const int y = exe_.u8(::bmh::layout::Bank_OriginalToUtf8_RuntimeField3 + size_t(i)); + const uint8_t shade = exe_.u8(::bmh::layout::Bank_OriginalToUtf8_RuntimeField4 + size_t(i)); + body_baseline(out, x, y, db(::bmh::layout::Bank_OriginalToUtf8_RuntimeField6 + uint32_t(i) * 4), 0x6a); + body_baseline_raw(out, x + 42, y, exe_.cstring(::bmh::layout::Bank_OriginalToUtf8_ExecutableField), 0x6a, true); + const int value_x = x + ((i == 4 || i == 6) ? 44 : 49); + const std::string& value = state_.finance_value_text[size_t(i)]; + body_baseline_raw(out, value_x, y, utf8_to_original(value), shade, i == 6); + + } + return out; + } + if (credit_open_) { + if (finance_frame_.width < 212 || finance_frame_.height < 142) + throw FormatError("bank: truncated credit view asset"); + copy_region(out, finance_frame_, 0, 0, 49, 45, 212, 142); + std::string lender_name; + if (state_.credit_counterparty != 0) { + const auto lender = std::find_if(state_.credit_lenders.begin(), state_.credit_lenders.end(), + [&](const auto& candidate) { return candidate.counterparty == state_.credit_counterparty; }); + if (lender != state_.credit_lenders.end()) lender_name = lender->manager_name; + } + const std::string title = texts_[text_id(::bmh::layout::Bank_FormatError_TextPointer)] + + (state_.credit_counterparty == 0 ? texts_[text_id(::bmh::layout::Bank_FormatError_TextPointer6)] : lender_name); + const std::string title_utf8 = original_to_utf8(title); + original_text(out, 154 - large_font_.text_width(utf8_to_original(title_utf8)) / 2, 54, title_utf8, 0x6a); + line(out, 51, 55, 258, 55, 0x6a); + for (int row = 0; row < 8; ++row) { + const int baseline = 77 + row * 9; + body_baseline(out, 53, baseline, state_.credit_labels[size_t(row)], 0x6a); + if (row == 7 || state_.credit_values[1] != 0) + body_baseline(out, 142, baseline, state_.credit_value_text[size_t(row)], 0x6a); + } + const auto draw_button = [&](int x, uint32_t text_address) { + constexpr int y = 174, button_width = 64; + rect(out, x + 2, y + 10, button_width, 2, 0x40); rect(out, x + button_width, y + 2, 2, 10, 0x40); + copy_region(out, widgets_, 24, 74, x, y, 31, 10); + int at = 31, remaining = button_width - 31; + while (remaining > 20) { const int n = std::min(8, remaining - 20); copy_region(out, widgets_, 24, 84, x + at, y, n, 10); at += n; remaining -= n; } + if (remaining > 0) copy_region(out, widgets_, 45 - remaining, 94, x + at, y, remaining, 10); + const size_t id = text_id(text_address); + if (id < texts_.strings.size()) { + const std::string label = original_to_utf8(texts_[id]); + sprite_font_.draw(out, x + (button_width - sprite_font_.text_width(label)) / 2, y + 7, + label, exe_.u8(::bmh::layout::Advertising_Button_RuntimeField)); + } + }; + draw_button(60, ::bmh::layout::Bank_FormatError_RuntimeField18 + 4 * 4); + draw_button(185, ::bmh::layout::Bank_FormatError_RuntimeField18 + 5 * 4); + if (credit_notice_open_) draw_credit_notice(out); + else if (credit_fee_confirmation_open_) draw_credit_fee_confirmation(out); + return out; + } + if (!exchange_open_ && !deposit_open_ && !property_open_ && !credit_open_) { + // Original room (MaxSharesToBuy case 0): access is by the baked Source + // hotspots below; the host-only ASCII shortcut legend is omitted. + return out; + } + if (property_open_) { + if (finance_frame_.width < 212 || finance_frame_.height < 142 || + property_art_.width < 134 || property_art_.height < 123) + throw FormatError("bank: truncated original property assets"); + copy_region(out, finance_frame_, 0, 0, 49, 45, 212, 142); + const auto db = [&](uint32_t address) -> std::string { + if (address < ::bmh::layout::TextPointerTable || (address - ::bmh::layout::TextPointerTable) % 4) return {}; + const size_t index = (address - ::bmh::layout::TextPointerTable) / 4; + return index < texts_.strings.size() ? original_to_utf8(texts_[index]) : std::string{}; + }; + const std::string title = db(::bmh::layout::Bank_FormatError_TextPointer4); + const int title_width = large_font_.text_width(utf8_to_original(title)); + original_text(out, 49 + (261 - 49) / 2 - title_width / 2, 54, title, 0x6a); + line(out, 51, 55, 258, 55, 0x6a); + body_baseline(out, 52, 63, db(::bmh::layout::Bank_FormatError_TextPointer5), 0x5f); + body_baseline(out, 52, 115, db(::bmh::layout::Bank_FormatError_ExecutableField3), 0x5f); + for (const int y : {61, 113}) { + rect(out, 172, y + 1, 71, 45, 0x6a); + rect(out, 173, y + 2, 69, 43, 0x62); + } + if (selected_owned_fund_ >= 0 && selected_owned_fund_ < int(state_.funds.size()) && + state_.funds[size_t(selected_owned_fund_)].owned) + draw_property_card(out, selected_owned_fund_, 72, true); + draw_property_card(out, selected_fund_, 124, false); + const auto source_button = [&](int x, std::string_view label) { + constexpr int width = 64, y = 174; + rect(out, x + 2, y + 10, width, 2, 0x40); + rect(out, x + width, y + 2, 2, 10, 0x40); + copy_region(out, widgets_, 24, 74, x, y, 31, 10); + int at = 31, remaining = width - 31; + while (remaining > 20) { + const int n = std::min(8, remaining - 20); + copy_region(out, widgets_, 24, 84, x + at, y, n, 10); + at += n; remaining -= n; + } + if (remaining > 0) copy_region(out, widgets_, 45 - remaining, 94, x + at, y, remaining, 10); + sprite_font_.draw(out, x + (width - sprite_font_.text_width(label)) / 2, y + 7, + label, exe_.u8(::bmh::layout::Advertising_Button_RuntimeField)); + }; + source_button(60, original_to_utf8(texts_[191])); + source_button(185, original_to_utf8(texts_[192])); + if (property_notice_open_) draw_property_notice(out); + return out; + } + if (exchange_open_) { + if (finance_frame_.width < 212 || finance_frame_.height < 142) + throw FormatError("bank: truncated stock-market frame"); + // MaxSharesToBuy case 0 copies KB5 as the opaque case background. + copy_region(out, finance_frame_, 0, 0, 49, 45, 212, 142); + const auto db = [&](uint32_t address) -> std::string_view { + if (address < ::bmh::layout::TextPointerTable || (address - ::bmh::layout::TextPointerTable) % 4) return {}; + const size_t index = (address - ::bmh::layout::TextPointerTable) / 4; + return index < texts_.strings.size() ? std::string_view(texts_[index]) : std::string_view{}; + }; + body_baseline(out, 59, 52, db(::bmh::layout::Bank_FormatError_TextPointer2), 0x5f); + body_baseline(out, 51, 168, db(::bmh::layout::Bank_FormatError_TextPointer3), 0x5f); + for (size_t i = 0; i < state_.stocks.size(); ++i) { + const auto& stock = state_.stocks[i]; + const int y = 68 + int(i) * 8; + const std::string_view name = db(::bmh::layout::Bank_FormatError_ExecutableField2 + uint32_t(i) * 4); + body_baseline(out, 51, y, name, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField17 + (int(i) == selected_stock_))); + const int x0 = 103; + for (int column = 0; column < 4; ++column) { + const int x = x0 + column * 22; + rect(out, x - 1, y - 7, 21, 9, 0x67); + line(out, x, y, x + 18, y, 0x65); + rect(out, x, y - 5, 19, 5, 0x62); + body_baseline(out, x, y, stock.market_text[size_t(column)], 0x27); + } + for (int marker = 0; marker < 2; ++marker) { + const int x = 190 + marker * 4; + rect(out, x, y - 5, 3, 3, 100); + if (!stock.owned) continue; + const uint32_t average = uint32_t(stock.paid) / stock.owned; + if (!(marker == 0 ? average < stock.price : stock.price <= average)) continue; + rect(out, x, y - 5, 3, 3, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField + size_t(marker) * 2)); + rect(out, x, y - 5, 2, 2, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField2 + size_t(marker) * 2)); + out.at(x, y - 5) = 0x27; // PlotsCallerCurrentPen plots the caller's current pen. + } + + } + const auto& stock = state_.stocks.at(size_t(selected_stock_)); + const int16_t quote_offset = int16_t(uint16_t(stock.price - uint16_t(0x118))); + auto graph_point = [&](int day) { + return 170 - int(stock.history[size_t(day)]) / 2 + int(quote_offset) / 2; + }; + rect(out, 198, 48, 61, 124, 100); + rect(out, 199, 49, 59, 122, 0x6a); + // Abs starts its major-axis accumulator at zero (not half + // a pixel). Abs4 clips endpoints before drawing its three strokes. + const auto source_line = [&](int x0, int y0, int x1, int y1, uint8_t color) { + const int dx = std::abs(x1 - x0), dy = std::abs(y1 - y0); + const int sx = x1 < x0 ? -1 : 1, sy = y1 < y0 ? -1 : 1; + int error = 0; + const auto plot = [&] { if (x0 >= 0 && x0 < out.width && y0 >= 0 && y0 < out.height) out.at(x0,y0) = color; }; + plot(); + for (int step = 0; step < std::max(dx,dy); ++step) { + if (dy < dx) { x0 += sx; error += dy; if (error >= dx) { error -= dx; y0 += sy; } } + else { y0 += sy; error += dx; if (error >= dy) { error -= dy; x0 += sx; } } + plot(); + } + }; + for (int day = 1; day < int(stock.history.size()); ++day) { + int x = day * 2 + 199, previous_x = x - 2; + int previous_y = graph_point(day - 1) + 49, y = graph_point(day) + 49; + if (!((previous_y < 171 || y < 171) && (previous_y > 48 || y > 48))) continue; + if (y > 170) { x += (previous_x - x) * (170 - y) / (previous_y - y); y = 170; } + if (y < 49) { x += (previous_x - x) * (49 - y) / (previous_y - y); y = 49; } + if (previous_y > 170) { previous_x += (x - previous_x) * (170 - previous_y) / (y - previous_y); previous_y = 170; } + if (previous_y < 49) { previous_x += (x - previous_x) * (49 - previous_y) / (y - previous_y); previous_y = 49; } + if (!(previous_x >= 199 && previous_x <= 258 && previous_y >= 49 && previous_y <= 170 && + x >= 199 && x <= 258 && y >= 49 && y <= 170)) continue; + source_line(previous_x, previous_y, x, y, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField15)); + source_line(previous_x, previous_y + 1, x, y + 1, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField15)); + source_line(previous_x, previous_y + 2, x, y + 2, exe_.u8(::bmh::layout::Bank_FormatError_RuntimeField16)); + } + if (visible_tip_) body_baseline(out, 200, 167, db(::bmh::layout::Bank_FormatError_RuntimeField19 + uint32_t(*visible_tip_) * 4), 0xf7); + auto source_button = [&](int x, std::string_view label) { + constexpr int width = 64, y = 174; + rect(out, x + 2, y + 10, width, 2, 0x40); rect(out, x + width, y + 2, 2, 10, 0x40); + copy_region(out, widgets_, 24, 74, x, y, 31, 10); + int at = 31, remain = width - 31; + while (remain > 20) { const int n = std::min(8, remain - 20); copy_region(out, widgets_, 24, 84, x + at, y, n, 10); at += n; remain -= n; } + if (remain > 0) copy_region(out, widgets_, 45 - remain, 94, x + at, y, remain, 10); + sprite_font_.draw(out, x + (width - sprite_font_.text_width(label)) / 2, y + 7, + label, exe_.u8(::bmh::layout::Advertising_Button_RuntimeField)); + }; + source_button(60, original_to_utf8(texts_[191])); + source_button(185, original_to_utf8(texts_[192])); + if (investment_warning_open_) draw_investment_warning(out); + return out; + } + // Case 3 first restores KB5 like every bank subview, then places KB65. + copy_region(out, finance_frame_, 0, 0, 49, 45, 212, 142); + // MaxSharesToBuy case 3: original scene KB/23 plus exact Sparbuch overlay KB/65. + if (deposit_frame_.width < 200 || deposit_frame_.height < 123) throw FormatError("bank: truncated original deposit frame"); + for (int y = 0; y < 123; ++y) for (int x = 0; x < 200; ++x) + out.at(55 + x, 48 + y) = deposit_frame_.pixels[size_t(y) * deposit_frame_.width + x]; + // The Sparbuch page always reports the fixed deposit. The withdrawal + // calculator is an input overlay and does not change the displayed row. + body_baseline(out, 195, 82, state_.deposit_text.empty() ? money(state_.deposit) : state_.deposit_text, 0x00); + auto source_button = [&](int x, std::string_view label) { + const int width = 64, y = 174; + rect(out, x + 2, y + 10, width, 2, 0x40); + rect(out, x + width, y + 2, 2, 10, 0x40); + copy_region(out, widgets_, 24, 74, x, y, 31, 10); + int at = 31, remaining = width - 31; + while (remaining > 20) { + const int n = std::min(8, remaining - 20); + copy_region(out, widgets_, 24, 84, x + at, y, n, 10); + at += n; remaining -= n; + } + if (remaining > 0) copy_region(out, widgets_, 45 - remaining, 94, x + at, y, remaining, 10); + sprite_font_.draw(out, x + (width - sprite_font_.text_width(label)) / 2, y + 7, label, + exe_.u8(::bmh::layout::Advertising_Button_RuntimeField)); + }; + source_button(60, original_to_utf8(texts_[193])); + source_button(185, original_to_utf8(texts_[194])); + return out; +} +BankRequest BankScreen::submit() { + if (pending_) return {}; + if (property_open_ && calculator_property_count_ && calculator_value_ == 0) return {}; + uint32_t value = 0; + const auto [end, ec] = std::from_chars(amount_text_.data(), amount_text_.data() + amount_text_.size(), value); + const uint32_t maximum = (exchange_open_ || property_open_) ? 9999u : 99999999u; + if (exchange_open_ && calculator_stock_count_ && ec == std::errc{} && + end == amount_text_.data() + amount_text_.size() && value == 0) { + feedback_.clear(); + return {}; + } + if (property_open_ && calculator_property_count_ && ec == std::errc{} && + end == amount_text_.data() + amount_text_.size() && value == 0) { + feedback_.clear(); + return {}; + } + if (amount_text_.empty() || ec != std::errc{} || end != amount_text_.data() + amount_text_.size() || value == 0 || value > maximum) { + feedback_ = "UNGUELTIGER BETRAG"; return {}; + } + if (exchange_open_) { + const auto& stock = state_.stocks.at(size_t(selected_stock_)); + const uint32_t stock_max = uint32_t(std::max(0, selling_shares_ ? int(stock.owned) : stock.max_to_buy)); + if (value > stock_max) { + feedback_ = "STUECKZAHL NICHT VERFUEGBAR"; return {}; + } + BankRequest request{selling_shares_ ? BankRequestKind::sell_shares : BankRequestKind::buy_shares, + state_.manager_slot, state_.runtime_club, state_.revision, 0, selected_stock_, int(value)}; + pending_ = request; feedback_.clear(); return request; + } + if (property_open_ && calculator_property_count_) { + const int property = selling_shares_ ? selected_owned_fund_ : selected_fund_; + if (property < 0 || property >= int(state_.funds.size())) return {}; + const auto& selected = state_.funds[size_t(property)]; + if (selling_shares_ ? value > selected.owned : value > uint32_t(std::max(0, selected.max_to_buy))) { + feedback_ = "STUECKZAHL NICHT VERFUEGBAR"; return {}; + } + BankRequest request{selling_shares_ ? BankRequestKind::sell_fund : BankRequestKind::buy_fund, + state_.manager_slot, state_.runtime_club, state_.revision, 0, property, int(value)}; + pending_ = request; feedback_.clear(); return request; + } + const int64_t available = withdrawing_ ? int64_t(state_.deposit) : int64_t(state_.balance); + if (int64_t(value) > std::max(0, available)) { feedback_ = "BETRAG NICHT VERFUEGBAR"; return {}; } + BankRequest request{BankRequestKind::move_to_deposit, state_.manager_slot, state_.runtime_club, + state_.revision, withdrawing_ ? -int32_t(value) : int32_t(value)}; + pending_ = request; feedback_.clear(); return request; +} +BankRequest BankScreen::click(int x, int y, bool right) { + if (credit_notice_open_) { + if (right || (x >= 95 && x <= 220 && y >= 166 && y <= 176)) { + credit_notice_open_ = false; + state_.credit_notice.reset(); + credit_open_ = false; credit_draft_ = {}; credit_fees_accepted_ = false; + restore_bank_credit(); + } + return {}; + } + if (credit_fee_confirmation_open_) { + if (right || (x >= 175 && x <= 250 && y >= 166 && y <= 176)) { + credit_fee_confirmation_open_ = false; + credit_open_ = false; + credit_draft_ = {}; + credit_fees_accepted_ = false; + restore_bank_credit(); + return {}; + } + if (x >= 62 && x <= 137 && y >= 166 && y <= 176) { + credit_fee_confirmation_open_ = false; + credit_fees_accepted_ = true; + return finish_credit(); + } + return {}; + } + if (property_notice_open_) { + if (right || (x >= 95 && x <= 220 && y >= 166 && y <= 176)) { + property_notice_open_ = false; + state_.property_notice.reset(); + } + return {}; + } + if (investment_warning_open_) { investment_warning_open_ = false; return {}; } + if (pending_) return {}; + if (calculator_open_) { + if (right) { calculator_open_ = false; calculator_backdrop_.reset(); calculator_credit_field_ = -1; amount_text_.clear(); return {}; } + for (int i = 0; i < 15; ++i) { + const int key_x = 103 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); + const int key_y = 55 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + if (x < key_x || x >= key_x + 16 || y < key_y || y >= key_y + 14) continue; + if (i < 10) { text(std::to_string(i)); return {}; } + if (i == 10) { calculator_value_ /= 10; return {}; } + if (i == 11) { calculator_value_ = calculator_initial_; return {}; } + if (i == 12) { calculator_value_ = 0; return {}; } + if (i == 13) { accept_calculator(); return credit_open_ ? BankRequest{} : submit(); } + if (i == 14) { calculator_open_ = false; calculator_backdrop_.reset(); calculator_credit_field_ = -1; amount_text_.clear(); return {}; } + } + for (int i = 0; i < 8; ++i) { + const int key_x = 103 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i + 15) * 2); + const int key_y = 55 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i + 15)); + if (calculator_presets_[size_t(i)] != UINT32_MAX && x >= key_x && x < key_x + 53 && + y >= key_y && y < key_y + 14) { calculator_value_ = calculator_presets_[size_t(i)]; return {}; } + } + return {}; + } + if (right) { + if (deposit_open_ || finance_open_ || exchange_open_ || property_open_ || credit_open_) { + const bool leaving_credit = credit_open_; + deposit_open_ = finance_open_ = exchange_open_ = property_open_ = credit_open_ = false; + if (leaving_credit) { credit_draft_ = {}; credit_fees_accepted_ = false; credit_fee_confirmation_open_ = false; restore_bank_credit(); } + amount_text_.clear(); feedback_.clear(); return {}; + } + close_requested_ = true; return {}; + } + if (x < 8 && y > 220) { close_requested_ = true; return {}; } + if (exchange_open_) { + if (y > 61 && y < 157) { + const int selected = (y - 61) >> 3; + if (selected != selected_stock_) visible_tip_.reset(); + selected_stock_ = selected; amount_text_.clear(); return {}; + } + if (x > 50 && x < 200 && y > 162 && y < 167) { + BankRequest request{BankRequestKind::stock_tip, state_.manager_slot, state_.runtime_club, + state_.revision, 0, selected_stock_, 0}; + pending_ = request; return request; + } + if (y >= 174 && y < 183) { + if (x >= 60 && x < 124) { selling_shares_ = false; amount_text_.clear(); open_stock_calculator(false); return {}; } + if (x >= 185 && x < 249) { selling_shares_ = true; amount_text_.clear(); open_stock_calculator(true); return {}; } + } + return {}; + } + if (property_open_) { + if (y >= 174 && y <= 184) { + if (x >= 60 && x <= 124) { selling_shares_ = false; amount_text_.clear(); open_property_calculator(false); return {}; } + if (x >= 185 && x <= 249) { selling_shares_ = true; amount_text_.clear(); open_property_calculator(true); return {}; } + } + if (x > 171 && x < 243 && y >= 61 && y <= 106) { + std::array owned{}; int count = 0; + for (int i = 0; i < int(state_.funds.size()); ++i) + if (state_.funds[size_t(i)].owned) owned[size_t(count++)] = i; + if (count) { + int position = 0; + for (; position < count && owned[size_t(position)] != selected_owned_fund_; ++position) {} + selected_owned_fund_ = owned[size_t((position + 1) % count)]; + } + return {}; + } + if (x > 171 && x < 243 && y >= 113 && y <= 158) { + selected_fund_ = (selected_fund_ + 1) % int(state_.funds.size()); + return {}; + } + return {}; + } + if (credit_open_) { + const std::vector editable_rows = state_.credit_counterparty == 0 + ? std::vector{0, 1, 3, 6} : std::vector{0, 1, 2, 3, 6}; + for (const int row : editable_rows) { + if (y >= 70 + row * 9 && y <= 79 + row * 9) { + credit_selected_row_ = row; + const int field = row == 0 ? 0 : row == 1 ? 1 : row == 2 ? 2 : row == 3 ? 3 : 6; + open_credit_calculator(field); + return {}; + } + } + // MaxSharesToBuy's bottom action confirms the current draft. + if (y >= 174 && y <= 184 && x >= 60 && x <= 124) return finish_credit(); + if (y >= 174 && y <= 184 && x >= 185 && x <= 249) { + credit_open_ = false; credit_draft_ = {}; credit_fees_accepted_ = false; restore_bank_credit(); return {}; + } + return {}; + } + if (!deposit_open_ && !finance_open_ && !exchange_open_ && !property_open_) { + // MaxSharesToBuy's six native bank hitbox slots (Bank_FinishCredit_RuntimeField/Bank_FinishCredit_RuntimeField2/Bank_FinishCredit_RuntimeField3/Bank_FinishCredit_RuntimeField4). + // Stock, financial overview, Immobilien and KASSE are mapped here. + for (int i = 0; i < 5; ++i) { + const int left = exe_.u16(::bmh::layout::Bank_FinishCredit_RuntimeField + size_t(i) * 2); + const int right_edge = exe_.u16(::bmh::layout::Bank_FinishCredit_RuntimeField2 + size_t(i) * 2); + const int top = exe_.u8(::bmh::layout::Bank_FinishCredit_RuntimeField3 + size_t(i)); + const int bottom = exe_.u8(::bmh::layout::Bank_FinishCredit_RuntimeField4 + size_t(i)); + if (x < left || x > right_edge || y < top || y > bottom) continue; + if (i == 0) { exchange_open_ = true; selected_stock_ = 11; visible_tip_.reset(); } + else if (i == 1) finance_open_ = true; + else if (i == 2) { + property_open_ = true; + selected_fund_ = 0; + selected_owned_fund_ = -1; + for (int property = 0; property < int(state_.funds.size()); ++property) + if (state_.funds[size_t(property)].owned) { selected_owned_fund_ = property; break; } + } + else if (i == 3) deposit_open_ = true; + else if (i == 4) { restore_bank_credit(); credit_open_ = true; credit_fees_accepted_ = false; credit_selected_row_ = -1; credit_draft_ = bank_credit_draft(state_.credit); refresh_credit_rows(); } + return {}; + } + // Source tests the five fixed bank hotspots first, then the lender + // hitboxes mapped into slots 5..7, with inclusive edges. + for (size_t i = 0; i < state_.credit_lenders.size(); ++i) { + const size_t table = i + 5; + const int left = exe_.u8(::bmh::layout::Bank_FinishCredit_RuntimeField5 + table), top = exe_.u8(::bmh::layout::Bank_FinishCredit_RuntimeField6 + table); + if (x < left || x > left + 0x11 || y < top || y > top + 0x11) continue; + const auto& lender = state_.credit_lenders[i]; + state_.credit = lender.credit; + state_.credit_counterparty = lender.counterparty; + credit_open_ = true; + credit_fees_accepted_ = false; + credit_fee_confirmation_open_ = false; + credit_selected_row_ = -1; + credit_draft_ = bank_credit_draft(state_.credit); + refresh_credit_rows(); + return {}; + } + return {}; + } + if (finance_open_) { finance_open_ = false; return {}; } + if (deposit_open_ && y >= 174 && y < 186) { + if (x >= 60 && x < 124) open_calculator(false); + else if (x >= 185 && x < 250) open_calculator(true); + } + return {}; +} +BankRequest BankScreen::key(std::string_view key) { + if (credit_notice_open_) { + if (key == "ENTER" || key == "J" || key == "ESC" || key == "ESCAPE") { + credit_notice_open_ = false; state_.credit_notice.reset(); credit_open_ = false; + credit_draft_ = {}; credit_fees_accepted_ = false; restore_bank_credit(); + } + return {}; + } + if (credit_fee_confirmation_open_) { + if (key == "Y" || key == "J" || key == "ENTER") { + credit_fee_confirmation_open_ = false; credit_fees_accepted_ = true; return finish_credit(); + } + if (key == "N" || key == "ESC" || key == "ESCAPE") { + credit_fee_confirmation_open_ = false; credit_open_ = false; credit_draft_ = {}; credit_fees_accepted_ = false; restore_bank_credit(); + } + return {}; + } + if (property_notice_open_) { + if (key == "ESC" || key == "ESCAPE" || key == "ENTER" || key == "J") { + property_notice_open_ = false; + state_.property_notice.reset(); + } + return {}; + } + if (investment_warning_open_) { investment_warning_open_ = false; return {}; } + if (pending_) return {}; + if (calculator_open_) { + if (key == "ESC" || key == "ESCAPE" || key == "N") { calculator_open_ = false; calculator_backdrop_.reset(); calculator_credit_field_ = -1; amount_text_.clear(); return {}; } + if (key == "ENTER" || key == "J") { accept_calculator(); return credit_open_ ? BankRequest{} : submit(); } + if (key == "BACKSPACE" || key == "D") { calculator_value_ /= 10; return {}; } + if (key == "CLEAR" || key == "SPACE" || key == "C") { calculator_value_ = 0; return {}; } + if (key == "R") { calculator_value_ = calculator_initial_; return {}; } + if (key.size() == 1 && key[0] >= '0' && key[0] <= '9') text(key); + return {}; + } + if (key == "ESC" || key == "ESCAPE") { + if (deposit_open_ || finance_open_ || exchange_open_ || property_open_ || credit_open_) { + const bool leaving_credit = credit_open_; + deposit_open_ = finance_open_ = exchange_open_ = property_open_ = credit_open_ = false; amount_text_.clear(); feedback_.clear(); credit_draft_ = {}; credit_fees_accepted_ = false; + if (leaving_credit) restore_bank_credit(); + } else close_requested_ = true; + return {}; + } + if (key == "BACKSPACE" && (deposit_open_ || exchange_open_ || property_open_)) { + deposit_open_ = false; exchange_open_ = false; property_open_ = false; amount_text_.clear(); feedback_.clear(); return {}; + } + if (!deposit_open_ && !exchange_open_ && !finance_open_ && !property_open_ && !credit_open_ && (key == "B" || key == "b")) { exchange_open_ = true; selected_stock_ = 11; visible_tip_.reset(); return {}; } + if (!deposit_open_ && !exchange_open_ && !finance_open_ && !property_open_ && !credit_open_ && (key == "F" || key == "f")) { deposit_open_ = true; return {}; } + if (!deposit_open_ && !exchange_open_ && !finance_open_ && !property_open_ && !credit_open_ && (key == "I" || key == "i")) { + property_open_ = true; selected_fund_ = 0; selected_owned_fund_ = -1; + for (int property = 0; property < int(state_.funds.size()); ++property) + if (state_.funds[size_t(property)].owned) { selected_owned_fund_ = property; break; } + return {}; + } + if (credit_open_) { + if (key == "UP" || key == "DOWN") { + const std::vector rows = state_.credit_counterparty == 0 + ? std::vector{0, 1, 3, 6, 7} : std::vector{0, 1, 2, 3, 6, 7}; + auto it = std::find(rows.begin(), rows.end(), credit_selected_row_); + int at = it == rows.end() ? 0 : int(it - rows.begin()); + at = (at + (key == "DOWN" ? 1 : int(rows.size()) - 1)) % int(rows.size()); + credit_selected_row_ = rows[size_t(at)]; + } + if (key == "N") { credit_open_ = false; credit_draft_ = {}; credit_fees_accepted_ = false; restore_bank_credit(); return {}; } + return {}; + } + if (key == "ENTER") return {}; + if (key == "BACKSPACE") { if (!amount_text_.empty()) amount_text_.pop_back(); return {}; } + return {}; +} +bool BankScreen::text(std::string_view value) { + if (pending_ || investment_warning_open_ || property_notice_open_ || value.empty() || + ((exchange_open_ || property_open_ || deposit_open_) && !calculator_open_)) return false; + if (std::any_of(value.begin(), value.end(), [](unsigned char c) { return c < '0' || c > '9'; })) return false; + if (calculator_open_) { + bool changed = false; + for (unsigned char c : value) { + const uint32_t digit = c - '0'; + if (calculator_value_ <= (calculator_max_ - std::min(calculator_max_, digit)) / 10) { + calculator_value_ = calculator_value_ * 10 + digit; + if (calculator_value_ > calculator_max_) calculator_value_ = calculator_max_; + changed = true; + } else if (calculator_value_ < calculator_max_) { + calculator_value_ = calculator_max_; changed = true; + } + } + amount_text_ = calculator_value_ ? std::to_string(calculator_value_) : std::string{}; + return changed; + } + const auto old = amount_text_; + for (const auto c : value) if (amount_text_.size() < 8) amount_text_.push_back(c); + return amount_text_ != old; +} +void BankScreen::acknowledge(BankState updated) { + if (!pending_) throw FormatError("bank: acknowledgment requires a pending action"); + if (updated.credit.counterparty != 0) + throw FormatError("bank: fresh ACK bank context must remain counterparty zero"); + const bool credit_ack = pending_ && pending_->kind == BankRequestKind::bank_credit; + bmh::BankCreditContext next_bank_credit = updated.credit; + if (credit_ack) { + if (pending_->credit_counterparty != state_.credit_counterparty) + throw FormatError("bank: pending credit counterparty changed"); + const int accepted_counterparty = pending_->credit_counterparty; + if (updated.credit_counterparty != 0 && updated.credit_counterparty != accepted_counterparty) + throw FormatError("bank: fresh credit projection names a different counterparty"); + if (accepted_counterparty == 0) { + next_bank_credit = updated.credit; + updated.credit_counterparty = 0; + } else { + const auto lender = std::find_if(updated.credit_lenders.begin(), updated.credit_lenders.end(), + [&](const auto& candidate) { return candidate.counterparty == accepted_counterparty; }); + if (lender == updated.credit_lenders.end() || lender->manager_slot + 1 != accepted_counterparty || + lender->credit.counterparty != accepted_counterparty) + throw FormatError("bank: fresh projection omitted accepted credit lender"); + next_bank_credit = updated.credit; + updated.credit = lender->credit; + updated.credit_counterparty = accepted_counterparty; + } + const bool expects_notice = credit_draft_.refund > 0; + if (expects_notice != updated.credit_notice.has_value() || + (expects_notice && updated.credit_notice->refund != credit_draft_.refund)) + throw FormatError("bank: missing or mismatched credit refund notice"); + } else if (updated.credit_notice) { + throw FormatError("bank: unexpected credit notice"); + } + const bool expects_property_notice = pending_ && pending_->kind == BankRequestKind::buy_fund && + pending_->asset_index > 0 && pending_->asset_index < int(state_.funds.size()); + if (expects_property_notice) { + if (!updated.property_notice || updated.property_notice->asset_index != pending_->asset_index) + throw FormatError("bank: missing or mismatched property purchase notice"); + } else if (updated.property_notice) { + throw FormatError("bank: unexpected property purchase notice"); + } + bool changed = updated.balance != state_.balance || updated.deposit != state_.deposit || updated.last_tip != state_.last_tip; + changed = changed || updated.credit.saved != state_.credit.saved; + for (size_t i = 0; i < updated.stocks.size(); ++i) + changed = changed || updated.stocks[i].owned != state_.stocks[i].owned || updated.stocks[i].paid != state_.stocks[i].paid; + for (size_t i = 0; i < updated.funds.size(); ++i) + changed = changed || updated.funds[i].owned != state_.funds[i].owned || updated.funds[i].paid != state_.funds[i].paid; + if (!pending_ || updated.manager_slot != state_.manager_slot || updated.runtime_club != state_.runtime_club || + updated.revision <= state_.revision || !changed) + throw FormatError("bank: expected a changed projection for the same manager"); + visible_tip_ = pending_->kind == BankRequestKind::stock_tip ? updated.last_tip : std::nullopt; + // LAB_0004c592 rebuilds the sorted held-type list and preserves its local + // position, rather than the previous raw type, unless the position wraps. + int owned_position = 0; + if (property_open_) { + for (int property = 0; property < selected_owned_fund_; ++property) + if (state_.funds[size_t(property)].owned) ++owned_position; + } + state_ = std::move(updated); + bank_credit_ = next_bank_credit; + property_notice_open_ = state_.property_notice.has_value(); + credit_notice_open_ = credit_ack && state_.credit_notice.has_value(); + if (credit_notice_open_) { + credit_draft_ = bank_credit_draft(state_.credit); + refresh_credit_rows(); + } + if (credit_ack && !credit_notice_open_) { + credit_open_ = false; + credit_draft_ = {}; + credit_fees_accepted_ = false; + restore_bank_credit(); + } + if (property_open_) { + std::array held{}; + int count = 0; + for (int property = 0; property < int(state_.funds.size()); ++property) + if (state_.funds[size_t(property)].owned) held[size_t(count++)] = property; + if (owned_position >= count) owned_position = 0; + selected_owned_fund_ = count ? held[size_t(owned_position)] : -1; + } + pending_.reset(); amount_text_.clear(); feedback_.clear(); + calculator_open_ = false; calculator_backdrop_.reset(); +} +void BankScreen::reject_action(std::string reason) { + if (reason == "credit_no_change") { + pending_.reset(); + credit_open_ = false; credit_draft_ = {}; credit_fees_accepted_ = false; restore_bank_credit(); feedback_.clear(); return; + } + if (!pending_ || reason.empty()) throw FormatError("bank: rejection requires a pending request and reason"); + pending_.reset(); + investment_warning_open_ = reason == "investment_limit" && exchange_open_; + feedback_ = reason == "insufficient_funds" ? "KONTO NICHT GEDECKT" : "AKTION ABGELEHNT"; +} +std::string BankScreen::state_json() const { + auto json = bank_state_json(state_); json.pop_back(); + return json + ",\"withdrawing\":" + (withdrawing_ ? "true" : "false") + ",\"amount_input\":" + + json_quote(amount_text_) + ",\"deposit_open\":" + (deposit_open_ ? "true" : "false") + + ",\"finance_open\":" + (finance_open_ ? "true" : "false") + + ",\"credit_open\":" + (credit_open_ ? "true" : "false") + + ",\"credit_selected_row\":" + std::to_string(credit_selected_row_) + + ",\"credit_fee_confirmation_open\":" + (credit_fee_confirmation_open_ ? "true" : "false") + + ",\"credit_notice_open\":" + (credit_notice_open_ ? "true" : "false") + + ",\"credit_calculator_field\":" + std::to_string(calculator_credit_field_) + + ",\"credit_fees_accepted\":" + (credit_fees_accepted_ ? "true" : "false") + + ",\"credit_edit_count\":" + std::to_string(credit_draft_.edits.size()) + + ",\"investment_warning_open\":" + (investment_warning_open_ ? "true" : "false") + + ",\"calculator_open\":" + (calculator_open_ ? "true" : "false") + + ",\"calculator_value\":" + std::to_string(calculator_value_) + + ",\"exchange_open\":" + (exchange_open_ ? "true" : "false") + ",\"property_open\":" + (property_open_ ? "true" : "false") + + ",\"funds_open\":" + (property_open_ ? "true" : "false") + + ",\"property_notice_open\":" + (property_notice_open_ ? "true" : "false") + + ",\"selected_property_catalog\":" + std::to_string(selected_fund_) + + ",\"selected_owned_property\":" + std::to_string(selected_owned_fund_) + ",\"selected_stock\":" + + std::to_string(selected_stock_) + ",\"selling_shares\":" + (selling_shares_ ? "true" : "false") + + ",\"pending_action\":" + (pending_ ? bank_request_json(*pending_) : "null") + + ",\"feedback\":" + (feedback_.empty() ? "null" : json_quote(feedback_)) + '}'; +} +} // namespace bmh::ui diff --git a/src/ui/bank.hpp b/src/ui/bank.hpp new file mode 100644 index 0000000..323a698 --- /dev/null +++ b/src/ui/bank.hpp @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/bank_credit.hpp" +#include "ui/desk_state.hpp" +#include "ui/manager.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +struct BankState { + int manager_slot = -1, runtime_club = -1; + std::string manager_name, club_name, source; + uint64_t revision = 0; + bool gradient_text = false; + int32_t balance = 0, deposit = 0, credit_line = 0, investment_balance = 0; + std::string balance_text, deposit_text, account_text; + std::string investment_limit_text; + int manager_portrait = 0, badge_sprite = 0; + // MaxSharesToBuy case 1: the seven read-only values shown in the finance view. + std::array finance_values{}; + std::array finance_gains{}; + std::array finance_value_text{}; + std::array finance_gain_text{}; + // Case 4 (bank credit) readonly values as seen before any local edits. + // The source UI only displays the first seven when a credit is outstanding. + std::array credit_values{}; + std::array credit_value_text{}; + std::array credit_labels{}; + bmh::BankCreditContext credit; + // Source MaxSharesToBuy lender candidates. The bank itself is counterparty 0; + // other manager slots use slot+1 and are kept in ascending Source order. + struct CreditLender { + int manager_slot = -1; + int counterparty = 0; + std::string manager_name; + bmh::BankCreditContext credit; + }; + std::vector credit_lenders; + int credit_counterparty = 0; + struct CreditNotice { + int32_t refund = 0; + std::string text; + friend bool operator==(const CreditNotice&, const CreditNotice&) = default; + }; + std::optional credit_notice; + std::array credit_currency{1, 1}; + std::array finance_fund_labels{}, finance_fund_prices{}; + std::array finance_stock_labels{}, finance_stock_prices{}; + struct Stock { + int32_t long_term_value = 0, paid = 0; + int max_to_buy = 0; + uint16_t price = 0, previous_price = 0, owned = 0, trend = 0, trend_age = 0; + std::array history{}; + std::array market_text{}; + }; + std::array stocks{}; + struct Fund { + uint32_t price = 0, paid = 0; + uint16_t owned = 0; + int max_to_buy = 0; + std::string name, unit_price_text, average_paid_text, quantity_text, one_quantity_text; + std::string singular_suffix, plural_suffix; + }; + std::array funds{}; + struct PropertyNotice { + int asset_index = -1; + int32_t additional_cost = 0; + std::string text; + friend bool operator==(const PropertyNotice&, const PropertyNotice&) = default; + }; + std::optional property_notice; + std::optional last_tip; +}; + +enum class BankRequestKind { none, move_to_deposit, buy_shares, sell_shares, stock_tip, buy_fund, sell_fund, bank_credit }; +struct BankRequest { + BankRequestKind kind = BankRequestKind::none; + int manager_slot = -1, runtime_club = -1; + uint64_t revision = 0; + int32_t amount = 0; // positive: account -> fixed deposit; negative: fixed deposit -> account + int asset_index = -1, count = 0; // asset_index addresses a stock or fund as selected by kind + std::array expected_credit{}; + std::vector credit_edits; + bool accept_credit_fees = false; + // 0 the bank (case 4), else the lending manager + 1 (case 5, credit between managers) + int credit_counterparty = 0; + friend bool operator==(const BankRequest&, const BankRequest&) = default; +}; + +BankState bank_from_game(const GameState&, const LeImage&, uint64_t revision); +std::string bank_state_json(const BankState&); +std::string bank_request_json(const BankRequest&); + +class BankScreen { +public: + BankScreen(const std::filesystem::path&, BankState); + Image render() const; + BankRequest click(int x, int y, bool right = false); + BankRequest key(std::string_view); + bool text(std::string_view); + bool close_requested() const { return close_requested_; } + bool timed_notice_open() const { return investment_warning_open_; } + bool expire_timed_notice() { + if(!investment_warning_open_)return false; + investment_warning_open_=false;return true; + } + bool calculator_open() const { return calculator_open_; } + bool credit_open() const { return credit_open_; } + const BankState& state() const { return state_; } + const std::optional& pending() const { return pending_; } + void acknowledge(BankState); + void reject_action(std::string); + std::string state_json() const; +private: + BankState state_; + Image background_, deposit_frame_, finance_frame_, credit_lender_frame_, property_art_, calculator_art_, widgets_, faces_; + std::optional badge_atlas_; + bool investment_warning_open_ = false; + LeImage exe_; + TextDb texts_; + Font font_; + Font large_font_; + SpriteFont sprite_font_; + std::string amount_text_; + std::string feedback_; + std::optional pending_; + std::optional visible_tip_; + bool withdrawing_ = false, deposit_open_ = false, finance_open_ = false, calculator_open_ = false; + bool exchange_open_ = false, property_open_ = false, close_requested_ = false; + bool credit_open_ = false; + bmh::BankCreditContext bank_credit_{}; + void restore_bank_credit(); + int credit_selected_row_ = -1; + bmh::BankCreditDraft credit_draft_{}; + int calculator_credit_field_ = -1; + uint32_t calculator_minimum_ = 0; + bool credit_fee_confirmation_open_ = false, credit_notice_open_ = false; + bool credit_fees_accepted_ = false; + bool selling_shares_ = false; + bool calculator_stock_count_ = false; + bool calculator_property_count_ = false; + int selected_stock_ = 11; + int selected_fund_ = 0; + int selected_owned_fund_ = -1; + bool property_notice_open_ = false; + uint32_t calculator_value_ = 0, calculator_max_ = 0, calculator_initial_ = 0; + std::array calculator_presets_{}; + std::optional calculator_backdrop_; + void text_at(Image&, int, int, std::string_view, uint8_t) const; + void original_text(Image&, int, int, std::string_view, uint8_t) const; + void body_baseline(Image&, int, int, std::string_view, uint8_t) const; + void body_baseline_raw(Image&, int, int, std::string_view, uint8_t, bool gradient) const; + void open_calculator(bool withdrawing); + void open_stock_calculator(bool selling); + void open_property_calculator(bool selling); + void open_credit_calculator(int field); + void refresh_credit_rows(); + BankRequest finish_credit(); + void draw_calculator(Image&) const; + void draw_investment_warning(Image&) const; + void draw_property_notice(Image&) const; + void draw_credit_notice(Image&) const; + void draw_credit_fee_confirmation(Image&) const; + void draw_credit_lender_selector(Image&) const; + void draw_property_card(Image&, int property, int y, bool owned) const; + void draw_manager_dialog(Image&, std::string_view, bool with_ack_button) const; + uint32_t accept_calculator(); + BankRequest submit(); +}; + +} // namespace bmh::ui diff --git a/src/ui/bank_tests.cpp b/src/ui/bank_tests.cpp new file mode 100644 index 0000000..2c258dc --- /dev/null +++ b/src/ui/bank_tests.cpp @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/bank.hpp" +#include "ui/source_notice_test_helpers.hpp" + +#include +#include + +#include "ui/setup.hpp" + +using namespace bmh; +using namespace bmh::ui; + +namespace { +int failures = 0; +void check(bool ok, const char* name) { if (!ok) { std::fprintf(stderr, "FAIL: %s\n", name); ++failures; } } +} + +int main(int argc, char** argv) { + if (argc != 2) return 2; + try { + BankState state; state.manager_slot = 0; state.runtime_club = 3; state.manager_name = "Nobody"; + state.club_name = "Deutschland"; state.revision = 8; state.balance = 80000; state.deposit = 120000; + state.source = "engine_projection"; + BankScreen screen(argv[1], state); + check(screen.render().width == 320, "original bank room canvas"); + check(screen.click(270, 90).kind == BankRequestKind::none && screen.state_json().find("\"deposit_open\":true") != std::string::npos, + "Kasse opens the deposit view locally"); + screen.click(90, 180); + check(screen.calculator_open(), "Einzahlen button opens the original calculator"); + check(!screen.text("-500"), "rejects non-digit input"); + check(screen.text("50000"), "accepts numeric amount"); + auto request = screen.key("ENTER"); + check(request.kind == BankRequestKind::move_to_deposit && request.amount == 50000 && + request.manager_slot == 0 && request.runtime_club == 3 && request.revision == 8, + "deposit request carries context"); + check(screen.key("ENTER").kind == BankRequestKind::none, "duplicate submit suppressed"); + BankState updated = state; updated.revision = 9; updated.balance = 30000; updated.deposit = 170000; + screen.acknowledge(updated); + check(screen.state().balance == 30000 && screen.state().deposit == 170000 && !screen.pending() && + !screen.calculator_open() && screen.state_json().find("\"deposit_open\":true") != std::string::npos, + "authoritative acknowledgement returns to the Sparbuch view"); + + BankScreen withdrawal(argv[1], state); + withdrawal.click(270, 90); + withdrawal.click(210, 180); withdrawal.text("20000"); + check(withdrawal.calculator_open(), "Abheben button opens the original calculator"); + request = withdrawal.key("ENTER"); + check(request.amount == -20000, "withdrawal request sign"); + withdrawal.reject_action("amount_unavailable"); + check(withdrawal.state().balance == state.balance && withdrawal.state().deposit == state.deposit && !withdrawal.pending(), + "rejection keeps projection unchanged"); + + BankScreen capped(argv[1], state); + capped.click(270, 90); capped.click(90, 180); capped.text("80001"); + check(capped.state_json().find("\"calculator_value\":80000") != std::string::npos, + "calculator clamps entries to the funded account amount"); + request = capped.key("ENTER"); + check(request.kind == BankRequestKind::move_to_deposit && request.amount == 80000, + "funded maximum remains a valid deposit request"); + BankScreen escape(argv[1], state); + escape.click(270, 90); escape.click(90, 180); + escape.key("ESC"); + check(!escape.calculator_open() && !escape.close_requested(), "escape closes calculator locally"); + escape.key("ESC"); + check(!escape.close_requested() && escape.state_json().find("\"deposit_open\":false") != std::string::npos, + "second escape returns from the Sparbuch to the room"); + escape.key("ESC"); + check(escape.close_requested(), "third escape exits the bank room"); + + BankScreen passbook_left(argv[1], state), passbook_right(argv[1], state); + passbook_left.click(270, 90); passbook_right.click(270, 90); + const auto source_passbook = passbook_left.render(); + passbook_right.click(210, 180); + passbook_right.key("ESC"); + check(passbook_right.render().pixels == source_passbook.pixels, + "withdrawal mode keeps the Source passbook balance unchanged until ACK"); + + BankScreen finance(argv[1], state); + finance.click(70, 80); + check(finance.state_json().find("\"finance_open\":true") != std::string::npos && + finance.render().width == 320, "Source finance hitbox opens the seven-row read-only overview"); + check(finance.click(70, 80).kind == BankRequestKind::none && + finance.state_json().find("\"finance_open\":false") != std::string::npos, + "finance overview closes locally without a game request"); + + state.stocks[2].price = 1000; state.stocks[2].owned = 5; state.stocks[2].max_to_buy = 20; + BankScreen exchange(argv[1], state); + exchange.key("B"); + const auto before_render = exchange.state_json(); + const auto rendered = exchange.render(); + check(rendered.width == 320 && rendered.pixels == exchange.render().pixels && + exchange.state_json() == before_render, + "stock screen renders repeatably without changing its projection"); + check(exchange.state_json().find("\"selected_stock\":11") != std::string::npos, "Original opens SKYNET row 11"); + exchange.click(300, 64 + 2 * 8); + check(exchange.state_json().find("\"selected_stock\":2") != std::string::npos, + "Source row hitbox selects by y without an invented x gate"); + exchange.click(70, 178); + check(exchange.calculator_open() && exchange.state_json().find("\"calculator_value\":0") != std::string::npos, + "KAUFEN opens the Source share-count calculator at zero"); + exchange.text("3"); + request = exchange.key("ENTER"); + check(request.kind == BankRequestKind::buy_shares && request.asset_index == 2 && request.count == 3 && + request.revision == state.revision && !exchange.calculator_open(), + "share purchase request carries selected stock, count and current revision"); + + exchange.reject_action("investment_limit"); + check(exchange.state_json().find("\"investment_warning_open\":true") != std::string::npos && !exchange.pending(), + "Source board rejection opens the information dialog"); + bmh::ui::test::expect_notice_symbols(exchange.render(),load_vga(asset_path(std::filesystem::path(argv[1])/"KB","0.VGA"))); + check(exchange.timed_notice_open(),"investment warning uses Source timed mode"); + auto expired_warning=exchange; + check(expired_warning.expire_timed_notice()&&!expired_warning.timed_notice_open()&& + !expired_warning.pending()&&!expired_warning.close_requested(),"warning expiry leaves its caller open without a request"); + auto selected_badge=state;selected_badge.badge_sprite=91; + BankScreen real_badge(argv[1],selected_badge);real_badge.key("B");real_badge.click(300,80);real_badge.click(70,178); + real_badge.text("1");real_badge.key("ENTER");real_badge.reject_action("investment_limit"); + const auto badge_image=real_badge.render();const auto w11=load_vga(asset_path(std::filesystem::path(argv[1])/"W","11.VGA")); + for(int yy=0;yy<38;++yy)for(int xx=0;xx<38;++xx) + check(badge_image.pixels[size_t(89+yy)*320+54+xx]==w11.pixels[size_t(yy)*w11.width+3*38+xx], + "a real manager's badge selector91 must remain W11 tile3, not neutral art"); + exchange.key("ESC"); + check(exchange.state_json().find("\"investment_warning_open\":false") != std::string::npos && + exchange.state_json().find("\"exchange_open\":true") != std::string::npos, + "warning escape dismisses the notice and keeps the exchange open"); + exchange.key("ESC"); exchange.key("B"); + check(exchange.state_json().find("\"selected_stock\":11") != std::string::npos, + "reopening exchange restores Source default selection"); + exchange.click(205,178); + check(!exchange.calculator_open(), "zero holdings cannot open a sale calculator"); + + BankScreen sale(argv[1], state); + sale.key("B"); sale.click(55, 64 + 2 * 8); sale.click(200, 178); + check(sale.calculator_open() && sale.state_json().find("\"calculator_value\":5") != std::string::npos, + "VERKAUFEN starts at the full Source-owned share count"); + request = sale.key("ENTER"); + check(request.kind == BankRequestKind::sell_shares && request.asset_index == 2 && request.count == 5, + "share sale emits the selected raw stock and count"); + + BankScreen max_buy(argv[1], state); + max_buy.key("B"); max_buy.click(55, 80); max_buy.click(70, 178); + max_buy.text("999"); + check(max_buy.state_json().find("\"calculator_value\":20") != std::string::npos, + "share-count input clamps to the Engine-projected purchasable maximum"); + + BankScreen tip(argv[1], state); + tip.key("B"); tip.click(55, 64 + 2 * 8); + const auto tip_request = tip.click(100, 164); + check(tip_request.kind == BankRequestKind::stock_tip && tip_request.asset_index == 2 && tip_request.count == 0, + "expert tip uses the Original caption hitbox"); + check(tip.click(100, 164).kind == BankRequestKind::none, "expert tip cannot be duplicated while pending"); + + state.funds[1].price = 100000; + state.funds[1].paid = 180000; + state.funds[1].owned = 2; + state.funds[1].max_to_buy = 4; + state.funds[1].name = "REIHENHAUS"; + state.funds[1].unit_price_text = "100.000 EU."; + state.funds[1].average_paid_text = "90.000 EU."; + state.funds[1].quantity_text = "2."; + state.funds[1].one_quantity_text = "1."; + state.funds[1].singular_suffix = ""; + state.funds[1].plural_suffix = ""; + BankScreen property(argv[1], state); + check(property.key("I").kind == BankRequestKind::none && + property.state_json().find("\"property_open\":true") != std::string::npos, + "I opens the original Immobilien screen locally"); + const auto property_pixels = property.render().pixels; + check(property_pixels == property.render().pixels && + property.state_json().find("\"selected_owned_property\":1") != std::string::npos, + "property cards render repeatably with the first owned type selected"); + const auto exe = load_le(asset_path(std::filesystem::path(argv[1]), "BMH.exe")); + const int property_x = (exe.u16(::bmh::layout::Bank_FinishCredit_RuntimeField + 2 * 2) + exe.u16(::bmh::layout::Bank_FinishCredit_RuntimeField2 + 2 * 2)) / 2; + const int property_y = (exe.u8(::bmh::layout::Bank_FinishCredit_RuntimeField3 + 2) + exe.u8(::bmh::layout::Bank_FinishCredit_RuntimeField4 + 2)) / 2; + BankScreen property_hotspot(argv[1], state); + property_hotspot.click(property_x, property_y); + check(property_hotspot.state_json().find("\"property_open\":true") != std::string::npos, + "Original bank hotspot index 2 opens Immobilien"); + property.click(200, 130); + check(property.state_json().find("\"selected_property_catalog\":1") != std::string::npos, + "lower Source preview advances the catalog type only"); + property.click(80, 178); + check(property.calculator_open() && property.state_json().find("\"calculator_value\":0") != std::string::npos, + "property purchase opens the Source count calculator at zero"); + check(property.key("ENTER").kind == BankRequestKind::none && !property.pending(), + "zero property count closes without a mutation request"); + property.click(80, 178); property.text("3"); + request = property.key("ENTER"); + check(request.kind == BankRequestKind::buy_fund && request.asset_index == 1 && request.count == 3 && + request.revision == state.revision, + "property purchase emits selected raw type, count and revision only"); + property.reject_action("test_reject"); + + BankScreen property_sale(argv[1], state); + property_sale.key("I"); property_sale.click(200, 178); + check(property_sale.calculator_open() && property_sale.state_json().find("\"calculator_value\":0") != std::string::npos, + "property sale also starts its count calculator at zero"); + property_sale.text("2"); + request = property_sale.key("ENTER"); + check(request.kind == BankRequestKind::sell_fund && request.asset_index == 1 && request.count == 2, + "property sale binds to the selected owned raw type"); + + BankScreen no_property_room(argv[1], state); + no_property_room.key("I"); no_property_room.click(80, 178); + check(!no_property_room.calculator_open(), "zero affordable quantity does not open a property calculator"); + + BankState two_owned = state; + two_owned.funds[0].owned = 1; + BankScreen cards(argv[1], two_owned); + cards.key("I"); + cards.click(200, 80); + check(cards.state_json().find("\"selected_owned_property\":1") != std::string::npos && + cards.state_json().find("\"selected_property_catalog\":0") != std::string::npos, + "owned-card click advances only through held types"); + cards.click(200, 80); + check(cards.state_json().find("\"selected_owned_property\":0") != std::string::npos, + "owned-card selection wraps to the first held type"); + for (int i = 0; i < 6; ++i) cards.click(200, 130); + check(cards.state_json().find("\"selected_property_catalog\":0") != std::string::npos && + cards.state_json().find("\"selected_owned_property\":0") != std::string::npos && + !cards.pending(), "catalog selection wraps across all six types without an action"); + + BankState insertion = state; + insertion.funds[0].max_to_buy = 1; + BankScreen insert_owned(argv[1], insertion); + insert_owned.key("I"); insert_owned.click(124, 184); insert_owned.text("1"); + check(insert_owned.key("ENTER").kind == BankRequestKind::buy_fund, + "Source inclusive button boundary submits the flat purchase"); + insertion.revision += 1; + insertion.funds[0].owned = 1; + insert_owned.acknowledge(insertion); + check(insert_owned.state_json().find("\"selected_owned_property\":0") != std::string::npos, + "Source held-list rebuild retains position when an earlier type is inserted"); + + BankScreen property_notice(argv[1], state); + property_notice.key("I"); property_notice.click(200, 130); + property_notice.click(80, 178); property_notice.text("1"); + request = property_notice.key("ENTER"); + BankState notice_state = state; + notice_state.revision = state.revision + 1; + notice_state.balance -= 105000; + notice_state.funds[1].owned += 1; + notice_state.funds[1].paid += 105000; + notice_state.property_notice = BankState::PropertyNotice{1, 5000, "Renovierungskosten 5.000 EU."}; + property_notice.acknowledge(notice_state); + check(property_notice.state_json().find("\"property_notice_open\":true") != std::string::npos && + property_notice.state().property_notice->additional_cost == 5000, + "only an authoritative property ACK opens the manager notice"); + property_notice.key("ESC"); + check(property_notice.state_json().find("\"property_notice_open\":false") != std::string::npos && + !property_notice.state().property_notice, + "property notice dismissal is local and creates no follow-up request"); + + BankScreen credit(argv[1], state); + const auto credit_before = credit.state_json(); + credit.click(70, 100); // EXE bank hotspot slot 4: x64..86, y96..107 + check(credit.credit_open() && credit.render().width == 320 && + credit.state_json().find("\"credit_open\":true") != std::string::npos, + "Source bank hotspot 4 opens the original credit view"); + const auto credit_frame = credit.render(); + check(credit_frame.pixels == credit.render().pixels && !credit.pending() && + credit.state().balance == state.balance && credit.state().credit_line == state.credit_line, + "credit view rerender and field selection are readonly"); + credit.click(10, 77); // Source row input has a y gate, no invented x gate + check(credit.state_json().find("\"credit_selected_row\":0") != std::string::npos && !credit.pending(), + "credit row selection uses the original row baseline without a request"); + credit.key("ESC"); + check(!credit.credit_open() && credit.state().balance == state.balance && !credit.pending(), + "closing the credit projection cannot mutate balances or create a loan request"); + check(credit_before.find("\"revision\":8") != std::string::npos, + "credit view starts from the same bank projection revision"); + + BankScreen credit_cancel(argv[1], state); + credit_cancel.click(70, 100); + const auto credit_room_balance = credit_cancel.state().balance; + const auto credit_room_revision = credit_cancel.state().revision; + credit_cancel.click(200, 178); // Original ABBRUCH button, no request. + check(!credit_cancel.credit_open() && !credit_cancel.pending() && + credit_cancel.state().balance == credit_room_balance && + credit_cancel.state().revision == credit_room_revision, + "credit cancel returns to the bank room without booking or advancing revision"); + + BankRequest credit_envelope; + credit_envelope.kind = BankRequestKind::bank_credit; + credit_envelope.manager_slot = 1; credit_envelope.runtime_club = 12; credit_envelope.revision = 19; + credit_envelope.expected_credit = {100, 200, 300, 4, 1, 2}; + credit_envelope.credit_edits = {{0, 1000}, {3, 12}}; + credit_envelope.accept_credit_fees = true; + const auto encoded_credit = bank_request_json(credit_envelope); + check(encoded_credit.find("\"kind\":\"bank_credit\"") != std::string::npos && + encoded_credit.find("\"expected_credit\":[100,200,300,4,1,2]") != std::string::npos && + encoded_credit.find("\"field\":3,\"value\":12") != std::string::npos && + encoded_credit.find("\"accept_credit_fees\":true") != std::string::npos, + "credit envelope preserves snapshot, ordered edits and explicit fee consent"); + + // Exercise the live Source rate table and a valid, zero-debt credit context. + GameState credit_game; + credit_game.manager_teams = {0}; + credit_game.manager_records.assign(0xb0c, 0); + credit_game.manager_records[0x314] = 0x20; + credit_game.manager_records[0x315] = 0xa1; // cash = 41,000 + credit_game.memory.add_block(::bmh::layout::Loans, 0x78); + const auto data = std::filesystem::path(argv[1]); + const auto executable = load_le(asset_path(data, "BMH.exe")); + const auto valid_credit = bank_credit_context(credit_game, executable, 0); + check(valid_credit.available, "real executable supplies a valid credit rate table"); + BankState valid_credit_state = state; + valid_credit_state.credit = valid_credit; + BankScreen valid_credit_screen(data, valid_credit_state); + valid_credit_screen.click(70, 100); + valid_credit_screen.click(10, 70); + check(valid_credit_screen.calculator_open(), "valid empty loan context opens the bounded principal calculator"); + check(valid_credit_screen.key("ENTER").kind == BankRequestKind::none && + valid_credit_screen.credit_open() && !valid_credit_screen.pending() && + valid_credit_screen.state_json().find("\"credit_edit_count\":1") != std::string::npos, + "calculator acceptance stages a local edit without an engine request"); + const auto valid_credit_request = valid_credit_screen.click(70, 178); + check(valid_credit_request.kind == BankRequestKind::bank_credit && + valid_credit_request.expected_credit == valid_credit.saved && + valid_credit_request.credit_edits == std::vector{{0, 1000}} && + !valid_credit_request.accept_credit_fees, + "OK emits the source-bounded principal edit with original identity snapshot"); + } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); ++failures; } + return failures ? 1 : 0; +} diff --git a/src/ui/calendar.cpp b/src/ui/calendar.cpp new file mode 100644 index 0000000..074d392 --- /dev/null +++ b/src/ui/calendar.cpp @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/calendar.hpp" +#include "game/schedule.hpp" + +#include +#include +#include + +#include "game/messages.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +namespace bmh::ui { + +CalendarCell calendar_cell(const CalendarDayProjection& day) { + const auto& date = day.date; + if (date.month < 1 || date.month > 12 || date.day < 1 || date.day > 31 || + date.weekday < 0 || date.weekday > 6) + throw FormatError("calendar: invalid date geometry"); + const int month = (date.month + 5) % 12; + const int first_weekday = (date.weekday - (date.day - 1) % 7 + 7) % 7; + const int week = (first_weekday + date.day - 1) / 7; + return {28 + (month % 4) * 70 + week * 12, + 29 + (month / 4) * 70 + date.weekday * 8, 11, 8}; +} + +CalendarScreen::CalendarScreen(const std::filesystem::path& data, CalendarState state, + std::string manager_name, bool decorated_background, int runtime_club, + DeskRequest owner) + : state_(std::move(state)), + background_(load_vga(asset_path(data / "KB", "129.VGA"))), + atlas_(load_vga(asset_path(data / "KB", "55.VGA"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))), sprite_font_(data), + exe_(load_le(asset_path(data, "BMH.exe"))), texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + decorated_background_(decorated_background), owner_(owner) { + if (runtime_club >= 0) { + // TeamLeague2 returns zero for team handles above0x164 (national included). + int league = 0, boundary = 0; + if (runtime_club <= 0x164) { + for (; league < 9; ++league) { + boundary += exe_.u8(::bmh::layout::LeagueSizes + uint32_t(league)); + if (runtime_club < boundary) break; + } + } + // DE shares the third-tier bit between leagues 2/3; EN division 3 + // has its own bit. Use the loaded calendar topology for hit eligibility. + active_calendar_class_ = league < kLeagueCount ? kLeagueBit[league] : -1; + } + (void)manager_name; // Source calendar's initial footer is empty, not a manager title. + if (state_.season_start_counter > std::numeric_limits::max() - 366 || + background_.width != 320 || background_.height != 240 || + atlas_.width != 320 || atlas_.height < 209 || + (state_.days.size() != 365 && state_.days.size() != 366) || + state_.current_day < 0 || size_t(state_.current_day) >= state_.days.size()) + throw FormatError("calendar: invalid annual projection or original assets"); + for (size_t index = 0; index < state_.days.size(); ++index) { + const auto& day = state_.days[index]; + const auto expected = desk_date(state_.season_start_counter + uint32_t(index), exe_); + if (day.season_day != int(index) - state_.leading_days || + day.day_counter != state_.season_start_counter + index || + day.date.year != expected.year || day.date.month != expected.month || + day.date.day != expected.day || day.date.weekday != expected.weekday || + day.current_day != (int(index) == state_.current_day)) + throw FormatError("calendar: inconsistent owned date projection"); + (void)calendar_cell(day); + } + const auto& first = state_.days.front().date; + const auto& last = state_.days.back().date; + const auto next = desk_date(state_.days.back().day_counter + 1, exe_); + if (first.month != 7 || first.day != 1 || last.month != 6 || last.day != 30 || + next.month != 7 || next.day != 1) + throw FormatError("calendar: projection is not a complete July-June season"); +} + +void CalendarScreen::text(Image& out, int x, int baseline, std::string_view bytes, uint8_t color) const { + // TextWidth3 refuses text outside the original screen; no UTF-8 enters BMH3. + const int top = baseline - font_.baseline; + if (x >= 0 && top >= 0 && top + font_.height <= out.height && + x + font_.text_width(bytes) <= out.width) + font_.draw(out, x, top, bytes, color); +} + +std::string CalendarScreen::information(const CalendarDayProjection& day) const { + // CalendarCell's generic competition footer. Club-specific fixture/score detail + // remains outside this read-only calendar packet. + std::string result; + if ((day.raw_entry & 0x7fff) == 0) return result; + for (int bit = 0; bit < 19; ++bit) { + if (!(day.competitions & (uint32_t(1) << bit))) continue; + if (!result.empty()) result += exe_.cstring(::bmh::layout::Calendar_Information_ExecutableField); + if (bit < 4) result += std::to_string(bit + 1) + texts_[(::bmh::layout::Calendar_Information_TextPointer3 - ::bmh::layout::TextPointerTable) / 4]; + else if (bit == 4) result += texts_[(::bmh::layout::Calendar_Information_TextPointer4 - ::bmh::layout::TextPointerTable) / 4]; + else if (bit < 16) { + const auto& label = texts_[(::bmh::layout::Calendar_Information_TextPointer2 - ::bmh::layout::TextPointerTable) / 4 + size_t(bit)]; + result += result.size() + label.size() < 30 ? label : exe_.cstring(::bmh::layout::Calendar_Information_TextPointer); + } else result += texts_[((bit == 16 ? ::bmh::layout::Calendar_Information_TextPointer5 : ::bmh::layout::Calendar_Information_TextPointer6) - ::bmh::layout::TextPointerTable) / 4]; + } + return result; +} + +Image CalendarScreen::render() const { + auto out = decorated_background_ ? background_ : Image(320, 240); + if (!decorated_background_) { + for (int y = 4; y <= 16; ++y) for (int x = 0; x < 320; ++x) out.at(x,y) = 0x44; + for (int y = 5; y <= 15; ++y) for (int x = 1; x < 319; ++x) out.at(x,y) = 0x39; + for (int y = 228; y <= 237; ++y) for (int x = 0; x < 320; ++x) out.at(x,y) = 0x44; + for (int y = 229; y <= 236; ++y) for (int x = 1; x < 319; ++x) out.at(x,y) = 0x39; + } + const auto title_address = state_.reschedule_manager >= 0 ? ::bmh::layout::Calendar_Render_ExecutableField3Unsigned : + state_.friendly_selection ? ::bmh::layout::Calendar_Render_ExecutableField2Unsigned : ::bmh::layout::Calendar_Render_ExecutableFieldUnsigned; + const auto title = original_to_utf8(texts_[(title_address - ::bmh::layout::TextPointerTable) / 4]); + sprite_font_.draw(out, SpriteFont::centered_title_x(sprite_font_.text_width(title)), 13, title); + // FormatError2: opaque KB55 crop 320x209 at (0,18). + for (int y = 0; y < 209; ++y) for (int x = 0; x < 320; ++x) out.at(x, y + 18) = atlas_.pixels[size_t(y) * atlas_.width + x]; + for (int row = 0; row < 3; ++row) for (int weekday = 0; weekday < 7; ++weekday) + text(out, 8, 36 + weekday * 8 + row * 70, + texts_[(::bmh::layout::Calendar_Render_TextPointer - ::bmh::layout::TextPointerTable) / 4 + size_t(weekday)], weekday == 6 ? 0xf7 : 0x6a); + for (int month = 0; month < 12; ++month) { + const auto& label = texts_[(::bmh::layout::Calendar_Render_TextPointer2 - ::bmh::layout::TextPointerTable) / 4 + size_t((month + 6) % 12 + 1)]; + text(out, 61 + (month % 4) * 70 - font_.text_width(label) / 2, + 25 + (month / 4) * 70, label, 0x6a); + } + for (const auto& day : state_.days) { + const auto cell = calendar_cell(day); + // CalendarCell colors every Source-eligible date in the calendar's local + // copy; it does not draw persistent boxes around targets or moved dates. + const uint8_t color = day.current_day ? 0xf7 : + (day.reschedule_target || day.friendly_target) ? ((day.competitions & 0x1c0) != 0 ? 0x7a : 0x51) : + day.competitions != 0 && day.competitions != 0x800000 ? 0x27 : 0x6a; + text(out, cell.x + 1, cell.y + 7, format_number(GameState{}, day.date.day, 0x82), color); + if (selected_source_day_ == day.season_day) { + for (int x = cell.x; x < cell.x + cell.width; ++x) { + out.at(x,cell.y + 1) = 0xf7; out.at(x,cell.y + 7) = 0xf7; + } + for (int y = cell.y + 1; y <= cell.y + 7; ++y) { + out.at(cell.x,y) = 0xf7; out.at(cell.x + 10,y) = 0xf7; + } + } + } + if (selected_day_ >= 0) { + const auto& day = state_.days[size_t(selected_day_)]; + const auto cell = calendar_cell(day); + // InclusiveHoverOutlineAtYHitThroughYHit's inclusive hover outline at yHit+1 through yHit+7. + const uint8_t hover_color = (day.raw_entry & 0x8000) || day.reschedule_target || day.friendly_target ? 0x75 : 0x27; + for (int x = cell.x; x < cell.x + cell.width; ++x) { + out.at(x,cell.y + 1) = hover_color; out.at(x,cell.y + 7) = hover_color; + } + for (int y = cell.y + 1; y <= cell.y + 7; ++y) { + out.at(cell.x,y) = hover_color; out.at(cell.x + 10,y) = hover_color; + } + const auto footer = original_to_utf8(information(day)); + sprite_font_.draw(out, 5, 235, footer); + } + return out; +} + +bool CalendarScreen::move(int x, int y) { + if (close_requested_) return false; + // Source removes the hover outline and footer when leaving all day cells. + for (size_t index = 0; index < state_.days.size(); ++index) { + const auto& day = state_.days[index]; + const auto cell = calendar_cell(day); + if (x >= cell.x && x < cell.x + cell.width && y >= cell.y && y < cell.y + cell.height) { + if (selected_day_ == int(index)) return false; + selected_day_ = int(index); return true; + } + } + const bool changed = selected_day_ != -1; + selected_day_ = -1; + return changed; +} + +bool CalendarScreen::click(int x, int y, bool right) { + if (close_requested_) return false; + if (right) { close_requested_ = true; return true; } + const bool changed = move(x,y); + if (selected_day_ >= 0) { + const auto& day = state_.days[size_t(selected_day_)]; + if (state_.reschedule_manager >= 0) { + if (pending_reschedule_) return changed; + if (selected_source_day_ >= 0) { + const auto option = std::find_if(state_.reschedule_options.begin(), state_.reschedule_options.end(), + [&](const RescheduleOption& item) { return item.match.day == selected_source_day_; }); + if (option != state_.reschedule_options.end()) { + if (day.season_day == selected_source_day_) { selected_source_day_ = -1; return true; } + if (std::find(option->target_days.begin(), option->target_days.end(), day.season_day) != option->target_days.end()) { + pending_reschedule_ = RescheduleAction{owner_, RescheduleActionKind::move, + option->match, day.season_day}; + return true; + } + selected_source_day_ = -1; + } + } + const auto moved = std::find_if(state_.moved_matches.begin(), state_.moved_matches.end(), + [&](const LeagueMatchRef& match) { return match.day == day.season_day; }); + if (moved != state_.moved_matches.end()) { + pending_reschedule_ = RescheduleAction{owner_, RescheduleActionKind::undo, *moved, day.season_day}; + return true; + } + const auto source = std::find_if(state_.reschedule_options.begin(), state_.reschedule_options.end(), + [&](const RescheduleOption& item) { return item.match.day == day.season_day; }); + if (source != state_.reschedule_options.end() && !source->target_days.empty()) { + selected_source_day_ = day.season_day; + return true; + } + return changed; + } + const bool own_league = active_calendar_class_ >= 0 && active_calendar_class_ < 4 && + (day.competitions & (uint32_t(1) << active_calendar_class_)); + // Source local30 is also set by the DFB/rearranged-fixture bit14. + if ((day.raw_entry & 0x7fff) && (own_league || (day.competitions & (uint32_t(1) << 14)))) { + close_requested_ = true; return true; + } + } + return changed; +} + +void CalendarScreen::acknowledge_reschedule(CalendarState state, DeskRequest owner) { + if (state.reschedule_manager != owner.manager_slot || owner.menu_kind != 7 || + owner.kind != DeskRequestKind::open_menu || owner.revision <= owner_.revision || !pending_reschedule_) + throw FormatError("calendar: invalid reschedule acknowledgement"); + state_ = std::move(state); + owner_ = owner; + selected_source_day_ = -1; + pending_reschedule_.reset(); +} + +void CalendarScreen::reject_reschedule() { + if (!pending_reschedule_) throw FormatError("calendar: no pending reschedule request"); + pending_reschedule_.reset(); + selected_source_day_ = -1; +} + +bool CalendarScreen::key(std::string_view value) { + if (close_requested_ || value != "ESC") return false; + close_requested_ = true; return true; +} + +std::string CalendarScreen::state_json() const { + std::ostringstream out; + out << "{\"screen\":\"" << (state_.reschedule_manager >= 0 ? "reschedule_calendar" : "calendar") + << "\",\"season_start_counter\":" << state_.season_start_counter + << ",\"day_count\":" << state_.days.size() << ",\"current_day\":" << state_.current_day + << ",\"selected_day\":" << selected_day_ << ",\"selected_source_day\":" << selected_source_day_ + << ",\"reschedule_options\":" << state_.reschedule_options.size() + << ",\"moved_matches\":" << state_.moved_matches.size() + << ",\"close_requested\":" << (close_requested_ ? "true" : "false"); + if (state_.reschedule_manager >= 0) { + out << ",\"source_days\":["; + for (size_t i = 0; i < state_.reschedule_options.size(); ++i) { + if (i) out << ','; + const auto& option = state_.reschedule_options[i]; + out << "{\"day\":" << option.match.day << ",\"targets\":["; + for (size_t j = 0; j < option.target_days.size(); ++j) { + if (j) out << ','; + out << option.target_days[j]; + } + out << "]}"; + } + out << "],\"undo_days\":["; + for (size_t i = 0; i < state_.moved_matches.size(); ++i) { + if (i) out << ','; + out << state_.moved_matches[i].day; + } + out << ']'; + } + if (selected_day_ >= 0) { + const auto& day = state_.days[size_t(selected_day_)]; + out << ",\"day_counter\":" << day.day_counter << ",\"raw_entry\":" << day.raw_entry + << ",\"competitions\":" << day.competitions << ",\"league_matchdays\":["; + for (size_t i = 0; i < day.league_matchdays.size(); ++i) { if (i) out << ','; out << day.league_matchdays[i]; } + out << "],\"information\":" << json_quote(original_to_utf8(information(day))); + } + out << '}'; return out.str(); +} + +} // namespace bmh::ui diff --git a/src/ui/calendar.hpp b/src/ui/calendar.hpp new file mode 100644 index 0000000..2240df8 --- /dev/null +++ b/src/ui/calendar.hpp @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "formats/font.hpp" +#include "formats/textd.hpp" +#include "ui/calendar_state.hpp" +#include "ui/desktop.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +enum class RescheduleActionKind : uint8_t { move, undo }; +struct RescheduleAction { + DeskRequest owner{}; + RescheduleActionKind kind = RescheduleActionKind::move; + LeagueMatchRef match{}; + int target_day = -1; + bool operator==(const RescheduleAction&) const = default; +}; + +struct CalendarCell { int x = 0, y = 0, width = 11, height = 8; }; +// CalendarCell: weekdays descend, weeks advance horizontally, July through June. +CalendarCell calendar_cell(const CalendarDayProjection& day); + +class CalendarScreen { +public: + CalendarScreen(const std::filesystem::path& data, CalendarState state, + std::string manager_name = {}, bool decorated_background = true, int runtime_club = -1, + DeskRequest owner = {}); + Image render() const; + bool move(int x, int y); + bool click(int x, int y, bool right = false); + bool key(std::string_view value); + bool close_requested() const { return close_requested_; } + const CalendarState& state() const { return state_; } + int selected_day() const { return selected_day_; } + const std::optional& pending_reschedule() const { return pending_reschedule_; } + const DeskRequest& owner() const { return owner_; } + void acknowledge_reschedule(CalendarState state, DeskRequest owner); + void reject_reschedule(); + std::string state_json() const; +private: + CalendarState state_; + Image background_, atlas_; + Font font_; + SpriteFont sprite_font_; + LeImage exe_; + TextDb texts_; + bool decorated_background_ = true, close_requested_ = false; + int selected_day_ = -1, active_calendar_class_ = -1; + DeskRequest owner_{}; + int selected_source_day_ = -1; + std::optional pending_reschedule_; + void text(Image&, int x, int baseline, std::string_view bytes, uint8_t color) const; + std::string information(const CalendarDayProjection&) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/calendar_state.cpp b/src/ui/calendar_state.cpp new file mode 100644 index 0000000..b9e3cb4 --- /dev/null +++ b/src/ui/calendar_state.cpp @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/calendar_state.hpp" + +#include +#include +#include + +#include "formats/le.hpp" +#include "game/matchday_setup.hpp" +#include "game/state.hpp" +#include "game/reschedule.hpp" + +namespace bmh::ui { +namespace { +constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; +constexpr int kMaxSeasonDays = 366; + +void require_memory(const GameState& game, uint32_t address) { + if (!game.memory.has(address)) throw FormatError("calendar: missing saved memory at " + std::to_string(address)); +} +} + +CalendarState calendar_from_game(const GameState& game, const LeImage& executable) { + if (!executable.contains(::bmh::layout::CalendarState_CalendarFromGame_ExecutableField) || !executable.contains(::bmh::layout::CalendarState_CalendarFromGame_ExecutableField2)) + throw FormatError("calendar: missing executable month lengths"); + require_memory(game, ::bmh::layout::CalendarState_FormatError_RuntimeField3); + require_memory(game, ::bmh::layout::DaysIntoSeason); + const uint32_t native_start = game.memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3); + const int native_current = game.memory.u16(::bmh::layout::DaysIntoSeason); + if (game.date < native_start || game.date - native_start != uint32_t(native_current)) + throw FormatError("calendar: saved native season cursor disagrees with current date"); + const DeskDate first_native_date = desk_date(native_start, executable); + if (first_native_date.month != 7 || first_native_date.day < 1 || first_native_date.day > 7) + throw FormatError("calendar: native season start is outside the first July week"); + const int leading_days = first_native_date.day - 1; + if (native_current < 0 || native_current >= kMaxSeasonDays) + throw FormatError("calendar: native season cursor is out of range"); + if (native_start < uint32_t(leading_days)) + throw FormatError("calendar: display calendar anchor underflow"); + const uint32_t display_start = native_start - uint32_t(leading_days); + const int current_display = native_current + leading_days; + + // CalendarCell reads 0x16e saved calendar words. Keep the whole source table + // available even when this particular year uses only its first 365 entries. + for (int day = 0; day < kMaxSeasonDays; ++day) { + const uint64_t address = uint64_t(kCalendar) + uint64_t(day) * 2 + 1; + if (address > std::numeric_limits::max()) + throw FormatError("calendar: calendar address overflow"); + require_memory(game, uint32_t(address)); + } + require_memory(game, ::bmh::layout::CalendarState_FormatError_RuntimeField2); + require_memory(game, ::bmh::layout::CalendarState_FormatError_RuntimeField); + require_memory(game, ::bmh::layout::CompetitionSelection); + for (int league = 0; league < 9; ++league) { + const uint32_t address = ::bmh::layout::LeagueCalendarBits + uint32_t(league); + if (!executable.contains(address)) + throw FormatError("calendar: missing executable league calendar class"); + if (executable.u8(address) > 31) + throw FormatError("calendar: invalid executable league calendar class"); + } + + CalendarState state; + state.season_start_counter = display_start; + state.leading_days = leading_days; + if (current_display >= kMaxSeasonDays) + throw FormatError("calendar: current date is outside the display calendar"); + + std::array ordinals{}; + state.days.reserve(kMaxSeasonDays); + for (int offset = 0; offset <= kMaxSeasonDays; ++offset) { + const uint64_t absolute = uint64_t(display_start) + uint64_t(offset); + if (absolute > std::numeric_limits::max()) + throw FormatError("calendar: day counter overflow"); + const auto day_counter = uint32_t(absolute); + const DeskDate date = desk_date(day_counter, executable); + if (offset > 0 && date.month == 7 && date.day == 1) break; + if (offset == kMaxSeasonDays) + throw FormatError("calendar: season did not reach the next July 1"); + + const int native_day = offset - leading_days; + const uint16_t raw = native_day >= 0 ? game.memory.u16(kCalendar + uint32_t(native_day) * 2) : 0; + const uint32_t competitions = native_day >= 0 ? day_competitions(game, raw) : 0; + CalendarDayProjection projection; + projection.season_day = native_day; + projection.day_counter = day_counter; + projection.date = date; + projection.raw_entry = raw; + projection.competitions = competitions; + projection.current_day = offset == current_display; + + for (int league = 0; league < 9; ++league) { + const uint32_t mask = uint32_t(1) << executable.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league)); + if ((competitions & mask) != 0) { + if (ordinals[size_t(league)] == std::numeric_limits::max()) + throw FormatError("calendar: league matchday ordinal overflow"); + projection.league_matchdays[size_t(league)] = ++ordinals[size_t(league)]; + } + } + state.days.push_back(projection); + } + + if (state.days.size() != 365 && state.days.size() != 366) + throw FormatError("calendar: unsupported season length"); + if (current_display >= int(state.days.size())) + throw FormatError("calendar: current date is outside the season calendar"); + state.current_day = current_display; + return state; +} + +CalendarState reschedule_calendar_from_game(const GameState& game, const LeImage& executable, int manager) { + CalendarState state = calendar_from_game(game, executable); + state.reschedule_manager = manager; + for (const auto& match : reschedulable_matches(game, manager)) { + RescheduleOption option; + option.match = match; + option.target_days = reschedule_target_days(game, manager, match); + const int display_day = match.day + state.leading_days; + if (match.day >= 0 && display_day >= 0 && size_t(display_day) < state.days.size()) + state.days[size_t(display_day)].reschedule_source = true; + for (const int day : option.target_days) + if (day >= 0 && day + state.leading_days >= 0 && + size_t(day + state.leading_days) < state.days.size()) + state.days[size_t(day + state.leading_days)].reschedule_target = true; + state.reschedule_options.push_back(std::move(option)); + } + state.moved_matches = moved_matches(game, manager); + for (const auto& match : state.moved_matches) { + const int display_day = match.day + state.leading_days; + if (match.day >= 0 && display_day >= 0 && size_t(display_day) < state.days.size()) + state.days[size_t(display_day)].reschedule_undo = true; + } + return state; +} + +} // namespace bmh::ui diff --git a/src/ui/calendar_state.hpp b/src/ui/calendar_state.hpp new file mode 100644 index 0000000..2f179b3 --- /dev/null +++ b/src/ui/calendar_state.hpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include + +#include "ui/desk_state.hpp" +#include "game/reschedule.hpp" + +namespace bmh { +struct GameState; +class LeImage; +} + +namespace bmh::ui { + +// Read-only projection of one saved day in the Source July-to-June calendar. +// raw_entry keeps the full saved word; competitions is the effective Source bitmap. +struct CalendarDayProjection { + int season_day = 0; // Native calendar-word index; negative for July cells before Source day zero. + uint32_t day_counter = 0; + DeskDate date; + uint16_t raw_entry = 0; + uint32_t competitions = 0; + std::array league_matchdays{}; // 1-based ordinal; zero when this league does not play. + bool current_day = false; + bool reschedule_source = false; + bool reschedule_target = false; + bool reschedule_undo = false; + bool friendly_target = false; +}; + +struct RescheduleOption { + LeagueMatchRef match; + std::vector target_days; +}; + +struct CalendarState { + // Display dates begin on July 1, while Source calendar word zero begins on + // the first Wednesday of the season. leading_days bridges those indices. + uint32_t season_start_counter = 0; + int leading_days = 0; + int current_day = -1; // Display-vector index, including leading July cells. + std::vector days; + int reschedule_manager = -1; + bool friendly_selection = false; + std::vector reschedule_options; + std::vector moved_matches; +}; + +// Projects the current saved season without preparing fixtures, advancing the date, +// changing calendar words, or consuming either random generator. +CalendarState calendar_from_game(const GameState& game, const LeImage& executable); +CalendarState reschedule_calendar_from_game(const GameState& game, const LeImage& executable, int manager); + +} // namespace bmh::ui diff --git a/src/ui/club_info.cpp b/src/ui/club_info.cpp new file mode 100644 index 0000000..291de46 --- /dev/null +++ b/src/ui/club_info.cpp @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/club_info.hpp" + +#include +#include + +#include "formats/font.hpp" +#include "game/club_info.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +void copy(Image& out, const Image& src, int sx, int sy, int x, int y, int w, int h, + int transparent = -1) { + if (sx < 0 || sy < 0 || w < 0 || h < 0 || sx + w > src.width || sy + h > src.height) + throw FormatError("club info: Original asset rectangle outside source: " + std::to_string(sx) + "," + + std::to_string(sy) + " " + std::to_string(w) + "x" + std::to_string(h) + " in " + + std::to_string(src.width) + "x" + std::to_string(src.height)); + for (int yy = 0; yy < h; ++yy) for (int xx = 0; xx < w; ++xx) { + const uint8_t value = src.pixels[size_t(sy + yy) * size_t(src.width) + size_t(sx + xx)]; + if (value != transparent && x + xx >= 0 && y + yy >= 0 && + x + xx < out.width && y + yy < out.height) out.at(x + xx, y + yy) = value; + } +} +void rect(Image& out, int x, int y, int w, int h, uint8_t color) { + for (int yy = std::max(0, y); yy < std::min(out.height, y + h); ++yy) + for (int xx = std::max(0, x); xx < std::min(out.width, x + w); ++xx) out.at(xx, yy) = color; +} +std::string padded(int value, int width = 2) { + std::string s = std::to_string(value); + if (int(s.size()) < width) s.insert(0, size_t(width - int(s.size())), '%'); + return s; +} +int sprite_width(const LeImage& exe, std::string_view value) { + int width = 0; + for (unsigned char c : value) { + if (c <= 31 || c >= 128) continue; + const int glyph = exe.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c); + width += glyph ? exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2) : 2; + } + return width; +} +int source_manager_of(const GameState& game, int team) { + const int manager = game.manager_of(team); + if (manager >= 0) return manager; + constexpr size_t fifth_team_offset = size_t(4) * 0xb0c + 0x290; + if (!game.manager_teams.empty() && game.manager_teams.front() == kNoTeam && + game.manager_records.size() >= fifth_team_offset + 2) { + const uint16_t fifth_team = uint16_t(game.manager_records[fifth_team_offset] | + uint16_t(game.manager_records[fifth_team_offset + 1]) << 8); + if (fifth_team == team) return 4; + } + return -1; +} +} + +ClubInfoProjection club_info_from_game(const GameState& g, int team, + const ClubInfoEntry& entry, const LeImage& exe, + const TextDb&) { + if (team < 0 || team > kNoTeam) throw FormatError("club info: runtime team outside Original range"); + ClubInfoProjection out; + out.runtime_team = team; + out.original_club_name = g.club_name(team); + out.gradient_text = g.memory.u8(::bmh::layout::TextGradientDisabled) == 0 && exe.u8(::bmh::layout::TextGradientMode) == 2; + out.decorated_background = g.memory.u8(::bmh::layout::PlainBackground) == 0; + out.has_squad = team == kNoTeam || team < exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField); + if (team != kNoTeam && team >= exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField)) { + out.has_squad = false; + out.category = team >= 0 && size_t(team) < g.team_morale.size() + ? uint8_t((g.team_morale[size_t(team)] >> 6) & 3) : 0; + return out; + } + const SquadRange range = squad_range(team); + out.squad_start_offset = int(range.first); + if (entry.displayed_slots.size() != range.count || range.first + range.count > g.squad_slots.size()) + throw FormatError("club info: entry slot snapshot does not match Source squad range"); + out.category = team >= 0 && size_t(team) < g.team_morale.size() + ? uint8_t((g.team_morale[size_t(team)] >> 6) & 3) : 0; + const int manager = source_manager_of(g, team); + std::vector loan_records; + if (manager >= 0 && team != kNoTeam && + g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) && g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b) && g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f)) { + for (int loan = 0; loan < 12; ++loan) + if (g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(loan) * 2) != 0x0fff && + g.memory.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(loan)) == uint8_t(manager)) loan_records.push_back(loan); + } + if (loan_records.size() > range.count) throw FormatError("club info: Source loan count exceeds squad capacity"); + const size_t ordinary_count = range.count - loan_records.size(); + int rendered_row = 0; + auto make_player = [&](int display_row, int physical_row, int loan_record, uint16_t slot, + std::optional> board) { + ClubInfoPlayer player; + player.row = display_row; + player.physical_row = physical_row; + player.human_loan_index = loan_record; + player.borrowed = loan_record >= 0; + player.displayed_slot = slot; + player.player_id = (player.displayed_slot & 0x0fff) == 0x0fff + ? -1 : int(player.displayed_slot & 0x0fff); + if (player.borrowed) player.player_id = g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(loan_record) * 2); + if (player.player_id >= 0) { + player.rendered_row = rendered_row++; + const size_t id = size_t(player.player_id); + if (id >= g.players.size() || id >= g.player_cards.size() || id >= g.player_bonus.size()) + throw FormatError("club info: player outside authoritative tables"); + player.attributes = g.players[id]; + player.original_name = g.player_name(player.player_id); + player.cards = g.player_cards[id]; + player.bonus = g.player_bonus[id]; + } + if (board) player.manager_board = std::move(board); + if (!player.borrowed && player.player_id >= 0) { + for (int loan = 0; loan < 200; ++loan) { + const uint32_t address = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan) * 4; + if (g.memory.has(address + 3) && g.memory.u32(address) != 0 && + (g.memory.u32(address) & 0x0fff) == uint32_t(player.player_id)) { + player.ordinary_loan = true; break; + } + } + } + if (player.player_id >= 0 && manager >= 0 && team != kNoTeam) { + for (int offer = 0; offer < 4; ++offer) { + const uint32_t address = ::bmh::layout::OfferSlots + uint32_t(offer) * 4; + if (g.memory.has(address + 3)) { + const uint32_t value = g.memory.u32(address); + if (int(value & 31) == manager && int((value >> 10) & 0x0fff) == player.player_id) + player.offer_name_color = true; + } + } + } + out.players.push_back(std::move(player)); + }; + for (size_t row = 0; row < ordinary_count; ++row) { + std::optional> board; + if (manager >= 0) { + const size_t offset = size_t(manager) * 0x840 + row * 0x58; + if (offset + 0x58 <= g.tactics.size()) { + board.emplace(); std::copy_n(g.tactics.begin() + static_cast(offset), board->size(), board->begin()); + } + } + make_player(int(row), int(row), -1, entry.displayed_slots[row], std::move(board)); + } + for (size_t index = 0; index < loan_records.size(); ++index) { + const int loan = loan_records[index]; + const size_t offset = size_t(loan) * 0x58; + if (offset + 0x58 > 0x420 || !g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(offset) + 0x57)) + throw FormatError("club info: borrowed-manager board truncated"); + std::array board{}; + for (size_t byte = 0; byte < board.size(); ++byte) board[byte] = g.memory.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(offset + byte)); + make_player(int(ordinary_count + index), -1, loan, + g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(loan) * 2), std::move(board)); + } + return out; +} + +ClubInfoScreen::ClubInfoScreen(const std::filesystem::path& data, ClubInfoProjection projection) + : projection_(std::move(projection)), exe_(load_le(asset_path(data, "BMH.exe"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))), font2_(load_font(asset_path(data / "F", "BMH2.FNT"))), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + background_(load_vga(asset_path(data / "KB", "129.VGA"))), + widgets_(load_vga(asset_path(data / "KB", "0.VGA"))), + atlas_(load_vga(asset_path(data / "KB", "2.VGA"))), + flags_(load_vga(asset_path(data / "KB", "24.VGA"))), + letters_(load_vga(asset_path(data / "KB", "54.VGA"))) { + if (atlas_.width == 314) { Image padded_atlas(320, atlas_.height, 0); padded_atlas.blit(atlas_, 0, 0); atlas_ = std::move(padded_atlas); } + if (projection_.runtime_team < 0 || + (projection_.has_squad && projection_.players.size() != 16u && projection_.players.size() != 24u) || + (!projection_.has_squad && !projection_.players.empty())) + throw FormatError("club info: invalid projection"); + if (projection_.category > 2) throw FormatError("club info: unsupported category value"); + int expected_rendered_row = 0; + for (size_t i = 0; i < projection_.players.size(); ++i) { + const auto& p = projection_.players[i]; + if (p.row != int(i) || p.player_id != ((p.displayed_slot & 0xfff) == 0xfff ? -1 : p.displayed_slot & 0xfff)) + throw FormatError("club info: inconsistent projected row"); + if ((p.player_id >= 0 && p.rendered_row != expected_rendered_row++) || + (p.player_id < 0 && p.rendered_row != -1) || + (p.borrowed != (p.human_loan_index >= 0)) || + (p.borrowed && p.physical_row != -1) || + (!p.borrowed && p.physical_row != p.row)) + throw FormatError("club info: inconsistent displayed/player identity"); + } +} + +void ClubInfoScreen::text(Image& out, int x, int baseline, std::string_view value, + uint8_t color, int right) const { + const int width = font_.text_width(value); + if (right >= 0) x += (right - x) / 2 - width / 2; + if (x < 0 || x + width > out.width || baseline < 5 || baseline >= out.height) return; + Image mask(std::max(1, width), 6); font_.draw(mask, 0, 0, value, 1); + int gradient = 0; while (gradient < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + gradient) != color) ++gradient; + for (int yy = 0; yy < 6; ++yy) for (int xx = 0; xx < width; ++xx) + if (mask.at(xx, yy)) out.at(x + xx, baseline - 5 + yy) = projection_.gradient_text + ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + gradient * 6 + yy) : color; +} + +void ClubInfoScreen::sprite_text(Image& out, int x, int baseline, std::string_view value, int mode) const { + for (unsigned char c : value) { + if (c <= 31 || c >= 128) continue; + const int glyph = exe_.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c); + if (!glyph) { x += 2; continue; } + const int sx = exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2); + const int width = exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - sx; + copy(out, letters_, sx, (mode - 4) * 7, x, baseline - 6, width, 7, 0); + x += width; + } +} + +std::vector> ClubInfoScreen::rows() const { + std::vector> out; + int baseline = 36; + int loan_row = 0; + for (size_t i = 0; i < projection_.players.size(); ++i) { + const auto& player = projection_.players[i]; + if (player.borrowed) { + if (player.player_id >= 0) out.emplace_back(int(i), 209 - 8 * loan_row); + ++loan_row; + continue; + } + if (i && ((player.displayed_slot & 0xc000) != (projection_.players[i - 1].displayed_slot & 0xc000))) baseline += 2; + if (player.player_id < 0) continue; + out.emplace_back(int(i), baseline); baseline += 7; + } + return out; +} + +Image ClubInfoScreen::render() const { + Image out = projection_.decorated_background ? background_ : Image(320, 240); + if (!projection_.decorated_background) { + rect(out, 0, 4, 320, 13, 0x44); rect(out, 1, 5, 318, 11, 0x39); + rect(out, 0, 228, 320, 10, 0x44); rect(out, 1, 229, 318, 8, 0x39); + } + sprite_text(out, 172 + (282 - 172) / 2 - sprite_width(exe_, texts_[(::bmh::layout::ClubInfo_Render_TextPointer6 - ::bmh::layout::TextPointerTable) / 4]) / 2, + 13, texts_[(::bmh::layout::ClubInfo_Render_TextPointer6 - ::bmh::layout::TextPointerTable) / 4]); + sprite_text(out, 5, 235, projection_.original_club_name); + if (projection_.has_squad) + text(out, 0, 26, texts_[((projection_.view == ClubInfoView::data_a ? ::bmh::layout::ClubInfo_Render_TextPointer3 : ::bmh::layout::ClubInfo_Render_TextPointer4) - ::bmh::layout::TextPointerTable) / 4], 0x51); + if (!projection_.has_squad) { + const auto& message = texts_[(::bmh::layout::ClubInfo_Render_TextPointer7 - ::bmh::layout::TextPointerTable) / 4]; + const int width = font2_.text_width(message); + font2_.draw(out, (320 - width) / 2, 120 - font2_.baseline, message, 0xfb); + } else { + for (const auto& [row, baseline] : rows()) { + const auto& p = projection_.players[size_t(row)]; const auto& a = p.attributes; + if (p.displayed_slot & 0xc000) { + const int jersey = (p.cards & 31) + 1; + const uint8_t color = p.displayed_slot & 0x1000 ? 0xf3 : p.borrowed ? 0x75 : p.displayed_slot & 0x8000 ? 0x6c : 0x68; + text(out, 4, baseline, std::to_string(jersey % 10), color); + if (jersey >= 10) text(out, 0, baseline, exe_.cstring(::bmh::layout::ClubInfo_Render_TextPointer), color); + } + uint8_t name_color = uint8_t(p.rendered_row % 2 ? 0x67 : 0x6b); + if (p.borrowed) name_color = 0x65; + if (p.offer_name_color) name_color = 0x75; + if (hovered_row_ == p.rendered_row) name_color = 0x3e; + text(out, 13, baseline, p.original_name, name_color); + if (projection_.view == ClubInfoView::data_a) { + const size_t pos = size_t(a.position()); + text(out, 66, baseline, texts_[(::bmh::layout::ClubInfo_Render_TextPointer2 - ::bmh::layout::TextPointerTable) / 4 + pos], 0x6c, 82); + for (int field = 0; field < 2; ++field) { + int value = (a.w35c >> (field == 0 ? 24 : 21)) & 7; if (value > 4) --value; + copy(out, atlas_, 208 + value * 16, field == 0 ? 17 : 22, field == 0 ? 88 : 103, baseline - 5, 16, 5, 0); + } + std::string attrs = padded(a.condition()) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField) + padded(a.technique()) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField) + + padded(a.form()) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField2) + padded(a.strength()) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4); + text(out, 117, baseline, attrs, 0x6c); + if (p.manager_board) { + const auto& board = *p.manager_board; + copy(out, atlas_, 304, int(board[0xe] >> 6) * 3, 179, baseline - 4, 16, 3, 0); + text(out, 232, baseline, padded(board[0xf]), board[0xf] < 61 ? 0x66 : board[0xf] < 71 ? 0x27 : 0xfb); + } + const int injury = (a.w364 >> 16) & 31; + const int marker = a.w35c >> 27; + if (p.borrowed) { + copy(out, atlas_, 197, 25, 196, baseline - 5, 10, 5); + } else if (marker == 0 && injury == 0) { + const int status = p.displayed_slot & 0x8000 ? 0 : p.displayed_slot & 0x4000 ? 1 : 2; + copy(out, atlas_, 272, status * 5, 191, baseline - 5, 32, 5, 0); + } else { + const int status = marker == 0 ? 5 : marker == 31 ? 8 : injury == 0 ? 4 : 3; + copy(out, atlas_, 197, (status - 3) * 6 + 1, 196, baseline - 5, 10, 5); + } + if (p.ordinary_loan) copy(out, atlas_, 304, 9, 9, baseline - 4, 16, 4, 0); + const int nationality = a.nationality() + ((p.bonus & 0x80) >> 2); + copy(out, flags_, (nationality % 12) * 9, (nationality / 12) * 6, 217, baseline - 6, 9, 6); + text(out, 247, baseline, padded(a.w364 >> 26) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + + padded((a.w364 >> 2) & 63) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + + padded((a.w368 >> 18) & 63) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + + padded((a.w368 >> 14) & 15) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + + padded((a.w368 >> 24) & 7) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField), 0x6c); + } else { + text(out, 65, baseline, padded(a.age()) + texts_[(::bmh::layout::ClubInfo_Render_TextPointer5 - ::bmh::layout::TextPointerTable) / 4], 0x6c); + for (int skill = 0; skill < 7; ++skill) + copy(out, atlas_, 256 + a.skill(Player::Skill(skill)) * 16, 32, 87 + skill * 10, baseline - 5, 16, 5, 0); + std::string attrs = padded(p.bonus & 127, 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5); + if (p.manager_board) { + const auto& b = *p.manager_board; + attrs += padded(b[7], 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + padded(b[9], 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5); + Bytes raw(b.begin(), b.end()); attrs += padded(le16(raw, 0x48), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField2) + + padded(le16(raw, 0x4a), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField2) + padded(le16(raw, 0x4c), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField); + } + text(out, 165, baseline, attrs, 0x6c); + } + } + } + auto button = [&](int x, std::string_view label) { + // FormatError3's requested 9px height is promoted to 10px; use the same + // Original widget slices as the existing menu renderer. + const int width = 51, height = 10; + const bool active = (x == 1 && pressed_button_ == (projection_.has_squad ? ClubInfoButton::view : ClubInfoButton::category)) || + (x == 60 && pressed_button_ == ClubInfoButton::statistics) || + (x == 120 && pressed_button_ == ClubInfoButton::category); + if (active) { const uint8_t base = out.at(x, 225); rect(out, x, 215, width + 1, 2, base); rect(out, x, 215, 2, height + 1, base); x += 2; } + else { rect(out, x + 2, 225, width, 2, 0x40); rect(out, x + width, 217, 2, height, 0x40); } + const int sy = active ? 44 : 74; + copy(out, widgets_, 24, sy, x, 215 + (active ? 2 : 0), 31, 10); + int at = 31, remain = width - 31; + while (remain > 20) { const int n = std::min(8, remain - 20); copy(out, widgets_, 24, sy + 10, x + at, 215 + (active ? 2 : 0), n, 10); at += n; remain -= n; } + copy(out, widgets_, 45 - remain, sy + 20, x + at, 215 + (active ? 2 : 0), remain, 10); + if (!label.empty()) { + const int mode = exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + int(active)); + const int label_baseline = active ? 224 : 222; + if (mode == 3) text(out, x, label_baseline, label, 0, x + width); + else { + int label_width = 0; + for (unsigned char c : label) { + const int glyph = exe_.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c); + label_width += glyph ? exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2) : 2; + } + sprite_text(out, x + width / 2 - label_width / 2, label_baseline, label, mode); + } + } + }; + button(1, projection_.has_squad ? texts_[((projection_.view == ClubInfoView::data_a ? ::bmh::layout::ClubInfo_Raw_TextPointer2 : ::bmh::layout::ClubInfo_Raw_TextPointer) - ::bmh::layout::TextPointerTable) / 4] : std::string_view{}); + if (projection_.has_squad) button(60, texts_[(::bmh::layout::ClubInfo_Raw_TextPointer3 - ::bmh::layout::TextPointerTable) / 4]); + if (projection_.has_squad) button(120, {}); + const int icon = std::clamp(int(projection_.category), 0, 2); + const bool category_pressed = pressed_button_ == ClubInfoButton::category; + const int category_x = projection_.has_squad ? 140 : 21; + copy(out, widgets_, 45 + 10 * icon, 96, category_x + (category_pressed ? 2 : 0), 216 + (category_pressed ? 2 : 0), 10, 8); + return out; +} + +bool ClubInfoScreen::move(int x, int y) { + bool changed = false; + if (pressed_button_ && button_at(x, y) != pressed_button_) { pressed_button_.reset(); changed = true; } + std::optional next; + if (projection_.has_squad && x >= 0 && x < 61) for (const auto& [row, baseline] : rows()) + if (y >= baseline - 7 && y < baseline + 2) { next = row; break; } + std::optional next_rendered; + if (next) next_rendered = projection_.players[size_t(*next)].rendered_row; + if (next_rendered != hovered_row_) { hovered_row_ = next_rendered; changed = true; } + return changed; +} + +ClubInfoRequest ClubInfoScreen::pointer_down(int x, int y, bool right) const { + ClubInfoRequest out; out.runtime_team = projection_.runtime_team; + out.squad_start_offset = projection_.squad_start_offset; + if (right) { out.kind = ClubInfoRequestKind::close; return out; } + if (!projection_.has_squad || x < 0 || x >= 61) return out; + for (const auto& [row, baseline] : rows()) if (y >= baseline - 7 && y < baseline + 2) { + const auto& player = projection_.players[size_t(row)]; + out.kind = ClubInfoRequestKind::open_player_detail; out.rendered_row = player.rendered_row; + out.player_id = player.player_id; out.physical_row = player.physical_row; + out.human_loan_index = player.human_loan_index; return out; + } + return out; +} + +std::optional ClubInfoScreen::button_at(int x, int y) const { + if (y < 215 || y > 225) return std::nullopt; + if (!projection_.has_squad && x >= 1 && x <= 52) return ClubInfoButton::category; + if (projection_.has_squad && x >= 1 && x <= 52) return ClubInfoButton::view; + if (projection_.has_squad && x >= 60 && x <= 111) return ClubInfoButton::statistics; + if (projection_.has_squad && x >= 120 && x <= 171) return ClubInfoButton::category; + return std::nullopt; +} + +void ClubInfoScreen::press(int x, int y) { pressed_button_ = button_at(x, y); } + +ClubInfoRequest ClubInfoScreen::release(int x, int y) { + ClubInfoRequest out; out.runtime_team = projection_.runtime_team; + out.squad_start_offset = projection_.squad_start_offset; + const auto pressed = pressed_button_; + const auto released = button_at(x, y); + pressed_button_.reset(); + if (!pressed || pressed != released) return out; + if (*pressed == ClubInfoButton::view) out.kind = ClubInfoRequestKind::toggle_view; + else if (*pressed == ClubInfoButton::statistics) out.kind = ClubInfoRequestKind::open_statistics; + else { out.kind = ClubInfoRequestKind::change_category; out.requested_category = uint8_t((projection_.category + 1) % 3); } + return out; +} + +} // namespace bmh::ui diff --git a/src/ui/club_info.hpp b/src/ui/club_info.hpp new file mode 100644 index 0000000..322a97f --- /dev/null +++ b/src/ui/club_info.hpp @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/font.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/club_info.hpp" +#include "game/state.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +enum class ClubInfoView : uint8_t { data_a = 1, data_b = 2 }; + +struct ClubInfoPlayer { + int row = -1; // physical ordinary row, or appended loan projection row + int rendered_row = -1; // index in Source's occupied-player navigation list + int physical_row = -1; + int human_loan_index = -1; + int player_id = -1; + uint16_t displayed_slot = 0x0fff; + std::string original_name; + Player attributes; + uint16_t cards = 0; + uint8_t bonus = 0; + bool borrowed = false; + bool ordinary_loan = false; + bool offer_name_color = false; + // Present only when this runtime club belongs to a human manager. + std::optional> manager_board; +}; + +// Owned inputs for one render of ClubInfoFromGame / LineupScreen. Build this from the actual +// runtime team and the Core-owned pre-injury-cleanup slot snapshot. +struct ClubInfoProjection { + int runtime_team = -1; + int squad_start_offset = -1; + std::string original_club_name; + ClubInfoView view = ClubInfoView::data_a; + bool has_squad = false; + bool gradient_text = true; + bool decorated_background = true; + uint8_t category = 0; + std::vector players; +}; + +ClubInfoProjection club_info_from_game(const GameState& game, int runtime_team, + const ClubInfoEntry& entry, const LeImage& exe, + const TextDb& texts); + +enum class ClubInfoRequestKind : uint8_t { + none, close, toggle_view, open_statistics, change_category, open_player_detail +}; +enum class ClubInfoButton : uint8_t { view, statistics, category }; + +struct ClubInfoRequest { + ClubInfoRequestKind kind = ClubInfoRequestKind::none; + int runtime_team = -1; + int squad_start_offset = -1; + int player_id = -1; + int rendered_row = -1; + int physical_row = -1; + int human_loan_index = -1; + uint8_t requested_category = 0; +}; + +class ClubInfoScreen { +public: + ClubInfoScreen(const std::filesystem::path& data_directory, ClubInfoProjection projection); + Image render() const; + bool move(int x, int y); + std::optional button_at(int x, int y) const; + void press(int x, int y); + ClubInfoRequest release(int x, int y); + std::optional pressed_button() const { return pressed_button_; } + // Source right-button DOWN closes. Left-button DOWN on a player-name hit box + // routes to the real player-detail modal; all other left clicks are inert. + ClubInfoRequest pointer_down(int x, int y, bool right_button = false) const; + const ClubInfoProjection& projection() const { return projection_; } + std::optional hovered_row() const { return hovered_row_; } +private: + ClubInfoProjection projection_; + LeImage exe_; + Font font_; + Font font2_; + TextDb texts_; + Image background_, widgets_, atlas_, flags_, letters_; + std::optional hovered_row_; + std::optional pressed_button_; + std::vector> rows() const; + void text(Image&, int x, int baseline, std::string_view, uint8_t color, int right = -1) const; + void sprite_text(Image&, int x, int baseline, std::string_view, int mode = 5) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/club_player_detail.cpp b/src/ui/club_player_detail.cpp new file mode 100644 index 0000000..b5888dd --- /dev/null +++ b/src/ui/club_player_detail.cpp @@ -0,0 +1,404 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/club_player_detail.hpp" + +#include +#include +#include +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +void rect(Image& out,int x,int y,int w,int h,uint8_t c) { + for(int yy=std::max(0,y);yysrc.width||sy+h>src.height)throw FormatError("player card: original atlas bounds"); + for(int yy=0;yy=0&&x+xx=0&&y+yyint(negative);at-=3)n.insert(size_t(at),"."); + const int digits=int(std::to_string(value).size()); + if(digits12 || p.redraw.context.original_name.empty()) + throw FormatError("club player detail: invalid owned projection"); + if(!p.redraw.context.human_loan && !p.redraw.market_value) + throw FormatError("club player detail: Core valuation required"); +} +} // namespace + +ClubPlayerDetailProjection club_player_detail_from_game(const GameState& g, + ClubPlayerDetailRedraw redraw,const LeImage& exe) { + ClubPlayerDetailProjection p;p.redraw=std::move(redraw); + const auto& c=p.redraw.context; + const int nation=c.attributes.nationality()+((c.bonus&0x80)?32:0); + p.original_nationality_name=g.club_name(exe.u16(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3)+exe.u16(::bmh::layout::NoTeamSquadStart)+nation); + for(int i=0;i<2;++i){ + const int id=i?c.secondary_club:c.primary_club;if(id<0||id==0xffff)continue; + ClubPlayerDetailClub club;club.runtime_team=id;club.original_full_name=g.club_name(id);club.original_short_name=club.original_full_name; + if(id<168){ + const uint8_t raw=g.memory.u8(::bmh::layout::ClubShortNameOffsets+uint32_t(id)); + club.original_short_name=club.original_short_name.substr(raw>>4,(raw&15)+1); + } + // SourceBadgeFallback consults the selector only for real atlas clubs. + if(id<=89||(id>=138&&id<=167)||id>=357){ + if(size_t(id)*2+1>=g.club_heap_78.size())throw FormatError("club player detail: truncated badge table"); + club.badge_selector=le16(g.club_heap_78,size_t(id)*2)&0x1ff; + } + p.clubs[size_t(i)]=std::move(club); + } + p.currency_numerator=int(exe.u32(::bmh::layout::CurrencyMultiplier));p.currency_denominator=int(exe.u32(::bmh::layout::CurrencyDivisor)); + if(g.memory.has(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField))p.currency_numerator=int(g.memory.u32(::bmh::layout::CurrencyMultiplier)); + if(g.memory.has(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField2))p.currency_denominator=int(g.memory.u32(::bmh::layout::CurrencyDivisor)); + p.gradient_text=(!g.memory.has(::bmh::layout::TextGradientDisabled)||g.memory.u8(::bmh::layout::TextGradientDisabled)==0)&&exe.u8(::bmh::layout::TextGradientMode)==2; + p.injury_as_text=g.memory.has(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4)?g.memory.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4)!=0:exe.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4)!=0; + if(c.board && !c.human_loan){ + const size_t month=size_t(c.active_manager)*0xb0c+0x286; + if(month>=g.manager_records.size())throw FormatError("club player detail: missing active statistics months"); + p.statistics_months=g.manager_records[month]; + const uint32_t flags=::bmh::layout::Flags+uint32_t(c.active_manager)*3+2; + if(g.memory.has(flags))p.statistics_flags=g.memory.u8(flags); + } + if(c.national_mode==0 && c.board && !c.human_loan && c.active_offer>=0){ + const uint32_t offer=g.memory.u32(::bmh::layout::OfferSlots+uint32_t(c.active_offer)*4); + if(offer&0x80000000){ + // The offer-record amount field; local34 is offer index+1. + const uint32_t amount=::bmh::layout::EditorList+uint32_t(40+c.active_offer)*0x58+12; + if(!g.memory.has(amount+3))throw FormatError("club player detail: missing offered amount"); + p.displayed_offer_amount=g.memory.u32(amount); + } + } + validate(p);return p; +} + +ClubPlayerDetailScreen::ClubPlayerDetailScreen(const std::filesystem::path& data, + ClubPlayerDetailProjection p,Image parent):projection_(std::move(p)), + exe_(load_le(asset_path(data,"BMH.exe"))), + small_(load_font(asset_path(data/"F","BMH3.FNT"))),heading_(load_font(asset_path(data/"F","BMH2.FNT"))), + texts_(load_textd(asset_path(data,"TEXTD.BLK"))),widgets_(load_vga(asset_path(data/"KB","0.VGA"))), + atlas_(load_vga(asset_path(data/"KB","2.VGA"))),flags_(load_vga(asset_path(data/"KB","24.VGA"))), + portrait_(load_vga(asset_path(data/"KB","29.VGA"))),letters_(load_vga(asset_path(data/"KB","54.VGA"))),parent_(std::move(parent)) { + validate(projection_); + if(parent_.width!=320||parent_.height!=240)throw FormatError("club player detail: parent must be320x240"); + if(atlas_.width==314){Image padded(320,atlas_.height);padded.blit(atlas_,0,0);atlas_=std::move(padded);} + for(size_t i=0;i<2;++i)if(projection_.clubs[i]){ + auto& club=*projection_.clubs[i];const int id=club.runtime_team; + if(id<=89||(id>=138&&id<=167)||id>=357){ + badges_[i]=load_vga(asset_path(data/"W",std::to_string(club.badge_selector>>3)+".VGA")); + } + // TextWidth national/foreign names: longest word, then remove two + // trailing characters until FNT3 fits57 pixels. + if(id>=168 && small_.text_width(club.original_short_name)>57){ + std::string longest;size_t at=0; + while(atlongest.size())longest=word; + if(end==std::string::npos)break; + at=end+1; + } + if(!longest.empty())club.original_short_name=longest; + while(small_.text_width(club.original_short_name)>57){ + const size_t n=club.original_short_name.size();if(n<2)break;club.original_short_name.resize(n-2); + } + } + } +} +const std::string& ClubPlayerDetailScreen::label(uint32_t address) const {return texts_[(address-::bmh::layout::TextPointerTable)/4];} +void ClubPlayerDetailScreen::text(Image& out,int x,int baseline,std::string_view value,uint8_t color,int right,bool heading) const { + const auto& font=heading?heading_:small_;const int width=font.text_width(value); + if(right>=0)x+=(right-x)/2-width/2; + if(x<0||x+width>out.width||baseline=out.height)return; + if(heading){font.draw(out,x,baseline-font.baseline,value,color);return;} + Image mask(std::max(1,width),font.height);font.draw(mask,0,0,value,1); + int gradient=0;while(gradient<32&&exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2+gradient)!=color)++gradient; + for(int yy=0;yy31?10:9; + if(active){const auto base=out.at(x,y+height);rect(out,x,y,width+1,2,base);rect(out,x,y,2,height+1,base);x+=2;y+=2;} + else {rect(out,x+2,y+height,width,2,0x40);rect(out,x+width,y+2,2,height,0x40);} + if(width>31){ + const int sy=active?44:74; + copy(out,widgets_,24,sy,x,y,31,10);int at=31,remaining=width-31; + while(remaining>20){const int n=std::min(8,remaining-20);copy(out,widgets_,24,sy+10,x+at,y,n,10);at+=n;remaining-=n;} + copy(out,widgets_,45-remaining,sy+20,x+at,y,remaining,10); + }else frame(out,x,y,width,height); + const int font=exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + int(active)); + if(font==3){text(out,x,y+height/2+2,value,0,x+width);return;} + int length=0;for(unsigned char c:value){const int g=exe_.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c);length+=g?exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2+g*2)-exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField+g*2):2;} + int cursor=x+width/2-length/2; + for(unsigned char c:value){const int g=exe_.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c);if(!g){cursor+=2;continue;} + const int sx=exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField+g*2),n=exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2+g*2)-sx; + copy(out,letters_,sx,(font-4)*7,cursor,y+height/2-4,n,7,0);cursor+=n;} +} + +void ClubPlayerDetailScreen::draw_portrait(Image& out) const { + const auto& r=projection_.redraw;if(!r.portrait_available)return; + // Copy2:FormatError2 c0 is opaque. CopyCrop forwards ff as VGA mask; + // actual14a15 transparency uses DesktopRuntimeField, reset0 by preceding text calls. + copy(out,portrait_,108+int(r.portrait_base)*38,168,181,109,38,38); + for(int i=0;i<5;++i){ + int sx=exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField+i),sy=exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField2+i); + for(int n=0;nexe_.u16(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField7+i*2)){sx=exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField+i);sy+=exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField4+i);} + } + copy(out,portrait_,sx,sy,182+exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField5+i),114+exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField6+i), + exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField3+i),exe_.u8(::bmh::layout::ClubPlayerDetail_DrawPortrait_RuntimeField4+i),0); + } +} + +Image ClubPlayerDetailScreen::render() const { + return statistics_open_?render_statistics():render_card(); +} +Image ClubPlayerDetailScreen::render_card() const { + auto out=restored_card_frame_?*restored_card_frame_:parent_; + const auto& r=projection_.redraw;const auto& c=r.context;const auto& a=c.attributes; + const Bytes board=c.board?Bytes(c.board->begin(),c.board->end()):Bytes{}; + const auto underline=[&](int x,int y,std::string_view value){ + rect(out,x,y+1,small_.text_width(value.substr(0,value.size()-1))+4,1,0x69); + }; + const auto cash=[&](uint32_t n,int width){return number(int64_t(n)*projection_.currency_numerator/projection_.currency_denominator,width,true)+exe_.cstring(::bmh::layout::CurrencySuffixText);}; + if(!restored_card_frame_){rect(out,2,225,318,2,0x40);frame(out,0,38,320,187);} + for(int y=52;y<=197;++y)for(int x=2;x<=317;++x) + out.at(x,y)=exe_.u8(::bmh::layout::Advertising_PatternRect_RuntimeField+((y-52)%16)*16+(x-2)%16); + text(out,4,49,c.original_name,0x6c,-1,true); + rect(out,3,50,313,1,0x69);rect(out,3,70,313,1,0x69); + if(c.board){ + const int games=board[0x11]+1; + const auto seniority=label(::bmh::layout::ClubPlayerDetail_RenderCard_ExecutableField)+number(games)+label(::bmh::layout::ClubPlayerDetail_RenderCard_ExecutableField2)+(games!=1?label(::bmh::layout::ClubPlayerDetail_RenderCard_ExecutableField3):"")+label(::bmh::layout::ClubPlayerDetail_RenderCard_ExecutableField4); + text(out,314-small_.text_width(seniority),49,seniority,0x6a); + } + const auto full_name=[&](int index)->std::string { + const auto& club=projection_.clubs.at(size_t(index)); + // ClubName2 masks the -1 club sentinel to fff and appends NoClubText. + return club?club->original_full_name:label(::bmh::layout::NoClubText); + }; + if(c.national_mode==2){ + text(out,4,58,label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer3),0x27); + text(out,4,66,(c.primary_club<0?full_name(0):label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer4)+full_name(0))+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField),0x6b); + }else if(c.human_loan){ + text(out,4,58,label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer5)+full_name(1)+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField),0x6b); + }else if(c.loan_record>=0){ + text(out,4,58,label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer6)+full_name(0)+label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer7)+full_name(1)+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField),0x6b); + text(out,4,66,label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer8)+number(c.loan_duration,2)+label(::bmh::layout::ClubPlayerDetail_RenderCard_ExecutableField2)+ + (c.loan_duration!=1?exe_.cstring(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer):"")+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField),0x6b); + }else text(out,0,63,label(c.primary_club<0?::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer9: ::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer10),0x6b,319); + text(out,181,106,c.original_name,0x6a,218);frame(out,179,107,42,42);draw_portrait(out); + text(out,181,155,number(a.age(),2)+label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer11),0x6a,218); + for(int i=0;i<2;++i){ + const int y=80+i*57;frame(out,254,y,42,42); + if(!projection_.clubs[size_t(i)])continue; + const auto& club=*projection_.clubs[size_t(i)]; + text(out,256,y-1,label(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer2+uint32_t(i)*4),0x6a,293); + rect(out,255,y+1,1,40,0x46);rect(out,255,y+1,40,1,0x46); + rect(out,255,y+40,40,1,0x40);rect(out,294,y+1,1,40,0x40); + if(badges_[size_t(i)])copy(out,*badges_[size_t(i)],(club.badge_selector&7)*38,0,256,y+2,38,38); + else copy(out,widgets_,8,0,256,y+2,38,38); + text(out,256,y+48,club.original_short_name,0x6a,293); + } + if(projection_.clubs[0]){ + copy(out,widgets_,8,93,220,118,15,11,0); + copy(out,widgets_,8,93,230,projection_.clubs[1]?132:104,15,11,0); + copy(out,widgets_,8,93,240,projection_.clubs[1]?147:90,15,11,0); + } + for(int i=0;i<7;++i){const int x=8+i*43; + frame(out,x,196,41,9);text(out,x,191,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer4+i*4),0x6b);underline(x,191,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer4+i*4)); + text(out,x+2,203,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer5+a.skill(Player::Skill(i))*4),0x6b); + copy(out,atlas_,256+a.skill(Player::Skill(i))*16,32,x+34,198,16,5,0); + } + for(int i=0;i<6;++i){const int x=(i%2)*80+10,base=exe_.u8(::bmh::layout::ClubPlayerDetail_Copy_RuntimeField+i); + text(out,x,base,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer3+i*4),0x6b);underline(x,base,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer3+i*4)); + std::string value; + if(i>1&&c.human_loan)value=label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer8); + else if(i>1&&!c.board&&i!=5)value=label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField2); + else if(i==0){ + value=projection_.original_nationality_name;text(out,10,105,exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_TextPointer),0x6a); + const int nation=a.nationality()+((c.bonus&0x80)?32:0); + copy(out,flags_,(nation%12)*9,(nation/12)*6,13,99,9,6); + }else if(i==1){ + const int unavailable=int(a.w35c>>27),injury=int(a.w364>>16&31); + if(unavailable==0&&injury==0){ + const int status=(c.displayed_slot&0x8000)?0:(c.displayed_slot&0x4000)?1:2; + copy(out,atlas_,272,status*5,x+4,base+14,32,5,0); + }else{ + const int status=unavailable==31?8:unavailable==0?5:injury==0?4:3; + copy(out,atlas_,197,(status-3)*6+1,x+9,base+14,10,5); + if(status==3||status==4)value=label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField3+unavailable*4); + if(status==5||(status==3&&projection_.injury_as_text))value=label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField7)+number(int(a.w364>>16&15))+label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField8); + else if(status==3)copy(out,atlas_,304-(std::min(int(a.w364>>16&15),11)/3)*16,32,136,100,16,5,0); + } + }else if(i==2){ + text(out,x,base+19,board[0xc]==255?label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer9):label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField7)+number(board[0xc])+label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer10),0x6a); + if(projection_.displayed_offer_amount) + text(out,x,base+27,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer11)+cash(*projection_.displayed_offer_amount,1)+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_TextPointer2),0x27); + value=cash(le32(board,0x50),5)+label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField4); + }else if(i==3&&board[0x43]){ + text(out,x,base+19,cash(le16(board,0x4e)&0x7fff,5)+label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField4),0x6a); + text(out,x,base+27,label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField7)+number(board[0x43]&63)+label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer10),0x6a); + value=label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer6+(board[0x43]>>6)*4); + }else if(i==4)value=le32(board,0x54)?cash(le32(board,0x54),1)+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField):label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField9); + else if(i==5)value=cash(*r.market_value,1)+exe_.cstring(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField); + text(out,x,base+11,value,0x6a); + } + button(out,8,211,60,label(::bmh::layout::ClubPlayerDetail_Copy_TextPointer7),pressed_==0); + const bool stats=c.board&&!c.human_loan; + if(stats)button(out,80,211,96,label(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField5),pressed_==1); + if(c.national_action_available||c.active_offer>=0) + button(out,stats?182:80,211,122,label(c.national_action_available&&c.active_offer<0?::bmh::layout::ClubPlayerDetail_Copy_ExecutableField2+c.national_mode*4: ::bmh::layout::ClubPlayerDetail_Copy_ExecutableField6),pressed_==2); + return out; +} + +Image ClubPlayerDetailScreen::render_statistics() const { + if(!projection_.redraw.context.board)throw FormatError("club player statistics: missing Source board"); + auto out=statistics_frame_?*statistics_frame_:render_card(); + if(!statistics_frame_)for(int y=52;y<=210;++y)for(int x=2;x<=317;++x) + out.at(x,y)=exe_.u8(::bmh::layout::Advertising_PatternRect_RuntimeField+((y-52)%16)*16+(x-2)%16); + const auto line=[&](int x,int y,int ex,int ey,uint8_t color){ + const int dx=std::abs(ex-x),sx=x=0&&x=0&&ydy){x+=sx;error+=dy;if(error>=dx){error-=dx;y+=sy;}} + else if(dy){y+=sy;error+=dx;if(error>=dy){error-=dy;x+=sx;}} + } + }; + if(!statistics_frame_)for(int edge=0;edge<4;++edge) + line(exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3+edge*4+2),exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 +edge*2+1), + exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3+edge*4),exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 +edge*2),exe_.u8(::bmh::layout::Analytics_Render_RuntimeField+edge)); + else for(int y=52;y<=137;++y)for(int x=12;x<=310;++x) + out.at(x,y)=exe_.u8(::bmh::layout::Advertising_PatternRect_RuntimeField+((y-52)%16)*16+(x-12)%16); + for(int curve=0;curve<4;++curve){ + const int x=27+(curve%2)*120,y=142+(curve/2)*11; + const uint8_t color=exe_.u8(::bmh::layout::Analytics_FormatError_RuntimeField+curve); + rect(out,x-7,y+3,5,4,color);line(x-8,y+2,x-2,y+2,0x68); + line(x-8,y+2,x-8,y+7,0x68);line(x-2,y+3,x-2,y+7,0x62); + line(x-8,y+7,x-2,y+7,0x62);out.at(x-8,y+2)=0x6a; + button(out,x,y,96,exe_.cstring(exe_.u32(::bmh::layout::Analytics_FormatError_ExecutableField+(12+curve)*4)), + pressed_==curve+10 || (projection_.statistics_flags&(1< values; + const auto& board=*projection_.redraw.context.board; + for(int month=0;month=high)throw FormatError("club player statistics: invalid Original scale"); + std::vector> points; + for(size_t month=0;month ClubPlayerDetailScreen::button_at(int x,int y) const { + const auto inside=[&](int bx,int by,int width){return x>=bx&&x<=bx+width&&y>=by&&y<=by+(width>31?10:9);}; + if(statistics_open_){ + for(int curve=0;curve<4;++curve)if(inside(27+(curve%2)*120,142+(curve/2)*11,96))return curve+10; + if(inside(265,142,30))return 14; + if(inside(265,153,30))return 15; + if(inside(8,185,140))return 16; + return std::nullopt; + } + const auto& c=projection_.redraw.context;const bool stats=c.board&&!c.human_loan; + if(inside(8,211,60))return 0; + if(stats&&inside(80,211,96))return 1; + if((c.national_action_available||c.active_offer>=0)&&inside(stats?182:80,211,122))return 2; + return std::nullopt; +} +void ClubPlayerDetailScreen::request(ClubPlayerDetailRequestKind kind,int source_return){ + request_={kind,projection_.redraw.context.selection,projection_.statistics_flags,source_return}; +} +bool ClubPlayerDetailScreen::finish_statistics(){ + restored_card_frame_=render_statistics();statistics_frame_.reset(); + statistics_open_=false;awaiting_redraw_=true; + request(ClubPlayerDetailRequestKind::redraw_card);return true; +} +bool ClubPlayerDetailScreen::activate(int id){ + if(id>=10&&id<=13){statistics_frame_=render_statistics();projection_.statistics_flags^=uint8_t(1<<(id-10));return true;} + if(id==14||id==15){statistics_frame_=render_statistics();projection_.statistics_flags^=0xc0;return true;} + if(id==16)return finish_statistics(); + if(id==0){closed_=true;request(ClubPlayerDetailRequestKind::close);return true;} + if(id==1){statistics_open_=true;statistics_frame_.reset();return true;} + if(id==2){ + closed_=true; + request(projection_.redraw.context.national_action_available? + ClubPlayerDetailRequestKind::national_action:ClubPlayerDetailRequestKind::offer_action,0xff); + return true; + } + return false; +} +bool ClubPlayerDetailScreen::move(int x,int y){ + if(!pressed_)return false; + if(button_at(x,y)!=pressed_){pressed_.reset();return true;}return false; +} +bool ClubPlayerDetailScreen::press(int x,int y,bool right){ + if(closed_||awaiting_redraw_)return false; + if(right){pressed_.reset();if(statistics_open_)return finish_statistics();closed_=true;request(ClubPlayerDetailRequestKind::close);return true;} + pressed_=button_at(x,y);if(pressed_)return true; + if(!statistics_open_){closed_=true;request(ClubPlayerDetailRequestKind::close);return true;}return false; +} +bool ClubPlayerDetailScreen::release(int x,int y,bool right){ + if(right||closed_||awaiting_redraw_||!pressed_)return false; + const auto chosen=pressed_;pressed_.reset();if(button_at(x,y)!=chosen)return true; + return activate(*chosen); +} +bool ClubPlayerDetailScreen::held_left_ticks(uint32_t ticks){ + if(ticks<=25||closed_||awaiting_redraw_||statistics_open_||projection_.redraw.context.human_loan)return false; + pressed_.reset();closed_=true; + request(ClubPlayerDetailRequestKind::close,projection_.redraw.context.source_slot+1);return true; +} +bool ClubPlayerDetailScreen::process_timer_expired(){ + if(closed_||awaiting_redraw_||pressed_||request_.kind!=ClubPlayerDetailRequestKind::none)return false; + if(statistics_open_)return finish_statistics(); // CopyOpaqueSlice returns before42dbd rebuilds. + closed_=true; + request(ClubPlayerDetailRequestKind::close); //ClubPlayerDetailFromGame returns0; it never chooses an offer/national action. + return true; +} +ClubPlayerDetailRequest ClubPlayerDetailScreen::take_request(){auto r=request_;request_={};return r;} +void ClubPlayerDetailScreen::replace_redraw(ClubPlayerDetailProjection next){ + if(!awaiting_redraw_)throw FormatError("club player detail: no Source redraw pending"); + validate(next); + const auto& a=projection_.redraw.context.selection;const auto& b=next.redraw.context.selection; + if(a.runtime_team!=b.runtime_team||a.player_id!=b.player_id||a.rendered_row!=b.rendered_row|| + a.physical_row!=b.physical_row||a.human_loan_index!=b.human_loan_index|| + a.origin!=b.origin||a.market_pool_slot!=b.market_pool_slot) + throw FormatError("club player detail: redraw identity changed"); + projection_=std::move(next);awaiting_redraw_=false;pressed_.reset(); +} +} // namespace bmh::ui diff --git a/src/ui/club_player_detail.hpp b/src/ui/club_player_detail.hpp new file mode 100644 index 0000000..dbaf7c4 --- /dev/null +++ b/src/ui/club_player_detail.hpp @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include "game/club_player_detail.hpp" +#include "formats/font.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" + +namespace bmh::ui { + +struct ClubPlayerDetailClub { + int runtime_team = -1; + uint16_t badge_selector = 0; + std::string original_full_name; + std::string original_short_name; +}; + +// Owned ClubPlayerDetailFromGame inputs. The redraw is produced by Core once per actual +// card rebuild; render/move/press/release never touch state or RNG. +struct ClubPlayerDetailProjection { + ClubPlayerDetailRedraw redraw; + std::array, 2> clubs; + std::string original_nationality_name; + int currency_numerator = 1, currency_denominator = 1; + bool gradient_text = true; + bool injury_as_text = false; + uint8_t statistics_months = 0, statistics_flags = 0; + std::optional displayed_offer_amount; +}; +ClubPlayerDetailProjection club_player_detail_from_game(const GameState&, + ClubPlayerDetailRedraw redraw, const LeImage&); + +enum class ClubPlayerDetailRequestKind : uint8_t { + none, close, redraw_card, national_action, offer_action +}; +struct ClubPlayerDetailRequest { + ClubPlayerDetailRequestKind kind = ClubPlayerDetailRequestKind::none; + ClubPlayerDetailSelection selection; + uint8_t statistics_flags = 0; + int source_return = 0; // 0 rebuilds ClubInfo; nonzero closes its parent. + bool close_parent() const { return source_return != 0; } +}; + +class ClubPlayerDetailScreen { +public: + ClubPlayerDetailScreen(const std::filesystem::path&, ClubPlayerDetailProjection, + Image parent_frame); + Image render() const; + bool move(int x, int y); + bool press(int x, int y, bool right = false); + bool release(int x, int y, bool right = false); + bool key(std::string_view) { return false; } // OriginalMouseSound ignores keys. + // Source CareerSession_InitializeClubModalRuntime_ExecutableField becomes true after more than25 held-left BIOS ticks. + // Caller consumes the opening DOWN in bbcde!=0, including its optional + // wait-for-prior-hold-release boundary; only selection mode retains it. + bool held_left_ticks(uint32_t ticks); + // OriginalMouseSound event8 follows the normal statistics/card return, after + // ExpireQuestion has released its pressed control. No player action is selected. + bool process_timer_expired(); + bool source_mouse_wait_release_pending() const { return pressed_.has_value(); } + ClubPlayerDetailRequest take_request(); + // After statistics returns, the caller persists statistics_flags and runs + // Core redraw once, then supplies the new projection before presenting. + void replace_redraw(ClubPlayerDetailProjection); + bool in_statistics() const { return statistics_open_; } + bool awaiting_redraw() const { return awaiting_redraw_; } + const ClubPlayerDetailProjection& projection() const { return projection_; } +private: + ClubPlayerDetailProjection projection_; + LeImage exe_; + Font small_, heading_; + TextDb texts_; + Image widgets_, atlas_, flags_, portrait_, letters_, parent_; + std::array, 2> badges_; + std::optional statistics_frame_, restored_card_frame_; + bool statistics_open_ = false, awaiting_redraw_ = false, closed_ = false; + std::optional pressed_; + ClubPlayerDetailRequest request_; + const std::string& label(uint32_t) const; + void text(Image&, int x, int baseline, std::string_view, uint8_t color, + int right = -1, bool heading = false) const; + void frame(Image&, int x, int y, int width, int height) const; + void button(Image&, int x, int y, int width, std::string_view, bool active = false) const; + void draw_portrait(Image&) const; + Image render_card() const; + Image render_statistics() const; + std::optional button_at(int x, int y) const; + bool activate(int); + bool finish_statistics(); + void request(ClubPlayerDetailRequestKind, int source_return = 0); +}; +} // namespace bmh::ui diff --git a/src/ui/contracts.cpp b/src/ui/contracts.cpp new file mode 100644 index 0000000..add8bcf --- /dev/null +++ b/src/ui/contracts.cpp @@ -0,0 +1,795 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/contracts.hpp" +#include "ui/game_end.hpp" + +#include +#include +#include + +#include "game/state.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +constexpr size_t kManagerRecord = 0xb0c; +constexpr size_t kBoard = 0x840; +constexpr size_t kBoardSlot = 0x58; + +void copy_region(Image& target, const Image& source, int sx, int sy, int x, int y, int width, int height, bool transparent = false) { + if (sx < 0 || sy < 0 || x < 0 || y < 0 || width < 0 || height < 0 || + sx + width > source.width || sy + height > source.height || x + width > target.width || y + height > target.height) + throw FormatError("contracts: invalid original widget bounds"); + for (int yy = 0; yy < height; ++yy) for (int xx = 0; xx < width; ++xx) { + const uint8_t value = source.pixels[size_t(sy + yy) * size_t(source.width) + size_t(sx + xx)]; + if (!transparent || value != 0) target.at(x + xx, y + yy) = value; + } +} + +void fill(Image& target, int x, int y, int width, int height, uint8_t color); + +void pattern(Image& out, const LeImage& exe, int x, int y, int width, int height) { + for (int yy = 0; yy < height; ++yy) + for (int xx = 0; xx < width; ++xx) + out.at(x + xx, y + yy) = exe.u8(::bmh::layout::Advertising_PatternRect_RuntimeField + size_t(yy % 16) * 16 + size_t(xx % 16)); +} + +void frame(Image& out, const LeImage& exe, const Image& widgets, int x, int y, int width, int height, bool shadow = true) { + if (shadow) { fill(out, x + 2, y + height, width, 2, 0x40); fill(out, x + width, y + 2, 2, height, 0x40); } + pattern(out, exe, x + 4, y + 4, width - 7, height - 7); + copy_region(out, widgets, 0, 0, x, y, 4, 4); + copy_region(out, widgets, 4, 0, x + width - 4, y, 4, 4); + copy_region(out, widgets, 0, 4, x, y + height - 4, 4, 4); + copy_region(out, widgets, 4, 4, x + width - 4, y + height - 4, 4, 4); + for (int at = 4; at < width - 4; at += 74) { + const int n = std::min(74, width - 4 - at); + copy_region(out, widgets, 0, 104, x + at, y, n, 4); + copy_region(out, widgets, 0, 108, x + at, y + height - 4, n, 4); + } + for (int at = 4; at < height - 4; at += 96) { + const int n = std::min(96, height - 4 - at); + copy_region(out, widgets, 0, 8, x, y + at, 4, n); + copy_region(out, widgets, 4, 8, x + width - 4, y + at, 4, n); + } +} + +void fill(Image& target, int x, int y, int width, int height, uint8_t color) { + if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > target.width || y + height > target.height) + throw FormatError("contracts: invalid fill bounds"); + for (int row = 0; row < height; ++row) + std::fill_n(target.pixels.begin() + size_t(y + row) * size_t(target.width) + size_t(x), size_t(width), color); +} + +// FormatGroupedDigits: '%' is the original bitmap font's blank padding glyph. +std::string original_number(uint32_t value, int width, bool grouped = false) { + std::string digits = std::to_string(value); + const int actual = int(digits.size()); + const int padding = std::max(0, width - actual); + digits.insert(0, size_t(padding), '%'); + if (grouped) { + for (int from = actual - 3; from > 0; from -= 3) + digits.insert(size_t(padding + from), "."); + const int wanted = width > 3 ? (width - 4) / 3 + 1 : 0; + const int used = actual > 3 ? (actual - 1) / 3 : 0; + if (wanted > used) digits.insert(0, size_t(wanted - used), ' '); + } + return digits; +} +std::string money(uint32_t value, int width = 5) { + return original_number(value, width, true) + " EU"; +} +std::string plain_number(uint32_t value) { + return original_number(value, 0, true); +} +} + +ContractsState contracts_from_game(const GameState& game, int manager_slot, uint64_t revision) { + if (manager_slot < 0 || manager_slot >= 4 || size_t(manager_slot) >= game.manager_teams.size() || + size_t(manager_slot) * kManagerRecord + kManagerRecord > game.manager_records.size()) + throw FormatError("contracts: invalid manager slot"); + const int team = game.manager_teams[size_t(manager_slot)]; + if (team == kNoTeam) throw FormatError("contracts: Vereinsverträge sind für Nationalteams nicht verfügbar"); + const SquadRange range = squad_range(team); + const size_t board = size_t(manager_slot) * kBoard; + if (range.count > 24 || range.first + range.count > game.squad_slots.size() || board + range.count * kBoardSlot > game.tactics.size()) + throw FormatError("contracts: invalid squad bounds"); + ContractsState state; + state.manager_slot = manager_slot; + state.runtime_club = team; + state.revision = revision; + state.mode_three = game.memory.u8(::bmh::layout::GameMode) == 3; + state.gradient_text = game.memory.u8(::bmh::layout::TextGradientDisabled) == 0; + state.decorated_background = game.memory.u8(::bmh::layout::PlainBackground) == 0; + state.currency_numerator = game.memory.has(::bmh::layout::CurrencyMultiplier) ? game.memory.u32(::bmh::layout::CurrencyMultiplier) : 1; + state.currency_denominator = game.memory.has(::bmh::layout::CurrencyDivisor) ? game.memory.u32(::bmh::layout::CurrencyDivisor) : 1; + if (!state.currency_denominator) throw FormatError("contracts: invalid currency divisor"); + state.club_name = original_to_utf8(game.club_name(team)); + const size_t manager = size_t(manager_slot) * kManagerRecord; + if (manager + 0x23a > game.manager_records.size()) throw FormatError("contracts: manager identity is unavailable"); + const auto name_begin = game.manager_records.begin() + std::ptrdiff_t(manager + 0xa8); + const auto name_end = std::find(name_begin, name_begin + 26, uint8_t(0)); + state.manager_name = original_to_utf8(std::string_view( + reinterpret_cast(&*name_begin), size_t(name_end - name_begin))); + state.manager_portrait = game.manager_records[manager + 0x221]; + if (state.manager_portrait < 0 || state.manager_portrait > 11) throw FormatError("contracts: invalid manager portrait"); + if (size_t(team) * 2 + 2 > game.club_heap_78.size()) throw FormatError("contracts: club badge identity is unavailable"); + state.badge_sprite = (int(game.club_heap_78[size_t(team) * 2]) | + int(game.club_heap_78[size_t(team) * 2 + 1]) << 8) & 0x1ff; + for (size_t row = 0; row < range.count; ++row) { + const int player = game.squad_slots.at(range.first + row) & 0x0fff; + if (player == 0x0fff) continue; + if (player < 0 || size_t(player) >= game.players.size()) + throw FormatError("contracts: invalid player in squad"); + const size_t at = board + row * kBoardSlot; + const auto& source = game.players[size_t(player)]; + ContractPlayer view; + view.row = int(row); + view.player_id = player; + view.name = original_to_utf8(game.player_name(player)); + view.age = source.age(); + view.position = source.position(); + view.remaining_months = game.tactics.at(at + 0x0c); + view.current_monthly_salary = uint32_t(game.tactics.at(at + 0x50)) | + uint32_t(game.tactics.at(at + 0x51)) << 8 | + uint32_t(game.tactics.at(at + 0x52)) << 16 | + uint32_t(game.tactics.at(at + 0x53)) << 24; + view.insurance = game.tactics.at(at + 0x43); + view.insurance_available = view.insurance == 0 && (game.tactics.at(at + 0x0b) & 0x60) == 0 && + (source.w35c >> 27) == 0; + view.offer_blocked = (game.tactics.at(at + 0x4f) & 0x80) != 0; + view.insurance_fee = uint16_t(game.tactics.at(at + 0x4e)) | + uint16_t(game.tactics.at(at + 0x4f) & 0x7f) << 8; + for (size_t premium = 0; premium < view.team_premiums.size(); ++premium) + view.team_premiums[premium] = game.tactics.at(at + 0x12 + premium); + view.attributes = {uint8_t(source.condition()), uint8_t(source.technique()), uint8_t(source.form()), uint8_t(source.strength())}; + view.board_flags = game.tactics.at(at + 0xb); + view.source.row = int(row); view.source.player_id = player; + view.source.slot = game.squad_slots.at(range.first + row); + view.source.name = game.player_name(player); view.source.attributes = source; + view.source.cards = game.player_cards.at(size_t(player)); view.source.bonus = game.player_bonus.at(size_t(player)); + std::copy_n(game.tactics.begin() + std::ptrdiff_t(at), 0x58, view.source.board.begin()); + state.players.push_back(std::move(view)); + } + if (!state.players.empty()) { + state.team_premiums = state.players.front().team_premiums; + for (const auto& player : state.players) + for (size_t i = 0; i < state.team_premiums.size(); ++i) + state.team_premiums[i] = std::min(state.team_premiums[i], player.team_premiums[i]); + } + return state; +} + +std::string contract_request_json(const ContractRequest& r) { + const char* kind = "demands"; + switch (r.kind) { + case ContractActionKind::request_demands: kind = "demands"; break; + case ContractActionKind::submit_offer: kind = "offer"; break; + case ContractActionKind::submit_bonuses: kind = "bonuses"; break; + case ContractActionKind::insure_player: kind = "insurance"; break; + } + std::ostringstream out; + out << "{\"kind\":\"" << kind + << "\",\"request_id\":" << r.request_id << ",\"revision\":" << r.revision + << ",\"manager_slot\":" << r.manager_slot << ",\"runtime_club\":" << r.runtime_club + << ",\"row\":" << r.row << ",\"player_id\":" << r.player_id + << ",\"quote_id\":" << r.quote_id << ",\"term_column\":" << unsigned(r.term_column) + << ",\"demand\":" << r.demand << ",\"monthly_salary\":" << r.monthly_salary + << ",\"insurance_months\":" << unsigned(r.insurance_months) << ",\"proposed_bonuses\":["; + for (size_t i = 0; i < r.proposed_bonuses.size(); ++i) { if (i) out << ','; out << unsigned(r.proposed_bonuses[i]); } + out << "]}"; + return out.str(); +} + +std::string contracts_state_json(const ContractsState& s) { + std::ostringstream out; + out << "{\"manager_slot\":" << s.manager_slot << ",\"runtime_club\":" << s.runtime_club + << ",\"revision\":" << s.revision << ",\"club_name\":" << json_quote(s.club_name) + << ",\"manager_name\":" << json_quote(s.manager_name) << ",\"manager_portrait\":" << s.manager_portrait + << ",\"badge_sprite\":" << s.badge_sprite + << ",\"selected_row\":" << s.selected_row << ",\"quote_id\":" << s.quote_id + << ",\"quote_row\":" << s.quote_row << ",\"players\":["; + for (size_t i = 0; i < s.players.size(); ++i) { + const auto& p = s.players[i]; + if (i) out << ','; + out << "{\"row\":" << p.row << ",\"player_id\":" << p.player_id + << ",\"name\":" << json_quote(p.name) << ",\"age\":" << p.age + << ",\"position\":" << p.position << ",\"remaining_months\":" << unsigned(p.remaining_months) + << ",\"current_monthly_salary\":" << p.current_monthly_salary << '}'; + } + out << "],\"demands\":"; + if (s.demands) { + out << '['; + for (size_t i = 0; i < s.demands->size(); ++i) { if (i) out << ','; out << (*s.demands)[i]; } + out << ']'; + } else out << "null"; + out << ",\"feedback\":" << json_quote(s.feedback) << '}'; + return out.str(); +} + +ContractsScreen::ContractsScreen(const std::filesystem::path& data, ContractsState state) + : state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))), + large_font_(load_font(asset_path(data / "F", "BMH2.FNT"))), sprite_font_(data), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + atlas_(load_vga(asset_path(data / "KB", "2.VGA"))), + flags_(load_vga(asset_path(data / "KB", "24.VGA"))), + background_(load_vga(asset_path(data / "KB", "129.VGA"))), + widgets_(load_vga(asset_path(data / "KB", "0.VGA"))), + calculator_(load_vga(asset_path(data / "KB", "6.VGA"))), + faces_(load_vga(asset_path(data / "KB", "26.VGA"))) { + if (atlas_.width == 314) { Image padded(320, atlas_.height, 0); padded.blit(atlas_,0,0); atlas_ = std::move(padded); } + if (state_.manager_slot < 0 || state_.manager_slot > 3 || state_.runtime_club < 0 || + state_.players.size() > 24 || background_.width != 320 || background_.height != 240) + throw FormatError("contracts: invalid state"); + if (state_.manager_portrait < 0 || state_.manager_portrait > 11 || state_.badge_sprite < 0 || state_.badge_sprite > 0x1ff) + throw FormatError("contracts: invalid manager identity"); + if (source_badge_fallback(state_.runtime_club)) badge_atlas_ = widgets_; + else badge_atlas_ = load_vga(asset_path(data / "W", std::to_string(state_.badge_sprite >> 3) + ".VGA")); +} + +void ContractsScreen::text(Image& out, int x, int baseline, std::string_view value, uint8_t color, int right) const { + std::string bytes = utf8_to_original(value); + const int limit = right < 0 ? out.width : std::min(right, out.width); + if (font_.text_width(bytes) > limit - x) return; + const int top = baseline - font_.baseline; + if (x < 0 || top < 0 || top + font_.height > out.height) return; + const int width = std::max(1, font_.text_width(bytes)); + Image mask(width, font_.height, 0); + font_.draw(mask, 0, 0, bytes, 1); + int gradient = 0; + while (gradient < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + gradient) != color) ++gradient; + for (int yy = 0; yy < font_.height; ++yy) + for (int xx = 0; xx < width; ++xx) + if (mask.at(xx, yy)) out.at(x + xx, top + yy) = state_.gradient_text && exe_.u8(::bmh::layout::TextGradientMode) == 2 && gradient < 32 ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + gradient * 6 + std::min(yy, 5)) : color; +} + +void ContractsScreen::emit(ContractRequest request) { + if (pending_) return; + request.request_id = state_.request_id_base + next_request_id_++; + request.revision = state_.revision; + request.manager_slot = state_.manager_slot; + request.runtime_club = state_.runtime_club; + pending_ = request; +} + +void ContractsScreen::open_calculator(int target, Page return_page, uint32_t initial) { + calculator_backdrop_ = render(); + calculator_bonus_index_ = target; + calculator_return_ = return_page; + calculator_initial_ = initial; + salary_input_ = initial; + if (target >= 0) { + calculator_max_ = target < 3 ? 20u : 1000u; + const uint32_t first = target < 3 ? 1u : uint32_t(50 - 10 * (target - 3)); + const uint32_t step = first; + for (size_t i = 0; i < 6; ++i) calculator_presets_[i] = first + uint32_t(i) * step; + } else if (target == -2) { + calculator_max_ = 60; + for (size_t i = 0; i < 6; ++i) calculator_presets_[i] = 12u + uint32_t(i) * 6u; + } else { + calculator_max_ = 200000;initial=std::min(initial,calculator_max_); + uint32_t factor=1000, step=0; + while(!step && factor) {step=factor*((initial/factor)/10);if(!step)factor/=10;} + if(!step)step=1; + initial=std::min(initial,calculator_max_); + const uint32_t rounded = 1000u * (initial / 1000u); + const uint32_t first = rounded >= 3u * step ? rounded - 3u * step : 0u; + for (size_t i = 0; i < 6; ++i) calculator_presets_[i] = first + uint32_t(i) * step; + } + salary_input_=std::min(initial,calculator_max_);calculator_initial_=salary_input_; + for(auto& preset:calculator_presets_)if(preset>calculator_max_)preset=UINT32_MAX; + calculator_presets_[6] = 0; + calculator_presets_[7] = calculator_max_; + page_ = Page::calculator; + editing_salary_ = true; +} + +bool ContractsScreen::text(std::string_view value) { + if (pending_ || !editing_salary_) return false; + bool changed = false; + for (char c : value) { + if (c == '\b' || c == 127) { salary_input_ /= 10; changed = true; } + else if (c >= '0' && c <= '9') { + const uint32_t digit = uint32_t(c - '0'); + if (salary_input_ <= (calculator_max_ - digit) / 10) { + salary_input_ = salary_input_ * 10 + digit; + changed = true; + } + } + } + return changed; +} + +// LineupScreen, contract mode: the same roster as lineup, including its +// original fixed-width number strings, jersey marks, and bitmap icons. +Image ContractsScreen::render_roster() const { + Image out = state_.decorated_background ? background_ : Image(320, 240); + if (!state_.decorated_background) { + fill(out, 0, 4, 320, 13, 0x44); fill(out, 1, 5, 318, 11, 0x39); + fill(out, 0, 228, 320, 10, 0x44); fill(out, 1, 229, 318, 8, 0x39); + } + auto original_text = [&](int x, int y, std::string_view raw, uint8_t color, int right = -1) { + const int width = font_.text_width(raw); + if (right >= 0) x += (right - x) / 2 - width / 2; + text(out, x, y, original_to_utf8(raw), color, -1); + }; + const auto fixed = [](uint32_t value, int width, bool grouped = false) { return original_number(value, width, grouped); }; + const auto title = original_to_utf8(texts_[(::bmh::layout::Contracts_RenderRoster_TextPointer2 - ::bmh::layout::TextPointerTable) / 4]); + sprite_font_.draw(out, SpriteFont::centered_title_x(sprite_font_.text_width(title)), 13, title, 5); + sprite_font_.draw(out, 5, 235, state_.club_name, 5); + const auto header = tab_ == 0 ? texts_[(::bmh::layout::ClubInfo_Render_TextPointer3 - ::bmh::layout::TextPointerTable) / 4] : tab_ == 1 ? texts_[(::bmh::layout::ClubInfo_Render_TextPointer4 - ::bmh::layout::TextPointerTable) / 4] : exe_.cstring(exe_.u32(::bmh::layout::Contracts_RenderRoster_TextPointer)); + original_text(0, 26, header, 0x51); + int baseline = 36; + uint16_t preceding = 0; + for (size_t visual = 0; visual < state_.players.size(); ++visual) { + const auto& p = state_.players[visual]; const auto& s = p.source; const auto& a = s.attributes; + if (visual && (s.slot & 0xc000) != (preceding & 0xc000)) baseline += 2; + preceding = s.slot; + if (s.slot & 0xc000) { + const int jersey = (s.cards & 31) + 1; + const uint8_t color = s.slot & 0x1000 ? 0xf3 : s.slot & 0x8000 ? 0x6c : 0x68; + original_text(4, baseline, std::string(1, char('0' + jersey % 10)), color); + if (jersey >= 10) original_text(0, baseline, exe_.cstring(::bmh::layout::ClubInfo_Render_TextPointer), color); + } + const uint8_t name_color = p.row == state_.selected_row ? 0x27 : p.row == hovered_row_ ? 0x3e : + tab_ == 2 && (p.offer_blocked || (p.board_flags & 0x20)) ? 0xf7 : visual % 2 ? 0x67 : 0x6b; + original_text(13, baseline, s.name, name_color); + if (tab_ != 1) { + original_text(66, baseline, texts_[(::bmh::layout::ClubInfo_Render_TextPointer2 - ::bmh::layout::TextPointerTable) / 4 + a.position()], 0x6c, 82); + for (int field = 0; field < 2; ++field) { + int value = (a.w35c >> (field == 0 ? 24 : 21)) & 7; if (value > 4) --value; + copy_region(out, atlas_, 208 + value * 16, field == 0 ? 17 : 22, + field == 0 ? 88 : 103, baseline - 5, 16, 5, true); + } + std::string values = fixed(a.condition(), 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField) + fixed(a.technique(), 2) + + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField) + fixed(a.form(), 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField2) + fixed(a.strength(), 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField3); + if (tab_ == 2 || tab_ == 3) { + values += fixed(a.age(), 2) + texts_[(::bmh::layout::Contracts_RenderRoster_TextPointer3 - ::bmh::layout::TextPointerTable) / 4]; + const uint32_t numerator = state_.currency_numerator, denominator = state_.currency_denominator; + const auto currency = [&](uint32_t value, int width) { return fixed(uint32_t(value * numerator) / denominator, width, true) + exe_.cstring(::bmh::layout::CurrencySuffixText); }; + values += currency(p.current_monthly_salary, 6) + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField2); + values += p.remaining_months == 255 ? exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField3) : fixed(p.remaining_months, 2) + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField4); + values += p.insurance == 0 ? texts_[(::bmh::layout::Contracts_RenderRoster_TextPointer4 - ::bmh::layout::TextPointerTable) / 4] : currency(p.insurance_fee, 5) + + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField2) + fixed(p.insurance & 0x3f, 2) + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField); + original_text(117, baseline, values, 0x6c); + } else { + original_text(117, baseline, values + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4), 0x6c); + copy_region(out, atlas_, 304, int(s.board[0xe] >> 6) * 3, 179, baseline - 4, 16, 3, true); + const int injury = (a.w364 >> 16) & 31, marker = a.w35c >> 27; + if (!marker && !injury) { + const int status = s.slot & 0x8000 ? 0 : s.slot & 0x4000 ? 1 : 2; + copy_region(out, atlas_, 272, status * 5, 191, baseline - 5, 32, 5, true); + } else { + const int status = !marker ? 5 : marker == 31 ? 8 : !injury ? 4 : 3; + copy_region(out, atlas_, 197, (status - 3) * 6 + 1, 196, baseline - 5, 10, 5); + } + const int nation = a.nationality() + ((s.bonus & 0x80) >> 2); + copy_region(out, flags_, nation % 12 * 9, nation / 12 * 6, 217, baseline - 6, 9, 6); + original_text(232, baseline, fixed(s.board[0xf], 2), s.board[0xf] < 61 ? 0x66 : s.board[0xf] < 71 ? 0x27 : 0xfb); + original_text(247, baseline, fixed(a.w364 >> 26, 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + fixed((a.w364 >> 2) & 63, 2) + + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + fixed((a.w368 >> 18) & 63, 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + + fixed((a.w368 >> 14) & 15, 2) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField4) + fixed((a.w368 >> 24) & 7, 2) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField), 0x6c); + } + } else { + original_text(65, baseline, fixed(a.age(), 2) + texts_[(::bmh::layout::ClubInfo_Render_TextPointer5 - ::bmh::layout::TextPointerTable) / 4], 0x6c); + for (int skill = 0; skill < 7; ++skill) copy_region(out, atlas_, 256 + a.skill(Player::Skill(skill)) * 16, 32, 87 + skill * 10, baseline - 5, 16, 5, true); + auto word = [&](int at) { return uint16_t(s.board[at] | uint16_t(s.board[at + 1]) << 8); }; + original_text(165, baseline, fixed(s.bonus & 127, 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + fixed(s.board[7], 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + + fixed(s.board[9], 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + fixed(word(0x48), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField2) + + fixed(word(0x4a), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField2) + fixed(word(0x4c), 3) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField), 0x6c); + } + baseline += 7; + } + return out; +} + +Image ContractsScreen::render() const { + Image out(320, 240); + if (page_ == Page::result && result_backdrop_) out = *result_backdrop_; + else if (page_ == Page::calculator && calculator_backdrop_) out = *calculator_backdrop_; + else out = render_roster(); + if (page_ == Page::result) { + // The original manager response is drawn over the still-open contract + // panel; the saved pixels below it are the exact pre-ACK screen. + } + const auto selected = std::find_if(state_.players.begin(), state_.players.end(), + [&](const auto& p) { return p.row == state_.selected_row; }); + static constexpr std::array tabs{"DATEN-A", "DATEN-B", "GEHALT", "TEAM-PRÄMIEN"}; + for (int i = 0; i < (state_.mode_three?4:3); ++i) { + const int x = i * 60 + 2, w = i == 3 ? 71 : 51; + if(i!=tab_) {fill(out,x+2,225,w,2,0x40);fill(out,x+w,217,2,10,0x40);} + else {const uint8_t color=out.at(x,225);fill(out,x,215,w+1,2,color);fill(out,x,215,2,11,color);} + const int source_y = i == tab_ ? 44 : 74; + const int dest_y = 215 + (i == tab_ ? 2 : 0); + const int dest_x = x + (i == tab_ ? 2 : 0); + copy_region(out, widgets_, 24, source_y, dest_x, dest_y, 31, 10); + int tab_at = 31, remain = w - 31; + while (remain > 20) { const int n = std::min(8, remain - 20); copy_region(out, widgets_, 24, source_y + 10, dest_x + tab_at, dest_y, n, 10); tab_at += n; remain -= n; } + if (remain > 0) copy_region(out, widgets_, 45 - remain, source_y + 20, dest_x + tab_at, dest_y, remain, 10); + sprite_font_.draw(out, dest_x + w/2 - sprite_font_.text_width(tabs[size_t(i)])/2, dest_y+7, tabs[size_t(i)], exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + (i==tab_))); + } + + auto panel = [&](int x, int y, int w, int h, bool shadow = true) { + frame(out, exe_, widgets_, x, y, w, h, shadow); + }; + auto button = [&](int x, int y, int w, std::string_view label) { + fill(out, x + 2, y + 10, w, 2, 0x40); fill(out, x + w, y + 2, 2, 10, 0x40); + copy_region(out, widgets_, 24, 74, x, y, 31, 10); + int at = 31, remaining = w - 31; + while (remaining > 20) { const int n = std::min(8, remaining - 20); copy_region(out, widgets_, 24, 84, x + at, y, n, 10); at += n; remaining -= n; } + if (remaining > 0) copy_region(out, widgets_, 45 - remaining, 94, x + at, y, remaining, 10); + const int font = exe_.u8(::bmh::layout::Advertising_Button_RuntimeField); + sprite_font_.draw(out, x + (w - sprite_font_.text_width(label)) / 2, y + 7, label, font); + }; + auto db = [&](uint32_t address) { return original_to_utf8(texts_[(address-::bmh::layout::TextPointerTable)/4]); }; + auto centered = [&](int left,int right,int y,std::string_view value,uint8_t color) { + const int x=left+(right-left)/2-font_.text_width(utf8_to_original(value))/2; + text(out,x,y,value,color,-1); + }; + const bool negotiating = page_ == Page::player_offer || page_ == Page::team_premiums; + if (negotiating) { + const bool team = page_ == Page::team_premiums && team_premium_mode_; + const int top = team || selected == state_.players.end() || selected->row >=13 ?22:130; + panel(0,top,319,90,false); + const auto heading = db(::bmh::layout::Contracts_Out_ExecutableField3 + (page_==Page::team_premiums?4:0)) + db(::bmh::layout::Contracts_Out_ExecutableField5) + (team?db(::bmh::layout::Contracts_Out_ExecutableField6):selected->name); + large_font_.draw(out,5,top+11-large_font_.baseline,utf8_to_original(heading),108); + fill(out,5,top+12,309,1,108); + if(!team && selected!=state_.players.end()) { + std::string current=db(::bmh::layout::Contracts_Out_ExecutableField7)+selected->name; + if(!selected->remaining_months)current+=db(::bmh::layout::Contracts_Out_ExecutableField8); + else current+=db(::bmh::layout::Contracts_Out_ExecutableField9)+std::to_string(selected->remaining_months)+db(::bmh::layout::Contracts_Out_ExecutableField10)+money(selected->current_monthly_salary)+db(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField4); + text(out,5,top+19,current,108,-1); + std::string insurance=db(::bmh::layout::Contracts_Out_TextPointer4); + if(selected->insurance) insurance=db(::bmh::layout::Contracts_Out_TextPointer3)+std::to_string(selected->insurance&63)+db(::bmh::layout::Contracts_Out_ExecutableField11)+ + db(::bmh::layout::ClubPlayerDetail_Copy_TextPointer6+((selected->insurance>>6)&3)*4)+db(::bmh::layout::Contracts_Out_ExecutableField12)+money(selected->insurance_fee)+db(::bmh::layout::Contracts_Out_ExecutableField13); + text(out,5,top+25,insurance,108,-1); + } + if(page_==Page::player_offer && selected!=state_.players.end()) { + text(out,5,top+46,db(::bmh::layout::Contracts_Out_ExecutableField14),106,-1);text(out,5,top+54,db(::bmh::layout::Contracts_Out_TextPointer5),106,-1); + if(state_.mode_three)text(out,5,top+72,db(::bmh::layout::Contracts_Out_TextPointer6),106,-1); + for(int term=0;term<4;++term) { + const int left=70+60*term; + centered(left,left+60,top+37,std::to_string(term+1)+db(::bmh::layout::Contracts_Out_ExecutableField15)+(term?exe_.cstring(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer):""),107); + if(salary_offer_set_ && term==offer_term_) centered(left,left+60,top+46,money(offer_salary_),108); + const uint32_t demand=state_.demands?(*state_.demands)[size_t(term)]:UINT32_MAX; + centered(left,left+60,top+54,demand==UINT32_MAX?db(::bmh::layout::Contracts_Out_ExecutableField16):money(demand), + demand==UINT32_MAX || selected->offer_blocked || (selected->board_flags&0x60)?251:95); + if(state_.mode_three) { + centered(left,left+55,top+64,db(::bmh::layout::ClubPlayerDetail_Copy_TextPointer6+term*4),107); + const uint32_t fee=(((uint32_t(term*10+10)*selected->current_monthly_salary)/1000)*10); + centered(left,left+60,top+72,original_number(fee,5,true)+db(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField4),selected->insurance && ((selected->insurance>>6)&3)==term?39:106); + } + } + } else { + uint32_t base=0; int occupied=0; + if(team)for(const auto& p:state_.players){base+=p.current_monthly_salary;++occupied;} + else if(selected!=state_.players.end())base=selected->current_monthly_salary; + for(int i=0;i<7;++i) { + text(out,25,top+32+i*7,db(::bmh::layout::Contracts_Out_ExecutableField4+i*4),exe_.u8(::bmh::layout::Contracts_Out_TextPointer2+i),-1); + const unsigned rate=proposed_bonuses_[size_t(i)]; + if(!rate) text(out,132,top+32+i*7,db(::bmh::layout::Contracts_Out_TextPointer8),108,-1); + else { + const unsigned percent=rate*(i<3?1:5); + uint32_t salary=base; + if(team&&i<3&&occupied){salary/=occupied;if(i==2)salary*=11;if(i==1)salary*=occupied;} + text(out,97,top+32+i*7,original_number(percent,4,true)+db(::bmh::layout::Contracts_Out_TextPointer7)+money((uint32_t(percent)*salary)/100,7)+exe_.cstring(::bmh::layout::Contracts_Out_TextPointer),108,-1); + } + } + } + button(5,top+76,51,db(::bmh::layout::Contracts_Out_ExecutableField17));button(90,top+76,80,db(::bmh::layout::Contracts_Out_ExecutableField18)); + if(!team&&state_.mode_three)button(261,top+76,51,db(page_==Page::player_offer?::bmh::layout::Contracts_Out_ExecutableField2: ::bmh::layout::Contracts_Out_ExecutableField)); + } else if (page_ == Page::calculator) { + copy_region(out, calculator_, 0, 0, 10, 10, 113, 136); + fill(out,123,12,2,136,0x40);fill(out,12,146,113,2,0x40); + const auto label=calculator_bonus_index_==-2?db(::bmh::layout::Contracts_Out_ExecutableField19):calculator_bonus_index_<0?db(::bmh::layout::Contracts_Out_ExecutableField14):db(::bmh::layout::Contracts_Out_ExecutableField4+calculator_bonus_index_*4); + centered(18,115,24,label,98); + for(int i=0;i<15;++i) { + const int x=10+exe_.u16(::bmh::layout::Advertising_Click_RuntimeField+i*2), y=10+exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2+i); + copy_region(out,calculator_,0,136,x,y,15,14); + text(out,x+5,y+9,std::string(1,"0123456789DRCJN"[i]),98,-1); + } + for(int i=0;i<8;++i) { + const int x=10+exe_.u16(::bmh::layout::Advertising_Click_RuntimeField+(i+15)*2), y=10+exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2+i+15); + if(calculator_presets_[size_t(i)]==UINT32_MAX)continue; + const auto value=plain_number(calculator_presets_[size_t(i)]); + text(out,x+47-font_.text_width(value),y+12,value,98,-1); + } + const auto value=plain_number(salary_input_); + text(out,116-font_.text_width(value),120,value,0,-1); + } else if (page_ == Page::result) { + TaxDialogProjection notice; + notice.manager_name=utf8_to_original(state_.manager_name); + notice.portrait=state_.manager_portrait; + notice.badge_sprite=state_.badge_sprite; + notice.badge_fallback=source_badge_fallback(state_.runtime_club); + notice.body=utf8_to_original(state_.feedback); + notice.source_manager_flags=0x80; + draw_source_dialog(out,{widgets_,faces_,&badge_atlas_,font_,large_font_, + exe_,sprite_font_,texts_},notice,state_.gradient_text); + } + return out; +} + +bool ContractsScreen::click(int x, int y, bool right) { + if (page_ == Page::result) { + if (x >= 95 && x <= 220 && y >= 166 && y <= 176) { page_ = result_return_; result_backdrop_.reset(); state_.feedback.clear(); return true; } + return false; + } + if (right && page_ == Page::roster) { + if (x >= 61 || y < 29) { close_requested_ = true; return true; } + const ContractPlayer* p = nullptr; int baseline = 36; + for (size_t i=0;i=baseline-7 && yrow; + ContractRequest request; request.kind = ContractActionKind::request_demands; request.row = p->row; request.player_id = p->player_id; + emit(request); page_ = Page::player_offer; return true; + } + if (page_ == Page::roster && x < 18 && y < 18) { close_requested_ = true; pending_.reset(); return true; } + if (pending_) return false; + if(right && page_==Page::calculator){page_=calculator_return_;calculator_backdrop_.reset();editing_salary_=false;return true;} + if(right && page_!=Page::roster){page_=Page::roster;return true;} + if (page_ == Page::calculator) { + auto accept_calculator = [&]() { + if (calculator_bonus_index_ >= 0) { + const auto selected_player = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == state_.selected_row; }); + const uint32_t maximum = calculator_bonus_index_ < 3 ? 20u : 1000u; + if ((!team_premium_mode_ && selected_player == state_.players.end()) || salary_input_ > maximum) return false; + proposed_bonuses_[size_t(calculator_bonus_index_)] = uint8_t(calculator_bonus_index_ < 3 ? salary_input_ : salary_input_ / 5); + page_ = Page::team_premiums; editing_salary_ = false; calculator_bonus_index_ = -1; return true; + } + if (calculator_bonus_index_ == -2) { + const auto selected_player = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == state_.selected_row; }); + if (selected_player == state_.players.end() || salary_input_ < 1 || salary_input_ > 60) return false; + ContractRequest req; req.kind = ContractActionKind::insure_player; req.row = selected_player->row; + req.player_id = selected_player->player_id; req.quote_id = state_.quote_id; req.term_column = insurance_term_; + req.insurance_months = uint8_t(salary_input_); emit(req); calculator_bonus_index_ = -1; return true; + } + if (calculator_return_ == Page::player_offer && calculator_bonus_index_ == -1) { + offer_salary_ = salary_input_; offer_term_ = selected_term_; salary_offer_set_ = true; + } + page_ = calculator_return_; calculator_backdrop_.reset(); editing_salary_ = false; return true; + }; + if (x >= 69 && x < 85 && y >= 125 && y < 139) { + salary_input_ = 0; + return true; + } + // Key positions are read from the original calculator hitbox table. + for (int i = 0; i < 15; ++i) { + const int key_x = 10 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); + const int key_y = 10 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + if (x < key_x || x >= key_x + 16 || y < key_y || y >= key_y + 14) continue; + if (i <= 9) return text(std::to_string(i)); + if (i == 10) { salary_input_ /= 10; return true; } + if (i == 11) { salary_input_ = calculator_initial_; return true; } + if (i == 12) { salary_input_ = 0; return true; } + if (i == 13) return accept_calculator(); + if (i == 14) { page_ = calculator_return_; calculator_backdrop_.reset(); editing_salary_ = false; calculator_bonus_index_ = -1; return true; } + } + for (int i = 0; i < 8; ++i) { + const int preset_x = 10 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i + 15) * 2); + const int preset_y = 10 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i + 15)); + if (x < preset_x || x >= preset_x + 53 || y < preset_y || y >= preset_y + 14) continue; + if(calculator_presets_[size_t(i)]==UINT32_MAX)return false; + salary_input_ = calculator_presets_[size_t(i)]; + return true; + } + return false; + } + if (page_ == Page::player_offer) { + const auto p = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& v) { return v.row == state_.selected_row; }); + if (p == state_.players.end()) return false; + const int top = p->row < 13 ? 130 : 22; + if (y >= top + 76 && y <= top + 85 && x < 60) { page_ = Page::roster; return true; } + if (y >= top + 76 && y <= top + 85 && x >= 261 && x <= 312) { + team_premium_mode_ = false; page_ = Page::team_premiums; return true; + } + if (y >= top + 76 && y <= top + 85 && x >= 90 && x <= 170 && state_.demands) { + if (!salary_offer_set_ && proposed_bonuses_ == p->team_premiums) { page_ = Page::roster; return true; } + ContractRequest request; request.kind = salary_offer_set_ ? ContractActionKind::submit_offer : ContractActionKind::submit_bonuses; + request.row = state_.quote_row; request.quote_id = state_.quote_id; request.player_id = p->player_id; + if (salary_offer_set_) { request.term_column = offer_term_; request.demand = (*state_.demands)[offer_term_]; request.monthly_salary = offer_salary_; } + request.proposed_bonuses = proposed_bonuses_; + if (request.demand == std::numeric_limits::max()) return false; + emit(request); return true; + } + if (y >= top + 40 && y < top + 58 && x >= 70 && x < 310 && !p->offer_blocked && !(p->board_flags & 0x60)) { + selected_term_ = uint8_t(std::clamp((x - 70) / 60, 0, 3)); + const uint32_t initial = state_.demands && state_.quote_row == state_.selected_row ? (*state_.demands)[selected_term_] : 0; + open_calculator(-1, page_, initial); return true; + } + if (y >= top + 58 && y < top + 74 && x >= 70 && x < 310 && state_.mode_three) { + if(!p->insurance_available) { + const uint32_t address=p->board_flags&0x20?::bmh::layout::CareerSession_Reject_TextPointer:p->board_flags&0x40?::bmh::layout::CareerSession_Reject_TextPointer2:p->insurance?::bmh::layout::CareerSession_Reject_TextPointer3: ::bmh::layout::CareerSession_Reject_TextPointer4; + result_backdrop_=render();state_.feedback=original_to_utf8(texts_[(address-::bmh::layout::TextPointerTable)/4]);result_return_=page_;page_=Page::result;return true; + } + insurance_term_ = uint8_t(std::clamp((x - 70) / 60, 0, 3)); + open_calculator(-2, page_, 12); return true; + } + return false; + } + if (page_ == Page::team_premiums) { + const auto selected_player = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& player) { return player.row == state_.selected_row; }); + const int top = team_premium_mode_ || selected_player == state_.players.end() || selected_player->row >= 13 ? 22 : 130; + if (y >= top + 76 && y <= top + 85 && x < 60) { page_ = Page::roster; return true; } + if (y >= top + 76 && y <= top + 85 && x >= 261 && x <= 312 && !team_premium_mode_) { page_ = Page::player_offer; return true; } + if (y >= top + 76 && y <= top + 85 && x >= 90 && x <= 170) { + ContractRequest req; + req.proposed_bonuses = proposed_bonuses_; + if (team_premium_mode_) { req.kind = ContractActionKind::submit_bonuses; req.row = -1; req.player_id = -1; } + else if (salary_offer_set_ && state_.demands && selected_player != state_.players.end()) { + req.kind = ContractActionKind::submit_offer; req.row = selected_player->row; req.player_id = selected_player->player_id; + req.quote_id = state_.quote_id; req.term_column = offer_term_; req.demand = (*state_.demands)[offer_term_]; req.monthly_salary = offer_salary_; + } else if (selected_player != state_.players.end()) { + req.kind = ContractActionKind::submit_bonuses; req.row = selected_player->row; req.player_id = selected_player->player_id; req.quote_id = state_.quote_id; + } else return false; + if (!salary_offer_set_ && req.proposed_bonuses == (team_premium_mode_ ? state_.team_premiums : selected_player->team_premiums)) { page_ = Page::roster; return true; } + emit(req); return true; + } + for (int index = 0; index < 7; ++index) { + if (y >= top + 25 + index * 7 && y < top + 32 + index * 7 && x >= 5 && x <= 300 && (team_premium_mode_ || selected_player != state_.players.end())) { + const uint32_t initial = proposed_bonuses_[size_t(index)]; + open_calculator(index, Page::team_premiums, initial); return true; + } + } + return false; + } + if (y >= 215 && y <= 224) { + const int which = x < 60 ? 0 : x < 120 ? 1 : x < 180 ? 2 : x < 250 ? 3 : -1; + if (which < 0 || (!state_.mode_three && which==3)) return false; + tab_ = uint8_t(which); + page_ = which == 3 ? Page::team_premiums : Page::roster; + if (which == 3) { + team_premium_mode_ = true; proposed_bonuses_ = state_.team_premiums; + } + return true; + } + if(page_==Page::roster && x>=0 && x<61) { + int baseline=36; + for(size_t i=0;i=baseline-7 && y=0&&y>=baseline-7&&y= '0' && key[0] <= '9') { + const uint32_t digit = uint32_t(key[0] - '0'); + const uint32_t max = calculator_bonus_index_ >= 0 ? (calculator_bonus_index_ < 3 ? 20u : 1000u) : calculator_bonus_index_ == -2 ? 60u : 200000u; + if (salary_input_ <= (max - digit) / 10) salary_input_ = salary_input_ * 10 + digit; + return true; + } + return false; +} + +void ContractsScreen::acknowledge_quote(const ContractsState& state) { + if (!pending_ || pending_->kind != ContractActionKind::request_demands || state.revision <= state_.revision || + state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club || !state.demands || + state.quote_row != pending_->row || state.quote_id == 0) + throw FormatError("contracts: quote acknowledgement does not match request"); + const auto old = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == pending_->row; }); + const auto fresh = std::find_if(state.players.begin(), state.players.end(), [&](const auto& p) { return p.row == pending_->row; }); + if (old == state_.players.end() || fresh == state.players.end() || old->player_id != pending_->player_id || fresh->player_id != old->player_id) + throw FormatError("contracts: quote player identity changed"); + const uint64_t request_id_base = state_.request_id_base; + proposed_bonuses_ = fresh->team_premiums; + state_ = state; + state_.selected_row = pending_->row; + state_.request_id_base = request_id_base; + salary_input_ = 0; + selected_term_ = 0; + salary_offer_set_ = false; + offer_salary_ = 0; + offer_term_ = 0; + editing_salary_ = false; + pending_.reset(); + page_ = Page::player_offer; +} + +void ContractsScreen::acknowledge_offer(const ContractsState& state) { + if (!pending_ || (pending_->kind != ContractActionKind::submit_offer && pending_->kind != ContractActionKind::submit_bonuses) || state.revision <= state_.revision || + state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club) + throw FormatError("contracts: offer acknowledgement does not match request"); + result_backdrop_ = render(); + const uint64_t request_id_base = state_.request_id_base; + state_ = state; + state_.request_id_base = request_id_base; + state_.selected_row = pending_->row; + state_.demands.reset(); state_.quote_id = 0; state_.quote_row = -1; + editing_salary_ = false; + pending_.reset(); + result_return_=Page::roster;page_ = Page::result; +} + +void ContractsScreen::acknowledge_bonus_offer(const ContractsState& state) { + if (!pending_ || pending_->kind != ContractActionKind::submit_bonuses || + state.revision <= state_.revision || state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club) + throw FormatError("contracts: bonus acknowledgement does not match request"); + result_backdrop_ = render(); + const uint64_t base = state_.request_id_base; + state_ = state; state_.request_id_base = base; pending_.reset(); result_return_=Page::roster;page_ = state.feedback.empty() ? Page::roster : Page::result; +} + +void ContractsScreen::acknowledge_insurance(const ContractsState& state) { + if (!pending_ || pending_->kind != ContractActionKind::insure_player || state.revision <= state_.revision || + state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club || + state.quote_id != state_.quote_id || state.quote_row != pending_->row || !state.demands) + throw FormatError("contracts: insurance acknowledgement does not match request"); + const auto before = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == pending_->row; }); + const auto after = std::find_if(state.players.begin(), state.players.end(), [&](const auto& p) { return p.row == pending_->row; }); + if (before == state_.players.end() || after == state.players.end() || before->player_id != pending_->player_id || after->player_id != before->player_id) + throw FormatError("contracts: insurance player identity changed"); + const auto base = state_.request_id_base; + state_ = state; state_.request_id_base = base; pending_.reset(); page_ = Page::player_offer; + calculator_backdrop_.reset(); editing_salary_ = false; +} + +void ContractsScreen::reject(std::string feedback) { + if (!pending_) throw FormatError("contracts: no action to reject"); + const auto kind = pending_->kind; + pending_.reset(); state_.feedback = std::move(feedback); editing_salary_ = false; + if (kind == ContractActionKind::insure_player) page_ = Page::player_offer; +} + +std::string ContractsScreen::state_json() const { + auto out = contracts_state_json(state_); + out.pop_back(); + out += ",\"monthly_salary_input\":" + std::to_string(salary_input_) + + ",\"selected_term\":" + std::to_string(unsigned(selected_term_)) + + ",\"editing_salary\":" + std::string(editing_salary_ ? "true" : "false") + + ",\"page\":" + std::to_string(unsigned(page_)) + "}"; + return out; +} + +} // namespace bmh::ui diff --git a/src/ui/contracts.hpp b/src/ui/contracts.hpp new file mode 100644 index 0000000..ee87de4 --- /dev/null +++ b/src/ui/contracts.hpp @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "ui/sprite_font.hpp" +#include "ui/lineup.hpp" + +namespace bmh { struct GameState; } + +namespace bmh::ui { + +struct ContractPlayer { + int row = -1; + int player_id = -1; + std::string name; + int age = 0; + int position = 0; + uint8_t remaining_months = 0; + uint32_t current_monthly_salary = 0; + uint8_t insurance = 0; + bool insurance_available = false; + bool offer_blocked = false; + uint16_t insurance_fee = 0; + std::array team_premiums{}; + std::array attributes{}; + LineupPlayer source; + uint8_t board_flags = 0; +}; + +struct ContractsState { + bool gradient_text = true, decorated_background = true, mode_three = true; + uint32_t currency_numerator = 1, currency_denominator = 1; + int manager_slot = -1; + int runtime_club = -1; + uint64_t revision = 0; + uint64_t request_id_base = 0; + std::string club_name; + std::string manager_name; + int manager_portrait = 0; + int badge_sprite = 0; + std::vector players; + std::array team_premiums{}; + int selected_row = -1; + std::optional> demands; + uint64_t quote_id = 0; + int quote_row = -1; + std::string feedback; +}; + +enum class ContractActionKind : uint8_t { request_demands, submit_offer, submit_bonuses, insure_player }; +struct ContractRequest { + ContractActionKind kind = ContractActionKind::request_demands; + uint64_t request_id = 0; + uint64_t revision = 0; + int manager_slot = -1; + int runtime_club = -1; + int row = -1; + int player_id = -1; + uint64_t quote_id = 0; + uint8_t term_column = 0; // 0..3 represents one to four years + uint32_t demand = 0; + uint32_t monthly_salary = 0; + std::array proposed_bonuses{}; + uint8_t insurance_months = 0; + friend bool operator==(const ContractRequest&, const ContractRequest&) = default; +}; + +struct ContractActionResult { + bool success = false; + bool accepted = false; + uint64_t quote_id = 0; + std::array demands{}; + std::string feedback; +}; + +ContractsState contracts_from_game(const GameState&, int manager_slot, uint64_t revision); +std::string contract_request_json(const ContractRequest&); +std::string contracts_state_json(const ContractsState&); + +class ContractsScreen { +public: + ContractsScreen(const std::filesystem::path&, ContractsState); + Image render() const; + bool click(int x, int y, bool right = false); + bool process_timer_expired(int pointer_x, int pointer_y); + bool key(std::string_view); + bool move(int x, int y); + int take_player_info_request() { const int row=player_info_row_; player_info_row_=-1; return row; } + bool text(std::string_view); + void acknowledge_quote(const ContractsState&); + void acknowledge_offer(const ContractsState&); + void acknowledge_bonus_offer(const ContractsState&); + void acknowledge_insurance(const ContractsState&); + void reject(std::string feedback); + bool close_requested() const { return close_requested_; } + bool result_page_open() const { return page_ == Page::result; } + const ContractsState& state() const { return state_; } + const ContractRequest* pending() const { return pending_ ? &*pending_ : nullptr; } + std::string state_json() const; +private: + enum class Page : uint8_t { roster, player_offer, team_premiums, calculator, insurance, result }; + ContractsState state_; + LeImage exe_; + Font font_; + Font large_font_; + SpriteFont sprite_font_; + TextDb texts_; + Image atlas_, flags_; + int hovered_row_ = -1; + int player_info_row_ = -1; + Image render_roster() const; + Image background_; + Image widgets_; + Image calculator_; + Image faces_; + Image badge_atlas_; + std::optional pending_; + std::optional result_backdrop_; + std::optional calculator_backdrop_; + uint64_t next_request_id_ = 1; + uint32_t salary_input_ = 0; + uint32_t calculator_initial_ = 0; + uint32_t offer_salary_ = 0; + std::array calculator_presets_{}; + bool salary_set_ = false; + bool team_premium_mode_ = false; + uint8_t selected_term_ = 0; + uint8_t offer_term_ = 0; + uint8_t insurance_term_ = 0; + bool salary_offer_set_ = false; + bool editing_salary_ = false; + Page page_ = Page::roster; + Page result_return_ = Page::roster; + uint8_t tab_ = 2; + Page calculator_return_ = Page::player_offer; + int calculator_bonus_index_ = -1; + std::array proposed_bonuses_{}; + uint8_t insurance_months_ = 0; + bool close_requested_ = false; + uint32_t calculator_max_ = 200000; + void open_calculator(int target, Page return_page, uint32_t initial); + void text(Image&, int x, int baseline, std::string_view utf8, uint8_t color, int right = 314) const; + void emit(ContractRequest); +}; + +} // namespace bmh::ui diff --git a/src/ui/contracts_tests.cpp b/src/ui/contracts_tests.cpp new file mode 100644 index 0000000..7455e0e --- /dev/null +++ b/src/ui/contracts_tests.cpp @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "ui/contracts.hpp" +#include "ui/source_notice_test_helpers.hpp" + +#include + +using namespace bmh::ui; + +namespace { +void check(bool value, const char* message) { + if (!value) throw std::runtime_error(message); +} +} + +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: ui_contracts_tests DATA"); + ContractsState state; + state.manager_slot = 0; + state.runtime_club = 12; + state.revision = 4; + state.request_id_base = uint64_t(5) << 32; + state.club_name = "UNIT FOOTBALL CLUB"; + state.players.push_back({0, 150, "TORWART", 25, 0, 8, 180000}); + state.players.push_back({1, 151, "STÜRMER", 21, 3, 14, 90000}); + auto blocked_state = state; + blocked_state.players[0].offer_blocked = true; + ContractsScreen blocked(argv[1], blocked_state); + check(blocked.click(20,33,true) && blocked.pending(), "offended players still display their salary demands"); + auto blocked_quote=blocked_state;blocked_quote.revision=5;blocked_quote.quote_id=3;blocked_quote.quote_row=0;blocked_quote.selected_row=0; + blocked_quote.demands=std::array{180000,190000,200000,210000};blocked.acknowledge_quote(blocked_quote); + check(!blocked.click(160,182), "Original grayed demands cannot open a salary calculator"); + ContractsScreen screen(argv[1], state); + const auto pixels = screen.render().pixels; + check(pixels.size() == 320 * 240 && screen.render().pixels == pixels, + "contract roster renders deterministically in the fixed 320x240 view"); + check(screen.state_json().find("UNIT FOOTBALL CLUB") != std::string::npos, + "owned projection retains UTF-8 club identity"); + check(screen.click(20, 33, true) && screen.pending() && + screen.pending()->kind == ContractActionKind::request_demands && + screen.pending()->row == 0 && screen.pending()->player_id == 150 && + screen.pending()->request_id == (uint64_t(5) << 32) + 1, + "right-clicking the selected row requests its term offers"); + auto bad = state; + bad.revision = 5; + bad.quote_row = 0; + bad.quote_id = 8; + bad.demands = std::array{180000,190000,200000,210000}; + ++bad.players[0].player_id; + bool rejected = false; + try { screen.acknowledge_quote(bad); } catch (const std::exception&) { rejected = true; } + check(rejected && screen.pending(), "stale player identity cannot consume a quote request"); + auto quote = state; + quote.revision = 5; + quote.selected_row = 0; + quote.quote_row = 0; + quote.quote_id = 8; + quote.demands = std::array{180000,190000,200000,210000}; + screen.acknowledge_quote(quote); + check(!screen.pending() && screen.state().demands == quote.demands && + screen.state_json().find("190000") != std::string::npos, + "matching four-term quote is shown after ACK"); + { + auto talk = screen; + check(talk.click(160,182) && talk.click(76,132) && talk.text("17000") && talk.click(94,132), + "a salary can be accepted locally before an offer is submitted"); + check(talk.process_timer_expired(100,100) && !talk.pending() && !talk.close_requested() && + talk.state_json().find("\"page\":0") != std::string::npos, + "41232 event8 cancels a locally accepted salary without submitting it"); + check(talk.process_timer_expired(100,100) && talk.close_requested(), + "the next outer poll returns the roster to the desk"); + auto name_column = screen; + check(name_column.process_timer_expired(20,33) && !name_column.pending() && + name_column.process_timer_expired(20,33) && name_column.pending() && + name_column.pending()->kind == ContractActionKind::request_demands && + name_column.pending()->player_id == 150, + "parent handback retains the real name-column pointer rather than inventing a desk close"); + auto premium = screen; + check(premium.click(285,210) && premium.click(30,157) && premium.click(76,132) && + premium.text("3") && premium.click(94,132), "a premium draft is accepted locally"); + const auto proposed_image = premium.render().pixels; + check(premium.click(30,157) && premium.click(76,132) && premium.text("17"), + "a second unconfirmed premium draft is entered"); + check(premium.process_timer_expired(100,100) && !premium.pending() && + premium.render().pixels == proposed_image, + "40c65 sentinel retains the earlier local premium and discards only unconfirmed digits"); + check(premium.process_timer_expired(100,100) && !premium.pending() && + premium.state_json().find("\"page\":0") != std::string::npos, + "premium parent deadline discards local rates without an offer command"); + auto team = state; team.mode_three = true; + ContractsScreen team_premiums(argv[1], team); + check(team_premiums.click(210,219) && team_premiums.process_timer_expired(100,100) && + !team_premiums.pending() && team_premiums.state_json().find("\"page\":0") != std::string::npos, + "team premium deadline does not commit a squad-wide bonus request"); + auto insurance_state = state; + insurance_state.mode_three = true; insurance_state.players[0].insurance_available = true; + ContractsScreen insurance(argv[1], insurance_state); + check(insurance.click(20,33,true), "eligible mode3 player requests a quote"); + auto insurance_quote = quote; + insurance_quote.mode_three = true; insurance_quote.players[0].insurance_available = true; + insurance.acknowledge_quote(insurance_quote); + check(insurance.click(220,197) && insurance.click(76,132) && insurance.text("24"), + "unconfirmed coverage duration is entered"); + check(insurance.process_timer_expired(100,100) && !insurance.pending() && + !insurance.state().players[0].insurance && insurance.state_json().find("\"page\":1") != std::string::npos, + "calculator sentinel discards coverage duration without buying an insurance policy"); + } + check(screen.click(160, 182) && screen.state_json().find("\"page\":3") != std::string::npos, + "clicking a term demand opens the original calculator overlay"); + check(screen.click(111, 132) && screen.state_json().find("\"page\":1") != std::string::npos, + "N cancels the calculator draft without submitting an offer"); + check(screen.click(160, 182), "the selected term can reopen its calculator"); + check(screen.click(76, 132) && screen.text("1234") && screen.click(41, 132) && + screen.state_json().find("\"monthly_salary_input\":123") != std::string::npos, + "C, digit entry, and D edit the calculator draft locally"); + check(screen.click(58, 132) && + screen.state_json().find("\"monthly_salary_input\":190000") != std::string::npos, + "R restores the original demand value"); + check(screen.click(94, 132) && screen.state_json().find("\"page\":1") != std::string::npos, + "original J calculator key accepts the salary draft"); + check(screen.click(125, 210) && screen.pending() && + screen.pending()->kind == ContractActionKind::submit_offer && + screen.pending()->term_column == 1 && screen.pending()->demand == 190000 && + screen.pending()->monthly_salary == 190000 && screen.pending()->quote_id == 8, + "ANGEBOT MACHEN submits the mouse-selected quoted term and amount"); + auto offer_ack = quote; + offer_ack.revision = 6; + offer_ack.demands.reset(); + offer_ack.quote_id = 0; + offer_ack.quote_row = -1; + offer_ack.feedback = "Der Spieler hat angenommen."; + screen.acknowledge_offer(offer_ack); + bmh::ui::test::expect_notice_symbols(screen.render(),bmh::load_vga(std::filesystem::path(argv[1])/"KB/0.VGA")); + check(!screen.pending() && screen.state().feedback == "Der Spieler hat angenommen.", + "accepted offer ACK returns the view to the live roster"); + const auto notice = screen.state_json(); + check(!screen.process_timer_expired(100,100) && screen.state_json() == notice, + "result notice keeps its physical KLICK rather than consuming the process deadline"); + check(screen.click(150, 170) && screen.state_json().find("\"page\":0") != std::string::npos, + "KLICK closes the source-style manager response overlay back to the roster"); + check(screen.click(20,33,true), "another individual negotiation opens via right click"); + quote.revision=7;quote.quote_id=9;screen.acknowledge_quote(quote); + check(screen.click(285, 210) && screen.state_json().find("\"page\":2") != std::string::npos, + "PRÄMIEN opens the original individual bonus view"); + check(screen.click(30, 160) && screen.state_json().find("\"page\":3") != std::string::npos, + "clicking a premium opens the bounded calculator"); + check(screen.click(76, 132) && screen.text("1") && screen.click(41, 132) && + screen.state_json().find("\"monthly_salary_input\":0") != std::string::npos, + "premium calculator C and D keep edits local"); + check(screen.click(58, 132) && screen.text("3"), "R restores the initial premium before a new value"); + check(screen.click(94, 132), "J accepts the local premium draft"); + check(screen.click(125, 210) && screen.pending() && + screen.pending()->kind == ContractActionKind::submit_bonuses && + screen.pending()->row == 0 && screen.pending()->player_id == 150 && + screen.pending()->proposed_bonuses[0] == 3, + "individual premium edit emits a typed player request"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "contracts UI test: %s\n", e.what()); + return 1; + } +} diff --git a/src/ui/cup_draw.cpp b/src/ui/cup_draw.cpp new file mode 100644 index 0000000..c306f13 --- /dev/null +++ b/src/ui/cup_draw.cpp @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/cup_draw.hpp" + +#include +#include +#include +#include +#include + +#include "game/cup.hpp" +#include "game/rating.hpp" +#include "game/messages.hpp" +#include "game/match.hpp" +#include "game/schedule.hpp" +#include "game/state.hpp" +#include "game/season.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +constexpr std::array kTierSourceX{0,16,32,32,24}; +constexpr int kCupOnlyTeams=30; + +bool valid_rect(const Image& dst,const Image& src,int sx,int sy,int x,int y,int w,int h) { + return w>0&&h>0&&sx>=0&&sy>=0&&x>=0&&y>=0&&sx+w<=src.width&&sy+h<=src.height&& + x+w<=dst.width&&y+h<=dst.height; +} +void copy(Image& dst,const Image& src,int sx,int sy,int x,int y,int w,int h) { + // FormatError2 passes ff as the VGA plane bitmask. The copy is opaque and an + // out-of-bounds rectangle is rejected in full by SourceMaskCopy. + if(!valid_rect(dst,src,sx,sy,x,y,w,h))return; + for(int yy=0;yy=0&&xx=0&&y-1=0&&yy=0&&x-1=0&&xx=0&&y+38=0&&yy=0&&x+38=5?league-5+1:0;} + if(t-kCupOnlyTeams>=0)return (t-kCupOnlyTeams)/7-5+10; + return 0; +} +int league_for_team(int id) { return id>0x164?0:team_league(id); } +uint8_t manager_color(const GameState& game,int id,uint8_t base) { + const int active=game.memory.has(::bmh::layout::ActiveManager)?game.memory.u8(::bmh::layout::ActiveManager):-1; + const int count=game.memory.has(::bmh::layout::ManagerCount)?game.memory.u8(::bmh::layout::ManagerCount):int(game.manager_teams.size()); + const bool active_context=game.memory.has(::bmh::layout::DeskPosition)&&game.memory.u8(::bmh::layout::DeskPosition)(4,game.manager_teams.size());++slot) { + const size_t rec=slot*0xb0c+0xa8; + if(rec>=game.manager_records.size()||!game.manager_records[rec])continue; + if(game.manager_teams[slot]==id)return int(slot)==active&&active_context?0x7a:0x75; + } + if(game.memory.has(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)&&game.memory.u16(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)==id)return 0xf7; + return base; +} +std::string source_field(int value,int width) { + std::string result=std::to_string(value); + if(int(result.size())=texts.strings.size())throw FormatError("cup draw: missing Source TEXTD entry"); + return original_to_utf8(texts[i]); +} +} + +CupDrawProjection cup_draw_from_game(const GameState& game,const SeasonCupDrawEvent& event, + const LeImage& exe,const TextDb& texts) { + if(event.entry_address64||event.participants.size()6) + throw FormatError("cup draw: invalid Source event"); + const uint32_t entry=event.entry_address; + const uint8_t flags=event.flags?event.flags:game.memory.u8(entry+0x14); + const uint8_t qualifier=game.memory.u8(entry+0x1c); + int round_index=((flags&4)?event.round:0)+1+qualifier; + if(qualifier==1&&event.round==0)--round_index; + if(round_index<0||round_index>31)throw FormatError("cup draw: invalid Source round text index"); + CupDrawProjection out; + out.phase=event.phase;out.entry_address=event.entry_address;out.competition=event.competition; + out.round=event.round;out.offset=event.offset;out.count=event.count; + out.flags=flags;out.group_stage=event.group_stage;out.group_index=event.group_index;out.group_count=event.group_count; + out.heading=text_at(texts,size_t((::bmh::layout::CupDraw_FormatError_ExecutableField4-::bmh::layout::TextPointerTable)/4)+size_t(round_index)); + out.footer=text_at(texts,size_t((::bmh::layout::CupDraw_FormatError_ExecutableField6-::bmh::layout::TextPointerTable)/4)+size_t(event.competition)); + if(out.group_stage) { + out.group_round_suffix=text_at(texts,size_t((::bmh::layout::CupDraw_FormatError_TextPointer6-::bmh::layout::TextPointerTable)/4)); + const size_t round_digit_index=size_t((::bmh::layout::Calendar_Information_TextPointer2-::bmh::layout::TextPointerTable)/4); + const size_t group_digit_index=size_t((::bmh::layout::CupDraw_FormatError_ExecutableField5-::bmh::layout::TextPointerTable)/4); + std::string round_digit=text_at(texts,round_digit_index); + std::string group_digit=text_at(texts,group_digit_index); + if(round_digit.size()>16)round_digit[16]=char('0'+event.group_index+1); + if(group_digit.size()>25) + group_digit[25]=char(event.phase==SeasonCupDrawPhase::draw?'0'+event.group_index+1: + (event.group_index==0?'1':'0'+event.group_index)); + out.group_caption=group_digit; + const size_t heading_index=size_t((::bmh::layout::CupDraw_FormatError_ExecutableField4-::bmh::layout::TextPointerTable)/4)+size_t(round_index); + const size_t footer_index=size_t((::bmh::layout::CupDraw_FormatError_ExecutableField6-::bmh::layout::TextPointerTable)/4)+size_t(event.competition); + if(heading_index==round_digit_index)out.heading=round_digit; + else if(heading_index==group_digit_index)out.heading=group_digit; + if(footer_index==round_digit_index)out.footer=round_digit; + else if(footer_index==group_digit_index)out.footer=group_digit; + const auto& form=texts[72]; + for(size_t i=0;i=4&&event.competition<=7)|| + (game.memory.has(::bmh::layout::CompetitionSelection)&&(game.memory.u32(::bmh::layout::CompetitionSelection)&1)); + if(game.memory.has(::bmh::layout::CupDraw_FormatError_RuntimeField)) { + const int speed=game.memory.u8(::bmh::layout::CupDraw_FormatError_RuntimeField); + out.source_option_delay_ms=speed>=0&&speed<=5?(speed/2)*20:speed*20; + } + out.clubs.reserve(event.count); + for(size_t i=0;i=game.club_heap_78.size())throw FormatError("cup draw: missing Source badge selector"); + const uint16_t selector=uint16_t(game.club_heap_78[size_t(id)*2]|uint16_t(game.club_heap_78[size_t(id)*2+1])<<8); + const uint8_t league=uint8_t(std::clamp(league_for_team(id),0,255)); + const uint8_t base=event.group_stage?0x6a:(region_for_team(id)?0x67:0x5f); + const uint8_t color=manager_color(game,id,base); + const uint8_t reveal_color=color==base?0:0x27; + std::string context; + if(event.group_stage&&event.phase==SeasonCupDrawPhase::overview) { + const bool human_national=game.manager_of(id)>=0|| + (game.memory.has(::bmh::layout::CupDraw_FormatError_RuntimeField2)&&game.memory.has(::bmh::layout::CupDraw_FormatError_RuntimeField3)&&game.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField2)==0x165&&game.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)==id); + if(id>=168&&!human_national) { + if(size_t(id-168)>=game.foreign_strength.size())throw FormatError("cup draw: missing Source foreign-strength byte"); + const uint8_t strength=game.foreign_strength[size_t(id-168)]; + const unsigned band=strength>>5; + context=text_at(texts,size_t((::bmh::layout::CupDraw_FormatError_TextPointer4-::bmh::layout::TextPointerTable)/4)+band)+original_to_utf8(exe.cstring(::bmh::layout::CupDraw_FormatError_TextPointer)); + for(unsigned bit=0;bit<3;++bit) + context+=original_to_utf8(exe.cstring(::bmh::layout::CupDraw_FormatError_ExecutableField3+(((strength>>(3-bit))&1u)*2u))); + context+=original_to_utf8(exe.cstring(::bmh::layout::CupDraw_FormatError_ExecutableField)); + } else { + std::array values{}; + if(id>=168&&id!=kNoTeam) { + const auto snapshot=std::find_if(event.group_average_snapshots.begin(),event.group_average_snapshots.end(), + [&](const auto& v){return v.runtime_id==id;}); + if(snapshot==event.group_average_snapshots.end()) + throw FormatError("cup draw: missing live TeamRating group-average snapshot"); + values=snapshot->values; + } else { + values={team_average(game,id,0x0f1).value,team_average(game,id,0x0f2).value, + team_average(game,id,0x0f4).value,team_average(game,id,0x0f8).value, + team_average(game,id,0x0ff).value}; + } + context=original_to_utf8(exe.cstring(::bmh::layout::CupDraw_FormatError_ExecutableField2)); + for(size_t i=0;i1) + for(size_t i=0;i badges; + struct Op { bool copy; std::array rect; int token; }; + std::vector ops; + std::vector revealed; + size_t op_index=0,total_revealed=0; + Impl(const std::filesystem::path& d,CupDrawProjection projection) + :p(std::move(projection)),data(d),exe(load_le(asset_path(d,"BMH.exe"))), + panel(load_vga(asset_path(d/"KB","67.VGA"))),background(load_vga(asset_path(d/"KB","56.VGA"))), + widgets(load_vga(asset_path(d/"KB","0.VGA"))),tier(load_vga(asset_path(d/"KB","1.VGA"))), + regions(load_vga(asset_path(d/"KB","24.VGA"))), + animation(load_vga(asset_path(d/"KB","74.VGA"))),texts(load_textd(asset_path(d,"TEXTD.BLK"))), + sprite(d),font(load_font(asset_path(d/"F","BMH3.FNT"))) { + if(panel.width<272||panel.height<203||background.width<318||background.height<207|| + p.count>64||p.clubs.size()=0x5a&&id<=0x89)||(id>=0xa8&&id<=0x164)||id==0xfff)){ + const int atlas=sel>>3;if(!badges.contains(atlas))badges.emplace(atlas,load_vga(asset_path(data/"W",std::to_string(atlas)+".VGA"))); + } + } + } + Image make_base() const { + Image out=p.decorated_background?load_vga(asset_path(data/"KB","129.VGA")):Image(320,240,0); + if(!p.decorated_background){fill(out,0,4,320,13,0x44);fill(out,1,5,318,11,0x39);fill(out,0,228,320,10,0x44);fill(out,1,229,318,8,0x39);} + return out; + } + void draw_header(Image& out,const std::string& heading,const std::string& footer) const { + const int x=172+(282-172)/2-sprite.text_width(heading)/2; + sprite.draw(out,x,13,heading,5);sprite.draw(out,5,235,footer,5); + } + void draw_gradient_text(Image& out,int x,int baseline,const std::string& name,uint8_t color) const { + const int top=baseline-font.baseline,width=font.text_width(name); + int ramp=0;while(ramp<32&&exe.u8(::bmh::layout::Advertising_Text_RuntimeField2Unsigned+uint32_t(ramp))!=color)++ramp; + if(!p.gradient_text||ramp==32){font.draw(out,x,top,name,color);return;} + Image mask(std::max(1,width),font.height,0);font.draw(mask,0,0,name,1); + for(int y=0;y=0&&x+xx=0&&top+y=0x5a&&id<=0x89)||(id>=0xa8&&id<=0x164)||id==0xfff) + copy(out,widgets,8,0,x,y,38,38); + else { + const int atlas=selector>>3;copy(out,badges.at(atlas),(selector&7)*38,0,x,y,38,38); + } + } + void group_marker(Image& out,const CupDrawClub& c,int x,int y) const { + if(c.league_tier<5) { + const int source_x=exe.u8(::bmh::layout::CupDraw_GroupMarker_RuntimeField+c.league_tier); + // Copy -> UsesForTheseSprites skips the atlas's transparent color DesktopRuntimeField. + copy_key0(out,tier,source_x,0x26,x,y,16,5); + } else { + const int region=c.country; + const int sx=(region%12)*8+region%12,sy=(region/12)*6; + copy(out,regions,sx,sy,x,y,9,6); + } + } + int club_x(int n) const {return p.group_stage?38:((n&1)?168:38);} + int club_y(int n) const {return p.group_stage?193+n*7:193+(n/2)*7;} + void draw_revealed() { + // Source restores only the bottom strip from the pre-reveal snapshot. + copy(drawing,bottom,29,182,29,182,254,34); + for(size_t j=0;j=ops.size()){ + if(script==0){script=1;begin_script();return true;} + const size_t window=p.group_stage?4:8,drop=p.group_stage?1:2; + if(revealed.size()>=window)revealed.erase(revealed.begin(),revealed.begin()+drop); + revealed.push_back(size_t(club));++total_revealed;draw_revealed();present_frame(true,true);++club;script=0;script_started=false; + if(size_t(club)>=p.count)complete=true;else poll=true; + return true; + } + const auto op=ops[op_index++]; + if(op.copy){apply_script_copy(op.rect[0],op.rect[1],op.rect[2],op.rect[3],op.rect[4],op.rect[5]);return true;} + const bool visible=op.token<=100; + present_frame(visible,false);option_delay=p.source_option_delay_ms;wait=visible?op.token*20:(op.token-100)*20;held=true;return true; + } + void draw_overview() { + screen=make_base(); + if(p.group_stage){draw_group_overview();return;} + const int count=int(p.count),firstrow=(64-count)/2; + const int baseline=firstrow*3+26; + // CupGroupOverviewEffects(param3=300) keeps the compact list. Its LoadGameEndTaxAnimationAssets backing + // rectangle follows the rows, even when fewer than 64 clubs remain: + // y=baseline-7 .. baseline+6*(count/2)-5, sampling KB56 at y-19. + if(p.original_table_panel&&count!=0){ + const int top=baseline-7,bottom=baseline+6*(count/2)-5; + copy(screen,background,0,top-19,1,top+1,318,bottom-top-1); + for(int x=0;x<320;++x)screen.at(x,top)=0x46; + for(int y=top;y<=bottom;++y)screen.at(0,y)=0x46; + for(int x=0;x<320;++x)screen.at(x,bottom)=0x40; + for(int y=top;y<=bottom;++y)screen.at(319,y)=0x40; + } + draw_header(screen,p.footer,p.heading); + for(int pair=0;pair2) { + const std::string round=source_field(p.round+1,1)+p.group_round_suffix; + draw_gradient_text(screen,2,22,utf8_to_original(round),0x5f); + } + const int fixture_baseline=count==2?0x68:0x27; + const int fixture_top=fixture_baseline-8; + const int fixture_bottom=fixture_baseline+16*(count/2)-6; + if(p.original_table_panel&&count>0) { + copy(screen,background,1,fixture_top-19,1,fixture_top+1,318,fixture_bottom-fixture_top-1); + for(int x=0;x<320;++x){screen.at(x,fixture_top)=0x46;screen.at(x,fixture_bottom)=0x40;} + for(int y=fixture_top;y<=fixture_bottom;++y){screen.at(0,y)=0x46;screen.at(319,y)=0x40;} + } + const int rounds=int(p.group_fixtures.size()); + for(int i=0;iconst CupDrawClub& { + const auto it=std::find_if(p.clubs.begin(),p.clubs.end(),[&](const CupDrawClub& c){return c.runtime_id==id;}); + if(it==p.clubs.end())throw FormatError("cup draw: fixture references a club outside its owned group"); + return *it; + }; + const auto& home=find(pair[0]);const auto& away=find(pair[1]); + draw_gradient_text(screen,5,baseline,utf8_to_original(home.original_name),home.name_color); + draw_gradient_text(screen,132,baseline,utf8_to_original(away.original_name),away.name_color); + draw_gradient_text(screen,125,baseline,utf8_to_original(exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer)),0x68); + group_marker(screen,home,115,baseline-5); + group_marker(screen,away,242,baseline-5); + if(!home.source_context.empty())draw_gradient_text(screen,3,baseline+7,utf8_to_original(home.source_context),0x68); + if(!away.source_context.empty())draw_gradient_text(screen,133,baseline+7,utf8_to_original(away.source_context),0x68); + } + if(count>2) { + const int top=125,bottom=count*7+126; + if(p.original_table_panel) { + copy(screen,background,1,top-19,1,top+1,318,bottom-top-1); + for(int x=0;x<320;++x){screen.at(x,top)=0x46;screen.at(x,bottom)=0x40;} + for(int y=top;y<=bottom;++y){screen.at(0,y)=0x46;screen.at(319,y)=0x40;} + } + for(size_t i=0;ioriginal_name),r.name_color); + const std::string rank=source_field(r.rank,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer2); + const std::string games=source_field(r.games,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer4)+ + source_field(r.wins,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer5)+source_field(r.draws,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer5)+ + source_field(r.defeats,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer4); + std::string points=exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer6); + if(p.flags&0x80)points+=exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer7); + points+=source_field(r.points,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer8); + if(!(p.flags&0x80)) + points+=exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer9)+source_field(2*r.games-r.points,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer8); + std::string signed_diff; + if(r.goals_for-r.goals_against<0)signed_diff=exetext(::bmh::layout::Bank_OriginalToUtf8_ExecutableField5); + else if(r.goals_for-r.goals_against==0)signed_diff=exetext(::bmh::layout::Bank_OriginalToUtf8_ExecutableField7); + else signed_diff=exetext(::bmh::layout::Bank_OriginalToUtf8_ExecutableField6); + const std::string goals=source_field(r.goals_for,3)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer9)+ + source_field(r.goals_against,3)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer10)+ + signed_diff+source_field(std::abs(r.goals_for-r.goals_against),3)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer11); + draw_gradient_text(screen,1,baseline,utf8_to_original(rank),r.rank_color); + if(p.previous_rank_visible) { + const int old=r.previous_rank; + draw_gradient_text(screen,12,baseline,utf8_to_original("("+source_field(old,2)+exetext(::bmh::layout::CupDraw_DrawGroupOverview_TextPointer3)), + r.rank>(3*form))&7u; + const unsigned glyph=(bits&4u)?(bits&3u):(bits&3u)+4u; + if(!p.group_form_glyphs[glyph].empty()) + draw_gradient_text(screen,207-form*6,baseline, + utf8_to_original(p.group_form_glyphs[glyph]),0x6a); + } + draw_gradient_text(screen,206,baseline,utf8_to_original(points),0x6a); + draw_gradient_text(screen,255,baseline,utf8_to_original(goals),0x6a); + } + } + } + void draw_overview_club(Image& out,const CupDrawClub& c,int x,int baseline) const { + const std::string raw=utf8_to_original(c.original_name); + const int width=font.text_width(raw);if(x+width<=out.width&&baseline-font.baseline>=0) + draw_gradient_text(out,x,baseline,raw,c.name_color); + if(c.league_tier<5)copy_key0(out,tier,kTierSourceX[c.league_tier],38,x+(x==2?88:90),baseline-5,16,5); + } +}; + +CupDrawScreen::CupDrawScreen(const std::filesystem::path& d,CupDrawProjection p) + :impl_(std::make_shared(d,std::move(p))){} +bool CupDrawScreen::advance_step(){auto& s=*impl_;s.present=false;s.flush=false;s.poll=false;s.held=false;s.option_delay=0;s.wait=0; + if(s.complete)return false; + if(s.p.phase==SeasonCupDrawPhase::overview){s.complete=true;return false;} + if(s.initial<10){++s.initial;s.option_delay=s.p.source_option_delay_ms;s.poll=true; + if(s.initial==10&&s.skip){s.aborted=true;s.complete=true;}return true;} + if(s.aborted){s.complete=true;return false;} + if(s.skip){s.aborted=true;s.complete=true;return false;} + if(!s.initial_poll_done){s.initial_poll_done=true;s.poll=true;return true;} + if(s.club>=int(s.p.count)){s.complete=true;return false;} + if(!s.script_started){s.script_started=true;s.script=0;s.begin_script();} + return s.process_script(); +} +bool CupDrawScreen::present_needed()const{return impl_->present;} +bool CupDrawScreen::queue_flush_needed()const{return impl_->flush;} +int CupDrawScreen::option_delay_milliseconds()const{return impl_->option_delay;} +int CupDrawScreen::wait_milliseconds()const{return impl_->wait;} +bool CupDrawScreen::input_poll_needed()const{return impl_->poll;} +bool CupDrawScreen::held_mouse_check_needed()const{return impl_->held;} +bool CupDrawScreen::reveal_complete()const{return impl_->complete&&impl_->p.phase==SeasonCupDrawPhase::draw&&!impl_->aborted;} +bool CupDrawScreen::reveal_aborted()const{return impl_->aborted;} +size_t CupDrawScreen::revealed_count()const{return impl_->total_revealed;} +bool CupDrawScreen::source_input(uint8_t code){auto&s=*impl_;if(!s.poll)return false;if(code==2||code==8){ + if(s.initial<10)s.skip=true;else{s.aborted=true;s.complete=true;}return true;}return false;} +bool CupDrawScreen::source_held_mouse(uint8_t mask){auto&s=*impl_;if(!s.held)return false;if(mask&3){s.aborted=true;s.complete=true;s.club=int(s.p.count);s.poll=false;s.held=false;return true;}return false;} +Image CupDrawScreen::render()const{return impl_->screen;} +std::optional CupDrawScreen::hit_test_team(int x,int y)const { + const auto&s=*impl_;if(s.p.phase!=SeasonCupDrawPhase::overview)return{}; + if(s.p.group_stage) { + for(size_t i=0;i=baseline)continue; + const auto pair=s.p.group_fixtures[i]; + if(x>0&&x<127)return pair[0]; + if(x>125&&x<319)return pair[1]; + } + return{}; + } + const int first=(64-int(s.p.count))/2,base=first*3+26; + for(size_t pair=0;pair=b)continue; + if(x>0&&x<102)return s.p.clubs[pair*2].runtime_id; + if(x>103&&x<319)return s.p.clubs[pair*2+1].runtime_id; + } + return{}; +} +} // namespace bmh::ui diff --git a/src/ui/cup_draw.hpp b/src/ui/cup_draw.hpp new file mode 100644 index 0000000..5cd17d8 --- /dev/null +++ b/src/ui/cup_draw.hpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/season.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +struct CupDrawClub { + uint16_t runtime_id = 0; + uint16_t badge_selector = 0; + uint8_t league_tier = 0; + uint8_t country = 0; // TeamRegion region/affiliation; 0 for the first five leagues + uint8_t name_color = 0x5f; + uint8_t reveal_name_color = 0; + std::string original_name; + std::string source_context; +}; + +struct CupDrawGroupRow { + uint16_t runtime_id = 0; + int rank = 0; + int games = 0; + int wins = 0; + int draws = 0; + int defeats = 0; + int previous_rank = 0; + int goals_for = 0; + int goals_against = 0; + int points = 0; + uint32_t form = 0; + uint8_t rank_color = 0xf7; + uint8_t name_color = 0x5f; +}; + +// Owned snapshot of the corresponding Source hook boundary. `draw` keeps the +// shuffled entry order; `overview` keeps Source's post-sort order. The renderer +// never advances cup state or consumes either game RNG. +struct CupDrawProjection { + SeasonCupDrawPhase phase = SeasonCupDrawPhase::draw; + uint32_t entry_address = 0; + int competition = 0; + int round = 0; + int offset = 0; + uint8_t flags = 0; + bool group_stage = false; + int group_index = 0; + int group_count = 0; + size_t count = 0; + std::string heading; // Original-encoded TEXTD round name + std::string footer; // Original-encoded TEXTD competition label + std::string group_caption; // owned TEXTD 574/577 variants; never edits the shared TEXTD database + std::string group_round_suffix; + std::array group_form_glyphs{}; + bool decorated_background = true; + bool original_table_panel = true; + bool gradient_text = true; + bool previous_rank_visible = false; + bool source_eligible = false; // CupDrawFromGame world-mode and per-competition guards + int source_option_delay_ms = 0; // AdvanceStep(8), derived from the saved speed option + std::vector clubs; + std::vector group_rows; + std::vector> group_fixtures; +}; + +CupDrawProjection cup_draw_from_game(const GameState& game, + const SeasonCupDrawEvent& event, + const LeImage& exe, + const TextDb& texts); + +class CupDrawScreen { +public: + CupDrawScreen(const std::filesystem::path& data_directory, + CupDrawProjection projection); + + // Draw-phase stepping consumes the Source bytecode scripts from BMH.exe. + // Each call advances one timeline step. Initial setup performs ten + // AdvanceStep(8)/poll steps even if skip was requested. Script wait tokens + // expose AdvanceStep(8), input-poll, presentation, and fixed DecodeTaxAnimationScript2 delay + // separately; copy tokens request no presentation or delay. + bool advance_step(); + bool present_needed() const; + bool queue_flush_needed() const; + int option_delay_milliseconds() const; + int wait_milliseconds() const; + bool input_poll_needed() const; + bool held_mouse_check_needed() const; + bool reveal_complete() const; + bool reveal_aborted() const; + size_t revealed_count() const; + // Queue codes 2 (left down) and 8 (right down) are consumed only at the + // initial/per-club OriginalMouseSound polls. The initial ten polls remember a skip + // but still all run. During a KB74 script, pass held-buttons separately: + // SourceInput checks the held mouse bitmask after each option delay. + bool source_input(uint8_t source_code); + bool source_held_mouse(uint8_t left_right_mask); + + // `render()` returns the current draw/reveal framebuffer or the complete + // CupGroupOverviewEffects(..., 300) overview, depending on projection.phase. + Image render() const; + // Interaction reports the runtime club id under a Source team-name hit box; + // callers route it to the full Source club-information flow. + std::optional hit_test_team(int x, int y) const; + +private: + struct Impl; + std::shared_ptr impl_; +}; + +} // namespace bmh::ui diff --git a/src/ui/desk_drawers.cpp b/src/ui/desk_drawers.cpp new file mode 100644 index 0000000..62a06c4 --- /dev/null +++ b/src/ui/desk_drawers.cpp @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/desk_drawers.hpp" + +#include +#include +#include +#include + +#include "formats/le.hpp" +#include "formats/vga.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { + +constexpr std::array, 4> kSourcePairs{{ + {{3, 4}}, {{11, 12}}, {{16, 17}}, {{20, 21}} +}}; + +const DeskRankCurve* curve_for(const DeskState& state, int team) { + for (const auto& curve : state.rank_curves) + if (curve.runtime_team == team) return &curve; + return nullptr; +} + +std::string team_name(const DeskState& state, int team) { + if (team == state.runtime_club) return state.club_name; + if (state.next_opponent && *state.next_opponent == team) return state.next_opponent_name; + if (const auto* curve = curve_for(state, team)) return curve->team_name; + return {}; +} + +std::string result_piece(uint8_t packed, const LeImage& exe) { + return std::to_string(packed & 0x0f) + exe.cstring(::bmh::layout::DeskDrawers_Recent_ExecutableField) + + std::to_string(packed >> 4) + exe.cstring(::bmh::layout::DeskDrawers_Recent_ExecutableField2); +} + +} // namespace + +std::optional source_drawer_team(const DeskState& state, int local_kind) { + for (const auto& pair : kSourcePairs) { + if (local_kind != pair[0] && local_kind != pair[1]) continue; + int open_count = 0; + // SourceDrawerTeam: local64 stays zero unless the saved option and raw away + // byte permit ordering, and retained param6 actually has an opponent. + // Projection already omitted hidden linked-list records; disabled but + // visible drawers still participate in Source's count. + if (state.paired_drawers_away_order && state.next_opponent.value_or(-1)>=0) + for (const auto& item : state.items) + if (item.open && (item.kind - 50 == pair[0] || item.kind - 50 == pair[1])) ++open_count; + + // SourceDrawerTeam retains local44=param6 and local48=param8 before its + // away-side swap. The drawer cases use those retained values: when + // both are open, uVar21 is local48; otherwise it is local44. + const int local44 = state.next_opponent.value_or(-1); + const int local48 = state.national_team ? 0x165 : state.runtime_club; + const int uVar21 = (open_count == 2) ? local48 : local44; + const bool first_case = local_kind == pair[0]; + const int side = first_case ? (uVar21 != local48 ? local48 : local44) : uVar21; + if (side < 0) return std::nullopt; + return side; + } + return std::nullopt; +} + +DeskDrawerRenderer::DeskDrawerRenderer(const std::filesystem::path& data) + : exe_(load_le(asset_path(data, "BMH.exe"))), + icons_(load_vga(asset_path(data / "KB", "3.VGA"))), + small_(load_font(asset_path(data / "F", "BMH3.FNT"))), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))) {} + +bool DeskDrawerRenderer::handles(int native_kind) const { + switch (native_kind - 50) { + case 0: case 1: case 2: case 3: case 4: case 9: case 10: + case 11: case 12: case 16: case 17: case 20: case 21: + return true; + default: return false; // Source 0xd / 0x16 are empty switch cases. + } +} + +void DeskDrawerRenderer::copy(Image& target, int sx, int sy, int x, int y, int w, int h) const { + if (sx < 0 || sy < 0 || sx + w > icons_.width || sy + h > icons_.height) + throw FormatError("desk drawer: sprite outside KB/3.VGA"); + for (int yy = 0; yy < h; ++yy) for (int xx = 0; xx < w; ++xx) { + const uint8_t pixel = icons_.pixels[size_t(sy + yy) * size_t(icons_.width) + size_t(sx + xx)]; + if (pixel && x + xx >= 0 && y + yy >= 0 && x + xx < target.width && y + yy < target.height) + target.at(x + xx, y + yy) = pixel; + } +} + +void DeskDrawerRenderer::text(Image& target, const DeskState& state, int x, int baseline, + std::string_view value, uint8_t color, int right) const { + const int width = small_.text_width(value); + if (right >= 0) x += (right - x) / 2 - width / 2; + if (x < 0 || x + width > target.width || baseline < 5 || baseline >= target.height) return; + Image mask(std::max(1, width), 6); + small_.draw(mask, 0, 0, value, 1); + int gradient = 0; + while (gradient < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + uint32_t(gradient)) != color) ++gradient; + for (int yy = 0; yy < 6; ++yy) for (int xx = 0; xx < width; ++xx) + if (mask.at(xx, yy)) + target.at(x + xx, baseline - 5 + yy) = state.gradient_text + ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + uint32_t(gradient * 6 + yy)) : color; +} + +void DeskDrawerRenderer::line(Image& target, int x1, int y1, int x2, int y2, uint8_t color) const { + const int dx = std::abs(x2 - x1), sx = x1 < x2 ? 1 : -1; + const int dy = -std::abs(y2 - y1), sy = y1 < y2 ? 1 : -1; + int error = dx + dy; + for (;;) { + if (x1 >= 0 && y1 >= 0 && x1 < target.width && y1 < target.height) target.at(x1, y1) = color; + if (x1 == x2 && y1 == y2) break; + const int twice = 2 * error; + if (twice >= dy) error += dy, x1 += sx; + if (twice <= dx) error += dx, y1 += sy; + } +} + +void DeskDrawerRenderer::folder(Image& target, const DeskState& state, const DeskItem& item) const { + const int folder_id = item.kind - 50; + if (folder_id < 0 || folder_id >= int(state.folder_icon_slots.size())) return; + const int left = item.x + 5, top = item.y + 4; + int x = left, y = top; + const int right = item.x + item.width - 4; + const int bottom = item.y + item.height - 4; + for (uint8_t id : state.folder_icon_slots[size_t(folder_id)]) { + const int tile = int(id) - 1; + if (tile < 0 || tile >= 30) continue; + if (x + 32 > right) x = left, y += 27; + if (y + 25 > bottom) break; + copy(target, (tile % 8) * 32, (tile / 8) * 25, x, y, 32, 25); + x += 34; + } +} + +void DeskDrawerRenderer::curve(Image& target, const DeskState& state, const DeskItem& item, int local_kind) const { + const auto selected = source_drawer_team(state, local_kind); + if (!selected) { + text(target, state, item.x + 5, item.y + 49, texts_[1207], 0x6a, item.x + 85); // DeskDrawersRuntimeField + return; + } + const auto* curve = curve_for(state, *selected); + if (!curve || curve->league < 0 || curve->league >= 9) { + text(target, state, item.x + 5, item.y + 49, texts_[1206], 0x6a, item.x + 85); // DeskDrawersRuntimeField2 + return; + } + const uint32_t league = uint32_t(curve->league); + const int teams = exe_.u8(::bmh::layout::LeagueSizes + league); + const int low_cut = exe_.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField + league) + exe_.u8(::bmh::layout::DeskDrawers_Curve_RuntimeField + league); + const int high_cut = teams - exe_.u8(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField2 + league); + const int left = item.x + 5, top = item.y + 1, bottom = top + 42; + line(target, left, top, left, bottom, 0x6a); + line(target, left, bottom, left + 80, bottom, 0x6a); + for (const DeskRankSample& sample : curve->samples) { + if (sample.matchday < 1 || sample.matchday > 38 || sample.source_rank < 0 || sample.source_rank >= teams) continue; + int band = 1; + if (sample.source_rank < low_cut || (sample.source_rank == 0 && curve->league == 0)) band = 0; + if (high_cut <= sample.source_rank) ++band; + const int y = top + 43 - (teams - sample.source_rank) * 2; + const uint32_t at = ::bmh::layout::DeskDrawers_Curve_ExecutableField + uint32_t(band * 8); + if (!exe_.contains(at + 4)) continue; + for (int stroke = 0; stroke < 2; ++stroke) + line(target, left + 1 + 2 * (sample.matchday - 1) + stroke, y, left + 1 + 2 * (sample.matchday - 1) + stroke, top + 41, + exe_.u8(at + uint32_t(stroke * 4))); + } +} + +void DeskDrawerRenderer::recent(Image& target, const DeskState& state, const DeskItem& item) const { + text(target, state, item.x + 1, item.y + 6, texts_[1208], 0x6a, item.x + item.width - 1); + int row = 0; + for (const DeskRecentMatch& match : state.recent_matches) { + const int baseline = item.y + 13 + row * 7; + text(target, state, item.x + 1, baseline, match.home_name, 0x5f); + text(target, state, item.x + 94, baseline, exe_.cstring(::bmh::layout::DeskDrawers_Recent_TextPointer), 0x5f); + text(target, state, item.x + 101, baseline, match.away_name, 0x5f); + const std::string score = std::to_string(match.source_score & 0x0f) + exe_.cstring(::bmh::layout::DeskDrawers_Recent_ExecutableField) + + std::to_string(match.source_score >> 4) + exe_.cstring(::bmh::layout::DeskDrawers_Recent_ExecutableField2); + text(target, state, item.x + 188, baseline, score, 0x5f); + if (++row == 6) break; + } +} + +void DeskDrawerRenderer::head_to_head(Image& target, const DeskState& state, const DeskItem& item) const { + if (!state.next_opponent || *state.next_opponent < 0 || *state.next_opponent > 0xa7) { + text(target, state, item.x + 1, item.y + 13, texts_[1207], 0x6a, item.x + 115); // DeskDrawersRuntimeField + return; + } + const auto found = std::find_if(state.opponent_histories.begin(), state.opponent_histories.end(), + [&](const DeskOpponentHistory& row) { return row.runtime_team == *state.next_opponent; }); + const std::string opponent = team_name(state, *state.next_opponent); + text(target, state, item.x + 1, item.y + 6, + texts_[1209] + texts_[state.next_match_away ? 1211 : 1210], 0x6a, item.x + 115); + text(target, state, item.x + 1, item.y + 13, opponent, 0x6a, item.x + 115); + if (found == state.opponent_histories.end()) { + text(target, state, item.x + 1, item.y + 20, texts_[1212], 0x6a, item.x + 115); + return; + } + const size_t venue = state.next_match_away ? 5 : 0; + std::string values; + for (size_t result = 0; result < 5; ++result) { + const uint8_t packed = found->source_results[venue + result]; + if (packed == 0xff) break; + if (!values.empty()) values += exe_.cstring(::bmh::layout::DeskDrawers_HeadToHead_ExecutableField); + values += result_piece(packed, exe_); + } + if (values.empty()) values = texts_[1212]; + text(target, state, item.x + 1, item.y + 20, values, 0x5f, item.x + 115); +} + +void DeskDrawerRenderer::rank_strength(Image& target, const DeskState& state, const DeskItem& item, + int local_kind) const { + const auto selected = source_drawer_team(state, local_kind); + if (!selected) return; + const auto* curve = curve_for(state, *selected); + std::string value; + std::optional position, strength; + if (*selected == state.runtime_club) { + position = state.table_position; + strength = state.strength; + } else if (curve) { + position = curve->current_position; + strength = curve->strength; + } + if (position) value = std::to_string(*position + 1) + texts_[1213]; + if (strength) { + if (!value.empty()) value += texts_[1214]; + else value = texts_[1214]; + if (*strength < 10) value += '%'; // FNT3's transparent 5px field pad. + value += std::to_string(*strength); + } + if (value.empty()) { + const auto name = team_name(state, *selected); + if (!name.empty()) text(target, state, item.x + 5, item.y + 6, name, 0x5f); + return; + } + if (!value.empty()) text(target, state, item.x, item.y + 6, value, 0x5f, item.x + 94); +} + +void DeskDrawerRenderer::opponent_name(Image& target, const DeskState& state, const DeskItem& item, + int local_kind) const { + const auto selected = source_drawer_team(state, local_kind); + if (!selected) return; + const std::string name = team_name(state, *selected); + if (!name.empty()) text(target, state, item.x, item.y + 6, name, 0x5f, item.x + 94); +} + +void DeskDrawerRenderer::badge(Image& target, const DeskState& state, const DeskItem& item, + int local_kind, const Image& own_badge_atlas, + const std::optional& rival_badge_atlas, + const Image& fallback_badge_atlas) const { + const int x = item.x + 1, y = item.y + 1; + line(target, x - 1, y - 1, x + 38, y - 1, 0x46); + line(target, x - 1, y - 1, x - 1, y + 38, 0x46); + line(target, x - 1, y + 38, x + 38, y + 38, 0x40); + line(target, x + 38, y - 1, x + 38, y + 38, 0x40); + + const auto selected = source_drawer_team(state, local_kind); + const Image* atlas = nullptr; + int crest = -1; + if (selected && *selected == state.runtime_club) { + atlas = &own_badge_atlas; + crest = state.badge & 0x1ff; + } else if (selected && state.next_opponent && *selected == *state.next_opponent && + !state.next_opponent_badge_fallback && state.next_opponent_badge && rival_badge_atlas) { + atlas = &*rival_badge_atlas; + crest = *state.next_opponent_badge & 0x1ff; + } + + if (atlas && crest >= 0 && atlas->width >= 304 && atlas->height >= 38) { + const int sx = (crest & 7) * 38; + for (int yy = 0; yy < 38; ++yy) for (int xx = 0; xx < 38; ++xx) { + const uint8_t pixel = atlas->pixels[size_t(yy) * size_t(atlas->width) + size_t(sx + xx)]; + if (x + xx >= 0 && y + yy >= 0 && x + xx < target.width && y + yy < target.height) + target.at(x + xx, y + yy) = pixel; + } + return; + } + + // SourceBadgeFallback falls through FormatError(..., 0x0e) when the + // selected Source team has no crest; DesktopScreen already owns KB/0.VGA. + if (fallback_badge_atlas.width >= 46 && fallback_badge_atlas.height >= 38) { + for (int yy = 0; yy < 38; ++yy) for (int xx = 0; xx < 38; ++xx) { + const uint8_t pixel = fallback_badge_atlas.pixels[size_t(yy) * size_t(fallback_badge_atlas.width) + size_t(8 + xx)]; + if (x + xx >= 0 && y + yy >= 0 && x + xx < target.width && y + yy < target.height) + target.at(x + xx, y + yy) = pixel; + } + } +} + +void DeskDrawerRenderer::draw(Image& target, const DeskState& state, const DeskItem& item, + const Image& own_badge_atlas, + const std::optional& rival_badge_atlas, + const Image& fallback_badge_atlas) const { + if (!handles(item.kind)) return; + DeskItem content = item; + if (item.open) content.x += 4, content.y += 4; + const int local_kind = content.kind - 50; + if (local_kind >= 0 && local_kind <= 2) return folder(target, state, content); + switch (local_kind) { + case 3: case 4: curve(target, state, content, local_kind); break; + case 9: recent(target, state, content); break; + case 10: head_to_head(target, state, content); break; + case 11: case 12: rank_strength(target, state, content, local_kind); break; + case 16: case 17: badge(target, state, content, local_kind, own_badge_atlas, + rival_badge_atlas, fallback_badge_atlas); break; + case 20: case 21: opponent_name(target, state, content, local_kind); break; + default: break; + } +} + +} // namespace bmh::ui diff --git a/src/ui/desk_drawers.hpp b/src/ui/desk_drawers.hpp new file mode 100644 index 0000000..4b056c5 --- /dev/null +++ b/src/ui/desk_drawers.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "ui/desk_state.hpp" + +namespace bmh::ui { + +// Source pair selection for SourceDrawerTeam's paired drawers. `local_kind` is +// the switch value (native item kind minus 50), not the native record kind. +std::optional source_drawer_team(const DeskState&, int local_kind); + +class DeskDrawerRenderer { +public: + explicit DeskDrawerRenderer(const std::filesystem::path& data); + bool handles(int native_kind) const; + // Draws content only; the caller retains ownership of the native drawer frame. + void draw(Image& target, const DeskState&, const DeskItem&, + const Image& own_badge_atlas, const std::optional& rival_badge_atlas, + const Image& fallback_badge_atlas) const; + +private: + LeImage exe_; + Image icons_; + Font small_; + TextDb texts_; + + void copy(Image&, int sx, int sy, int x, int y, int w, int h) const; + void text(Image&, const DeskState&, int x, int baseline, std::string_view, uint8_t color, int right = -1) const; + void line(Image&, int x1, int y1, int x2, int y2, uint8_t color) const; + void folder(Image&, const DeskState&, const DeskItem&) const; + void curve(Image&, const DeskState&, const DeskItem&, int local_kind) const; + void recent(Image&, const DeskState&, const DeskItem&) const; + void head_to_head(Image&, const DeskState&, const DeskItem&) const; + void rank_strength(Image&, const DeskState&, const DeskItem&, int local_kind) const; + void opponent_name(Image&, const DeskState&, const DeskItem&, int local_kind) const; + void badge(Image&, const DeskState&, const DeskItem&, int local_kind, + const Image& own_badge_atlas, const std::optional& rival_badge_atlas, + const Image& fallback_badge_atlas) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/desk_records.cpp b/src/ui/desk_records.cpp new file mode 100644 index 0000000..e5793cd --- /dev/null +++ b/src/ui/desk_records.cpp @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/desk_records.hpp" + +#include +#include + +#include "game/lineup.hpp" +#include "game/messages.hpp" +#include "game/schedule.hpp" +#include "ui/manager.hpp" +#include "formats/textd.hpp" + +namespace bmh::ui { +std::filesystem::path asset_path(const std::filesystem::path&, const std::string&); +namespace { +void copy(Image& out, const Image& src, int sx, int sy, int x, int y, int w, int h) { + if (sx < 0 || sy < 0 || x < 0 || y < 0 || sx+w>src.width || sy+h>src.height || + x+w>out.width || y+h>out.height) throw FormatError("desk records: Original asset bounds"); + for(int yy=0;yy(g.manager_teams.size(),4); + const int active=g.memory.has(::bmh::layout::ActiveManager)?g.memory.u8(::bmh::layout::ActiveManager):-1; + const int managers=g.memory.has(::bmh::layout::ManagerCount)?g.memory.u8(::bmh::layout::ManagerCount):int(count); + const bool current=g.memory.has(::bmh::layout::DeskPosition)&&g.memory.u8(::bmh::layout::DeskPosition)=g.manager_records.size()||g.manager_records[at]==0)continue; + if(g.manager_teams[slot]==team)return int(slot)==active&¤t?0x7a:0x75; + } + if(g.memory.has(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)&&g.memory.u16(::bmh::layout::AlltimeTable_TeamColor_RuntimeField)==team)return 0xf7; + return 0x5f; +} + +} + +DeskRecordsState fair_play_state_from_game(const GameState& g, int league, const Image& underlay,int manager_slot) { + if(league<0||league>=9) throw FormatError("fair play: invalid Source league"); + const int first=league_first_team(league), count=kLeagueSizes[league]; + if(first<0||count<=0||first+count>138||g.club_ids.size() teams(static_cast(count)); std::vector keys(static_cast(count)); + for(int i=0;i>8)*4+(cards&0xff)); + } + // FairPlayStateFromGame passes ascending=1 to the same in-place Source quicksort. + quicksort_by_key(teams.data(),keys.data(),count,true); + DeskRecordsState out; out.kind=DeskRecordKind::fair_play;out.league=league;out.underlay=underlay; + out.original_panel=!g.memory.has(::bmh::layout::SolidPanelBackground)||g.memory.u8(::bmh::layout::SolidPanelBackground)==0; + if(manager_slot>=0&&size_t(manager_slot)>8),int(keys[size_t(i)]),g.club_name(team),source_team_color(g,team)}); + } + return out; +} + +DeskRecordsScreen::DeskRecordsScreen(const std::filesystem::path& data, DeskRecordsState state) + : exe_(load_le(asset_path(data,"BMH.exe"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))), + font_(load_font(asset_path(data/"F","BMH3.FNT"))),sprite_font_(data), + background_(load_vga(asset_path(data/"KB","129.VGA"))),state_(std::move(state)) { + if(state_.underlay.width!=320||state_.underlay.height!=240) throw FormatError("desk records: missing accepted desk underlay"); + if(state_.kind==DeskRecordKind::fair_play) { + kb56_=load_vga(asset_path(data/"KB","56.VGA")); + const int bottom=int(state_.fair_play_rows.size())*9+38; + if(state_.league<0||state_.league>=9||state_.fair_play_rows.size()!=size_t(kLeagueSizes[state_.league])|| + kb56_.width<296||kb56_.height<9+(bottom-28-1)) + throw FormatError("fair play: incomplete Original view"); + } else if(state_.highscore.ranked) { + kb51_=load_vga(asset_path(data/"KB","51.VGA")); + if(kb51_.width<112||kb51_.height<74||state_.highscore.rows.size()!=5) + throw FormatError("highscore: incomplete Original view"); + } else if(state_.highscore.rows.size()!=5) throw FormatError("highscore: incomplete Original view"); + if(state_.kind==DeskRecordKind::highscore&&!state_.highscore.ranked) + alternate_=std::make_unique(load_game_end_alternate_score_assets(data),state_.underlay,state_.gradient_text); +} +void DeskRecordsScreen::text(Image& out,int x,int baseline,std::string_view value,uint8_t color,bool shadow) const { + const int width=font_.text_width(value), top=baseline-font_.baseline; + const int offset=shadow?2:0; + if(x<0||x+width+offset>out.width||top<0||top+font_.height+offset>out.height)return; + if(shadow)font_.draw(out,x+2,top+2,value,0x40); + if(!state_.gradient_text){font_.draw(out,x,top,value,color);return;} + Image mask(std::max(1,width),font_.height); + font_.draw(mask,0,0,value,1); + int index=0;while(index<32&&exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2+uint32_t(index))!=color)++index; + for(int y=0;yrender(); + } + Image out=state_.decorated_background?background_:Image(320,240); + if(!state_.decorated_background){ + fill_rect(out,0,4,320,13,0x44);fill_rect(out,1,5,318,11,0x39); + fill_rect(out,0,228,320,10,0x44);fill_rect(out,1,229,318,8,0x39); + } + if(state_.kind==DeskRecordKind::fair_play) { + // LoadGameEndTaxAnimationAssets(0,26,28,296,count*9+38): exact absolute Source edges. + const int right=296, bottom=int(state_.fair_play_rows.size())*9+38; + if(state_.original_panel) copy(out,kb56_,26,9,27,29,right-27,bottom-29); + else fill_rect(out,26,28,right-26+1,bottom-28+1,0x42); + for(int y=28;y<=bottom;++y)out.at(26,y)=0x46; + for(int x=26;x<=right;++x)out.at(x,28)=0x46; + for(int x=26;x<=right;++x)out.at(x,bottom)=0x40; + for(int y=28;y<=bottom;++y)out.at(right,y)=0x40; + const auto heading=original_to_utf8(texts_.strings.at((::bmh::layout::DeskRecords_FillRect_TextPointer5-::bmh::layout::TextPointerTable)/4)); + const int heading_x=SpriteFont::centered_title_x(sprite_font_.text_width(heading)); + sprite_font_.draw(out,heading_x,13,heading,5); + sprite_font_.draw(out,5,235,original_to_utf8(state_.manager_name),5); + for(size_t i=0;iphase()==AlternateScorePhase::AwaitAck) { + if(alternate_->acknowledge()) { closed_=true; return true; } + return false; + } + if(alternate_->phase()==AlternateScorePhase::Cancelled) { closed_=true; return true; } + if(alternate_->phase()!=AlternateScorePhase::Calculator)return false; + if(right) { alternate_->cancel(); closed_=true; return true; } + const bool changed=alternate_->mouse_down(x,y); + if(alternate_->phase()==AlternateScorePhase::Cancelled)closed_=true; + return changed; +} +bool DeskRecordsScreen::pointer_up(int,int,bool) { + if(closed_||!alternate_)return false; + return alternate_->mouse_up(); +} +bool DeskRecordsScreen::text_input(std::string_view input) { + if(closed_||!alternate_)return false; + return alternate_->text(input); +} +bool DeskRecordsScreen::key_input(std::string_view key) { + if(closed_)return false; + if(!alternate_)return false; // SDLFlushEvents2 only returns on mouse down or quit. + return alternate_->key(key); +} +} // namespace bmh::ui diff --git a/src/ui/desk_records.hpp b/src/ui/desk_records.hpp new file mode 100644 index 0000000..f9cc79b --- /dev/null +++ b/src/ui/desk_records.hpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/highscore.hpp" +#include "game/state.hpp" +#include "ui/game_end_alternate.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { + +enum class DeskRecordKind { fair_play, highscore }; +struct FairPlayRow { int team = -1, rank = 0, yellow = 0, red = 0, points = 0; std::string name; uint8_t name_color=0x5f; }; +struct DeskRecordsState { + DeskRecordKind kind = DeskRecordKind::fair_play; + int league = -1; + std::vector fair_play_rows; + HighscoreProjection highscore; + Image underlay; + bool gradient_text = true; + bool original_panel = true; + bool decorated_background = true; + std::string manager_name; +}; + +// Original menu-25/FairPlayStateFromGame and menu-26/GameEndAlternateScoreScreen report views. Their engine +// projections are read-only here; only the highscore file's Source update is +// performed by the caller before constructing this presentation. +DeskRecordsState fair_play_state_from_game(const GameState&, int league, const Image& underlay = {}, int manager_slot=-1); +class DeskRecordsScreen { +public: + DeskRecordsScreen(const std::filesystem::path& data, DeskRecordsState); + Image render() const; + bool pointer_down(int x,int y,bool right=false); + bool pointer_up(int x,int y,bool right=false); + bool advance_point() { return alternate_ && alternate_->advance_point(); } + bool finish_points() { return alternate_ && alternate_->finish_points(); } + bool points_active() const { return alternate_ && alternate_->phase()==AlternateScorePhase::Points; } + bool text_input(std::string_view); + bool key_input(std::string_view); + bool is_alternate_calculator() const { return bool(alternate_); } + bool close_input() { if (closed_) return false; closed_ = true; return true; } + bool closed() const { return closed_; } + DeskRecordKind kind() const { return state_.kind; } +private: + LeImage exe_; TextDb texts_; Font font_; SpriteFont sprite_font_; Image kb56_, kb51_, background_; + DeskRecordsState state_; bool closed_ = false; + std::unique_ptr alternate_; + void text(Image&, int x, int baseline, std::string_view, uint8_t color, bool shadow=false) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/desk_state.cpp b/src/ui/desk_state.cpp new file mode 100644 index 0000000..15b944e --- /dev/null +++ b/src/ui/desk_state.cpp @@ -0,0 +1,752 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/desk_state.hpp" + +#include +#include +#include + +#include "formats/fbm.hpp" +#include "formats/savestate.hpp" +#include "game/match_engine.hpp" +#include "game/matchday.hpp" +#include "game/schedule.hpp" +#include "game/season.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { + +Bytes block_copy(const SaveState& s, uint32_t a) { + const auto& b = s.block(a); + return Bytes(s.stream().begin() + b.offset, s.stream().begin() + b.offset + b.size); +} +std::string bounded_string(const Bytes& b, size_t offset, size_t limit) { + if (offset >= b.size()) throw FormatError("desk: name offset outside pool/record"); + const auto end = std::min(b.size(), offset + limit); + const auto nul = std::find(b.begin() + offset, b.begin() + end, 0); + if (nul == b.begin() + end) throw FormatError("desk: unterminated name"); + return std::string(b.begin() + offset, nul); +} +uint16_t word(const Bytes& b, size_t at) { return le16(b, at); } +int32_t signed_word(const Bytes& b, size_t at) { return int32_t(le32(b, at)); } + +std::string pool_name(const Bytes& names, const std::vector& offsets, int team) { + if (team < 0 || size_t(team) >= offsets.size() || offsets[size_t(team)] >= names.size()) return {}; + return bounded_string(names, offsets[size_t(team)], names.size()); +} + +int executable_league(const LeImage& exe, int team) { + if (team < 0 || team >= 138 || !exe.contains(::bmh::layout::LeagueSizes + 8)) return -1; + int first = 0; + for (int league = 0; league < 9; ++league) { + if (!exe.contains(::bmh::layout::LeagueSizes + uint32_t(league))) return -1; + first += exe.u8(::bmh::layout::LeagueSizes + uint32_t(league)); + if (team < first) return league; + } + return -1; +} + +void project_drawer_rows(DeskState& d, const LeImage& exe, const Bytes& managers, + const Bytes& club_names, const std::vector& club_ids, + const std::vector& position_history, + const std::vector& manager_results, + const std::vector& league_rounds, + std::optional authenticated_rival, + const GameState* game = nullptr) { + if (d.manager_slot < 0) return; + const size_t manager = size_t(d.manager_slot); + const size_t record = manager * 0xb0c; + if (record + 0x2aa <= managers.size()) { + for (int match = 0; match < 6; ++match) { + const size_t at = record + 0x292 + size_t(match) * 4; + const int home = int16_t(le16(managers, at)); + const int away = int16_t(le16(managers, at + 2)); + if (home == away) break; // SourceDrawerTeam uses equal adjacent IDs as its terminator. + if (home < 0 || away < 0 || size_t(home) >= club_ids.size() || size_t(away) >= club_ids.size()) + break; + DeskRecentMatch row; + row.home_team = home; row.away_team = away; + row.home_name = pool_name(club_names, club_ids, home); + row.away_name = pool_name(club_names, club_ids, away); + row.source_score = managers.at(record + 0x212 + size_t(match)); + d.recent_matches.push_back(std::move(row)); + } + } + + auto rank_curve = [&](int team, DeskRankCurve& curve) { + curve.runtime_team = team; + curve.team_name = pool_name(club_names, club_ids, team); + if (team == 0x165) { + // TablePosition returns rank 2 for this special national row; + // QuoteNationalFriendlyMatch uses its native no-team squad (no random rating). + curve.current_position = 2; + if (game) curve.strength = team_average(*game, kNoTeam, 0x1ff).value; + return; + } + const int league = executable_league(exe, team); + if (league < 0 || size_t(league) >= league_rounds.size()) return; + curve.league = league; + const int rounds = std::min(league_rounds[size_t(league)], 38); + const size_t team_base = size_t(team) * 13 * 2; + if (team_base + size_t((rounds + 2) / 3) * 2 > position_history.size()) return; + for (int round = 0; round < rounds; ++round) { + const size_t word_at = team_base + size_t(round / 3) * 2; + const uint16_t packed = uint16_t(position_history[word_at] | + (uint16_t(position_history[word_at + 1]) << 8)); + curve.samples.push_back({round + 1, int((packed >> ((round % 3) * 5)) & 0x1f)}); + } + if (!curve.samples.empty()) curve.current_position = curve.samples.back().source_rank; + if (game && team < 138) curve.strength = team_average(*game, team, 0x1ff).value; + }; + rank_curve(d.runtime_club < 0 ? 0x165 : d.runtime_club, d.rank_curves[0]); + if (authenticated_rival && *authenticated_rival >= 0 && *authenticated_rival != d.runtime_club) + rank_curve(*authenticated_rival, d.rank_curves[1]); + + // SourceDrawerTeam reads only the prepared opponent's venue history. Other + // teams' names need not be available to render this manager's current Desk. + if (!authenticated_rival || *authenticated_rival < 0 || *authenticated_rival >= 168) return; + const size_t at = manager * 0x690 + size_t(*authenticated_rival) * 10; + if (at + 10 > manager_results.size()) return; + const bool present = std::any_of(manager_results.begin() + at, + manager_results.begin() + at + 10, [](uint8_t value) { return value != 0xff; }); + if (!present) return; + DeskOpponentHistory row; + row.runtime_team = *authenticated_rival; + row.team_name = pool_name(club_names, club_ids, row.runtime_team); + std::copy_n(manager_results.begin() + at, row.source_results.size(), row.source_results.begin()); + d.opponent_histories.push_back(std::move(row)); +} + +void project_table_position(DeskState& desk, const GameState& game) { + // SourceDrawerTeam permits league clubs and CupDraw_FormatError_RuntimeField2 (the Source 0x165 + // national-team slot) through its rank/strength path. + const int position = table_position(game, desk.runtime_club); + if (position >= 0) desk.table_position = position; +} + +struct Tables { + const Bytes &managers, &tactics, &options, &stocks, &badges, &names; + const std::vector& name_offsets; + const std::vector& squads; + const std::vector& players; + const std::vector& morale; + const std::vector& teams; + const std::vector& rounds; +}; + +DeskState project(const StaticMemory& memory, const Tables& t, const LeImage& exe, + int level, uint32_t date, int season_day, int season, uint64_t revision) { + DeskState d; + d.revision = revision; + d.options.duration = memory.u8(::bmh::layout::CareerDuration); d.options.mode = memory.u8(::bmh::layout::GameMode); + d.options.managers = memory.u8(::bmh::layout::ManagerCount); d.options.difficulty = level; + const auto competitions = memory.u32(::bmh::layout::CompetitionSelection); + d.options.league = (competitions & 1) != 0; d.options.world = (competitions & 2) != 0; + if (d.options.managers < 1 || d.options.managers > 4 || level < 0 || level > 9 || + d.options.duration < 1 || d.options.duration > 5 || d.options.mode < 1 || d.options.mode > 3 || + (!d.options.league && !d.options.world)) throw FormatError("desk: invalid saved setup"); + d.manager_slot = memory.u8(::bmh::layout::ActiveManager); + if (d.manager_slot < 0 || d.manager_slot >= d.options.managers || + t.teams.size() != size_t(d.options.managers)) throw FormatError("desk: unsupported/inconsistent active manager"); + const uint32_t layout_base = ::bmh::layout::Desktops + uint32_t(d.manager_slot) * 0x360; + for (int record = 0; record < 54; ++record) { + const uint32_t at = layout_base + uint32_t(record) * 16; + for (int byte = 0; byte < 16; ++byte) + d.layout_records[size_t(record)][size_t(byte)] = memory.u8(at + uint32_t(byte)); + } + d.layout_snap = memory.u8(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField2) == 0; + // SourceDrawerTeam cases 0..2 collect folder children from records 1..30; + // the item number itself is the KB/3 tile index plus one. + for (int slot = 0; slot < 30; ++slot) { + const int item = slot + 1; + const auto& record = d.layout_records[size_t(item)]; + if ((record[1] & 0x10) != 0 || record[5] != 0xff) continue; + const int folder = record[13] & 0x7f; + if (folder >= 0 && folder < 3 && d.folder_icon_slots[size_t(folder)].size() < 12) + d.folder_icon_slots[size_t(folder)].push_back(uint8_t(item)); + } + d.manager_teams = t.teams; + std::set unique_teams; + d.managers.reserve(d.manager_teams.size()); + for (size_t slot = 0; slot < d.manager_teams.size(); ++slot) { + const int team = d.manager_teams[slot]; + if (team < 0 || team >= int(t.name_offsets.size()) || !unique_teams.insert(team).second) + throw FormatError("desk: invalid or duplicate manager runtime club"); + const size_t manager_base = slot * 0xb0c; + if (t.managers.size() < manager_base + 0xb0c || t.badges.size() < size_t(team + 1) * 2) + throw FormatError("desk: truncated manager identity/assets"); + DeskManagerIdentity identity; + identity.runtime_club = team; + // club_ids maps runtime teams to stable name-pool identities. Season + // table changes may replace the runtime ID while preserving this key. + identity.club_identity_key = int(t.name_offsets.at(size_t(team))); + identity.name = bounded_string(t.managers, manager_base + 0xa8, 26); + identity.league = t.managers.at(manager_base + 0x210); + identity.portrait = t.managers.at(manager_base + 0x221); + identity.badge = word(t.badges, size_t(team) * 2) & 0x1ff; + if ((team != kNoTeam && identity.league > 8) || identity.portrait > 11) + throw FormatError("desk: invalid manager identity"); + d.managers.push_back(std::move(identity)); + } + const size_t base = size_t(d.manager_slot) * 0xb0c; + if (t.managers.size() < base + 0xb0c || t.options.size() < size_t(d.manager_slot + 1) * 5) + throw FormatError("desk: truncated manager records/options"); + d.runtime_club = t.teams.at(d.manager_slot); + d.national_team = d.runtime_club == kNoTeam; + d.national_coach_takeover = memory.has(::bmh::layout::CoachActive) && memory.u8(::bmh::layout::CoachActive) != 0; + if (d.national_team && d.national_coach_takeover) { + const int saved_manager_count = memory.has(::bmh::layout::OriginalManagerCount) ? memory.u8(::bmh::layout::OriginalManagerCount) : 0; + if (saved_manager_count < 1 || saved_manager_count > 4) + throw FormatError("desk: invalid saved manager count during national takeover"); + d.national_return_roster.reserve(size_t(saved_manager_count)); + for (int slot = 0; slot < saved_manager_count; ++slot) { + // SwapManagerSlots2 swaps the original slot 0 through spare record 4; + // other human records remain in their original slots. + const size_t source_slot = slot == 0 ? 4 : size_t(slot); + const size_t manager_base = source_slot * 0xb0c; + if (t.managers.size() < manager_base + 0x292) + throw FormatError("desk: truncated saved manager roster during national takeover"); + const int team = word(t.managers, manager_base + 0x290); + if (team < 0 || team >= int(t.name_offsets.size()) || team == kNoTeam || + t.badges.size() < size_t(team + 1) * 2) + throw FormatError("desk: invalid home club in national return roster"); + DeskManagerIdentity original; + original.runtime_club = team; + original.club_identity_key = int(t.name_offsets.at(size_t(team))); + original.name = bounded_string(t.managers, manager_base + 0xa8, 26); + original.league = t.managers.at(manager_base + 0x210); + original.portrait = t.managers.at(manager_base + 0x221); + original.badge = word(t.badges, size_t(team) * 2) & 0x1ff; + d.national_return_roster.push_back(std::move(original)); + } + const auto coach = std::find_if(d.national_return_roster.begin(), d.national_return_roster.end(), + [&](const DeskManagerIdentity& candidate) { + return candidate.name == d.managers.at(0).name && + candidate.portrait == d.managers.at(0).portrait; + }); + if (coach == d.national_return_roster.end()) + throw FormatError("desk: national coach is absent from the saved manager roster"); + d.managers.at(0).club_identity_key = coach->club_identity_key; + } + if (d.runtime_club < 0 || d.runtime_club >= int(t.name_offsets.size())) throw FormatError("desk: invalid runtime club"); + if (d.national_team && ((!d.options.world && !d.national_coach_takeover) || + d.manager_slot != 0 || d.options.managers != 1)) + throw FormatError("desk: national team requires one manager and world-mode or source takeover evidence"); + d.manager_name = d.managers[size_t(d.manager_slot)].name; + d.club_name = bounded_string(t.names, t.name_offsets.at(d.runtime_club), t.names.size()); + d.badge = d.managers[size_t(d.manager_slot)].badge; + d.league = d.managers[size_t(d.manager_slot)].league; d.portrait = d.managers[size_t(d.manager_slot)].portrait; + if ((!d.national_team && d.league > 8) || d.portrait > 11) throw FormatError("desk: invalid league/portrait"); + d.day_counter = date; d.season_day = season_day; d.season_index = season; + if (season < 0 || season_day < 0 || season_day > 366) throw FormatError("desk: invalid season context"); + d.date = desk_date(date, exe); + if (date == 0 && season == 0 && season_day == 0) { d.next_competition = 33; d.next_opponent = -1; } + // A completed round count is not proof of the current/next matchday. + if (!d.national_team && size_t(d.league) >= t.rounds.size()) throw FormatError("desk: missing league round counters"); + d.balance = signed_word(t.managers, base + 0x314); d.savings = signed_word(t.managers, base + 0x318); + d.ticket_price = t.managers.at(base + 0x26e); d.fans = t.managers.at(base + 0x211); + // Currency constants are not FBM blocks. Read executable defaults unless the + // application explicitly supplies their live values in StaticMemory. + d.money_numerator = int32_t(memory.has(::bmh::layout::CurrencyMultiplier) ? memory.u32(::bmh::layout::CurrencyMultiplier) : exe.u32(::bmh::layout::CurrencyMultiplier)); + d.money_denominator = int32_t(memory.has(::bmh::layout::CurrencyDivisor) ? memory.u32(::bmh::layout::CurrencyDivisor) : exe.u32(::bmh::layout::CurrencyDivisor)); + if (d.money_denominator <= 0) throw FormatError("desk: invalid currency denominator"); + d.decorated_background = memory.u8(::bmh::layout::PlainBackground) == 0; + d.gradient_text = memory.u8(::bmh::layout::TextGradientDisabled) == 0 && exe.u8(::bmh::layout::TextGradientMode) == 2; + d.drawer_handles = memory.u8(::bmh::layout::CareerSession_DispatchDesktopLayout_RuntimeField) == 0; + d.paired_drawers_away_order = memory.u8(::bmh::layout::DeskState_FormatError_RuntimeField2) == 0 && t.managers.at(base+0x28a) != 0; + d.shortcut_bar_always = memory.u8(::bmh::layout::DeskState_FormatError_RuntimeField3) == 0; + // CopyN returns the matching record index. The last bar cell (value + // 72) resolves to native record 53; DeskDate dispatches that index as MEN. + // Record 34/kind 53 belongs to the curves drawer and is not the MEN handle. + for (int item = 0; item < 54; ++item) { + const uint32_t at = ::bmh::layout::Desktops + uint32_t(d.manager_slot) * 0x360 + uint32_t(item) * 16; + if (item != 53 || memory.u8(at + 12) != 72) continue; + DeskItem shortcut; + shortcut.id = item; shortcut.kind = 53; + shortcut.x = 0x16 + (72 - 50) * 12; shortcut.y = 0xd7; + shortcut.width = 12; shortcut.height = 11; + d.menu_layout_shortcut = shortcut; + break; + } + // The mailbox dispatcher additionally requires record index 44. + for (int item = 0; item < 54; ++item) { + const uint32_t at = ::bmh::layout::Desktops + uint32_t(d.manager_slot) * 0x360 + uint32_t(item) * 16; + if (memory.u8(at + 12) != 63) continue; + // The dispatcher opens mail only for returned item index 44. A changed + // kind-to-index mapping is not evidence for a different mailbox entry. + if (item != 44) break; + DeskItem shortcut; + shortcut.id = item; shortcut.kind = 63; + shortcut.x = 0x16 + (63 - 50) * 12; shortcut.y = 0xd7; + shortcut.width = 12; shortcut.height = 11; + // Unlike ordinary desk icons, CopyN checks no disabled mask. + shortcut.disabled = false; + d.mailbox_shortcut = shortcut; + break; + } + std::copy_n(t.options.begin() + size_t(d.manager_slot) * 5, 5, d.automation.begin()); + + // Fill: display predicates only. No game state is changed. + d.warnings.fill(false); + for (size_t share = 0; share < 12; ++share) { + const size_t at = share * 0x5c; + const auto owned = word(t.stocks, at + 0x50 + size_t(d.manager_slot) * 2); + if (owned && le32(t.stocks, at + 4 + size_t(d.manager_slot) * 4) / owned < word(t.stocks, at + 0x4e)) + d.warnings[0] = true; + } + const int64_t overdraft = signed_word(t.managers, base + 0x31c); + d.warnings[1] = -int64_t(d.balance) != overdraft && d.balance <= -overdraft; + for (size_t ad = 0; ad < 16; ++ad) + if (!t.managers.at(base + 0xa39 + ad * 12)) d.warnings[2] = true; + uint8_t remaining = 18; + for (size_t kind = 6; kind < 13; ++kind) remaining = uint8_t(remaining - t.managers.at(base + 0xc5 + kind)); + d.warnings[3] = remaining < 4; + const int max24 = exe.u16(::bmh::layout::TeamsWithSquads), league_teams = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField); + if (!d.national_team && d.runtime_club >= league_teams) throw FormatError("desk: cup-only squad projection not supported"); + const size_t first = d.national_team ? 3072 : size_t(d.runtime_club < max24 ? d.runtime_club * 24 : d.runtime_club * 16 + max24 * 8); + const size_t count = d.national_team ? 24 : (d.runtime_club < max24 ? 24 : 16); + if (t.squads.size() < first + count || t.tactics.size() < size_t(d.manager_slot) * 0x840 + count * 0x58) + throw FormatError("desk: truncated squad/tactics"); + int lineup = 0, reserve = 0, condition = 0, technique = 0, form = 0, morale = 0; + for (size_t row = 0; row < count; ++row) { + const auto slot = t.squads.at(first + row); + if ((slot & 0xfff) == 0xfff) continue; + const size_t board = size_t(d.manager_slot) * 0x840 + row * 0x58; + if (slot & 0x8000) { + ++lineup; + const auto& p = t.players.at(slot & 0xfff); + condition += p.condition(); technique += p.technique(); form += p.form(); + morale += (t.morale.at(d.runtime_club) & 0x3f) * 2; + } + if (slot & 0x4000) ++reserve; + if (row < 11 && t.tactics.at(board + 0x0f) > 69) d.warnings[4] = true; + if (t.tactics.at(board + 0x0c) < 4) d.warnings[8] = true; + } + d.warnings[5] = lineup < 11; d.warnings[6] = reserve < 5; + d.warnings[7] = int8_t(t.managers.at(base + 0xd9)) > 8; + // QuoteNationalFriendlyMatch(team, 0x1ff): pure display strength; fixed divisor of eleven. + int strength = (condition + technique) / 2; + if (form) strength = (100 + (form / 11 - 50) / 8) * strength / 100; + if (morale) strength = (100 + (morale / 11 - 50) / 8) * strength / 100; + d.strength = std::max(1, std::clamp(strength / 11, 0, 99)); + // Int64T -> HighscoreScore(0x0f/0x10,0,0xff): readonly assets/debt sum. + int64_t assets = int64_t(d.balance) + d.savings, debt = 0; + for (size_t property = 0; property < 6; ++property) { + const auto at = ::bmh::layout::FundBlockUnsigned + uint32_t(property) * 0x1c; + assets += int64_t(memory.u16(at + 0x14 + uint32_t(d.manager_slot) * 2)) * memory.u32(at); + } + for (size_t share = 0; share < 12; ++share) + assets += int64_t(word(t.stocks, share * 0x5c + 0x50 + size_t(d.manager_slot) * 2)) * word(t.stocks, share * 0x5c + 0x4e); + for (size_t loan = 0; loan < 5; ++loan) { + const auto at = ::bmh::layout::LoansUnsigned + uint32_t(d.manager_slot) * 0x78 + uint32_t(loan) * 0x18; + debt += int64_t(int32_t(memory.u32(at + 4))) - int32_t(memory.u32(at + 0x14)); + } + const auto licence = t.managers.at(base + 0x220); + d.warnings[9] = assets - debt + int64_t(t.managers.at(base + 0x26f)) * 80000 < -6000000 || + ((licence >> 5) == 2 && int64_t(licence & 31) * 100000 <= signed_word(t.managers, base + 0x330)); + + std::set visited; + const auto layout = ::bmh::layout::DesktopsUnsigned + uint32_t(d.manager_slot) * 0x360; + int current = memory.u8(layout + 5); + while (current != 0) { + if (current < 1 || current >= 54 || !visited.insert(current).second) + throw FormatError("desk: invalid/cyclic layout list"); + const auto at = layout + uint32_t(current) * 16; + const auto xflags = memory.u16(at); + if (!(xflags & 0x1000)) { + DeskItem item; + item.id = current; item.x = int16_t(xflags & ~0x1000); item.y = memory.u8(at + 2); + item.width = memory.u8(at + 3); item.height = memory.u8(at + 4); + item.kind = memory.u8(at + 12); item.flags = memory.u8(at + 13); + item.folder = item.flags & 0x7f; item.open = (item.flags & 0x80) != 0; + item.disabled = (memory.u8(at + 1) & 0x10) != 0; + // SourceDrawerTeam derives the three folder drawer dimensions from + // child count; stored layout dimensions are not authoritative. + const int drawer_kind = item.kind - 50; + if (drawer_kind >= 0 && drawer_kind < 3) { + const size_t count = d.folder_icon_slots[size_t(drawer_kind)].size(); + if (count > 12 || !exe.contains(::bmh::layout::DeskState_FormatError_ExecutableFieldUnsigned + uint32_t(count)) || + !exe.contains(::bmh::layout::DeskState_FormatError_ExecutableField2Unsigned + uint32_t(count))) + throw FormatError("desk: folder child count outside Source dimensions"); + item.width = exe.u8(::bmh::layout::DeskState_FormatError_ExecutableFieldUnsigned + uint32_t(count)); + item.height = exe.u8(::bmh::layout::DeskState_FormatError_ExecutableField2Unsigned + uint32_t(count)); + } + // Club-only finance, stadium, Toto and training screens require + // projections unavailable to a national coach. + if (d.national_team && (item.kind == 13 || item.kind == 14 || + item.kind == 15 || item.kind == 16 || + item.kind == 22)) item.disabled = true; + if (item.x < 0 || item.x > 319 || item.y > 239 || item.kind > 72) + throw FormatError("desk: invalid layout coordinates/type"); + d.items.push_back(item); + } + current = memory.u8(at + 5); + } + validate_desk_state(d); + return d; +} +std::vector words(const Bytes& data) { + if (data.size() % 2) throw FormatError("desk: odd word-table size"); + std::vector result; + for (size_t i = 0; i < data.size(); i += 2) result.push_back(le16(data, i)); + return result; +} +} // namespace + +void validate_desk_profile(const SetupOptions& o) { + if (o.managers < 1 || o.managers > 4 || o.difficulty < 0 || o.difficulty > 9 || + o.duration < 1 || o.duration > 5 || o.mode < 1 || o.mode > 3 || + (!o.league && !o.world) || (!o.league && o.managers != 1)) + throw FormatError("unsupported_desk_profile: invalid manager count or competition options"); +} + +void validate_desk_state(const DeskState& d) { + validate_desk_profile(d.options); + if (d.mailbox_shortcut && (d.mailbox_shortcut->id != 44 || + d.mailbox_shortcut->kind != 63 || d.mailbox_shortcut->x != 178 || d.mailbox_shortcut->y != 215 || + d.mailbox_shortcut->width != 12 || d.mailbox_shortcut->height != 11)) + throw FormatError("desk: invalid original mailbox shortcut"); + if (d.national_team && d.mailbox_notification_pending) + throw FormatError("desk: national runtime cannot auto-open the mailbox"); + if (d.menu_layout_shortcut && (d.menu_layout_shortcut->id != 53 || + d.menu_layout_shortcut->kind != 53 || d.menu_layout_shortcut->x != 286 || + d.menu_layout_shortcut->y != 215 || d.menu_layout_shortcut->width != 12 || + d.menu_layout_shortcut->height != 11)) + throw FormatError("desk: invalid original menu-layout shortcut"); + if (d.manager_teams.size() != size_t(d.options.managers) || d.managers.size() != size_t(d.options.managers) || d.manager_slot < 0 || + d.manager_slot >= d.options.managers || d.runtime_club != d.manager_teams[size_t(d.manager_slot)]) + throw FormatError("desk: inconsistent manager slot/runtime mapping"); + std::set unique, unique_identities; + for (size_t slot = 0; slot < d.manager_teams.size(); ++slot) { + const int team = d.manager_teams[slot]; + const auto& manager = d.managers[slot]; + if (team < 0 || !unique.insert(team).second || manager.runtime_club != team || + manager.club_identity_key < 0 || !unique_identities.insert(manager.club_identity_key).second || + manager.portrait < 0 || manager.portrait > 11 || + (team != kNoTeam && (manager.league < 0 || manager.league > 8))) + throw FormatError("desk: invalid or duplicate manager runtime club"); + } + const bool national = d.runtime_club == kNoTeam; + if (d.table_position && (*d.table_position < 0 || *d.table_position > 31)) + throw FormatError("desk: invalid Source table position"); + if (d.national_team != national || + (national && (d.manager_slot != 0 || d.options.managers != 1 || + (!d.options.world && !d.national_coach_takeover)))) + throw FormatError("desk: inconsistent national-team manager context"); + if (national && d.national_coach_takeover) { + if (d.national_return_roster.size() < 1 || d.national_return_roster.size() > 4) + throw FormatError("desk: missing national return roster"); + std::set return_keys; + for (const auto& manager : d.national_return_roster) + if (manager.runtime_club < 0 || manager.runtime_club >= kNoTeam || + manager.club_identity_key < 0 || !return_keys.insert(manager.club_identity_key).second || + manager.portrait < 0 || manager.portrait > 11 || manager.league < 0 || manager.league > 8) + throw FormatError("desk: invalid national return roster identity"); + const auto& active = d.managers[size_t(d.manager_slot)]; + if (std::none_of(d.national_return_roster.begin(), d.national_return_roster.end(), + [&](const DeskManagerIdentity& manager) { + return manager.club_identity_key == active.club_identity_key && + manager.name == active.name && manager.portrait == active.portrait; + })) + throw FormatError("desk: national manager does not match return roster"); + } else if (!d.national_return_roster.empty()) { + throw FormatError("desk: unexpected national return roster outside takeover"); + } + const auto& active = d.managers[size_t(d.manager_slot)]; + if (d.manager_name != active.name || d.portrait != active.portrait || d.league != active.league || d.badge != active.badge) + throw FormatError("desk: active manager identity does not match its slot projection"); +} + +DeskDate desk_date(uint32_t counter, const LeImage& exe) { + if (counter == 0xffff || counter > 3000000) throw FormatError("desk: unsupported date counter"); + DeskDate d; d.weekday = int((counter + 2) % 7); + int cycle = 3, years = 0; + while (counter > uint32_t(364 + (cycle == 4))) { + if (cycle == 4) { cycle = 0; --counter; } + ++years; counter -= 365; ++cycle; + } + d.month = 7; + auto month_days = [&] { return d.month == 2 ? 28 + (cycle == 4) : exe.u8(::bmh::layout::DeskState_DeskDate_RuntimeField + d.month); }; + while (counter > uint32_t(month_days())) { + counter -= uint32_t(month_days()); + if (++d.month == 13) { d.month = 1; ++years; } + } + d.day = int(counter) + 1; + if (d.day > month_days()) { + d.day -= month_days(); + if (++d.month == 13) { d.month = 1; ++years; } + } + d.year = 2026 + years; + return d; +} + +DeskState desk_from_save(const SaveState& s, const LeImage& exe, uint64_t revision) { + StaticMemory memory(s); + auto manager = block_copy(s, ::bmh::layout::ManagerRecords), tactics = block_copy(s, ::bmh::layout::TacticsBoards), options = block_copy(s, ::bmh::layout::ManagerAutomation); + auto stocks = block_copy(s, ::bmh::layout::StockExchange), badges = block_copy(s, ::bmh::layout::ClubBadgeSelectors), morale = block_copy(s, ::bmh::layout::TeamMorale); + auto offsets = words(block_copy(s, ::bmh::layout::ClubIdentities)), squads = words(block_copy(s, ::bmh::layout::SquadSlots)); + auto w1 = block_copy(s, ::bmh::layout::PlayerConditionTechniqueForm), w2 = block_copy(s, ::bmh::layout::PlayerSkillWords), w3 = block_copy(s, ::bmh::layout::PlayerIdentityWords); + std::vector players; + if (w1.size() != w2.size() || w1.size() != w3.size() || w1.size() % 4) throw FormatError("desk: inconsistent player tables"); + for (size_t at = 0; at < w1.size(); at += 4) players.push_back({{}, le32(w1, at), le32(w2, at), le32(w3, at)}); + std::vector teams; + for (int i = 0; i < memory.u8(::bmh::layout::ManagerCount); ++i) teams.push_back(word(manager, size_t(i) * 0xb0c + 0x290)); + auto rounds = block_copy(s, ::bmh::layout::LeagueRoundCounters); + auto d = project(memory, {manager, tactics, options, stocks, badges, s.pool(0), offsets, squads, players, morale, teams, rounds}, + exe, memory.u8(::bmh::layout::Difficulty), memory.u32(::bmh::layout::CalendarDay), memory.u16(::bmh::layout::DaysIntoSeason), int16_t(memory.u16(::bmh::layout::SeasonIndex)), revision); + GameState table_source; + const auto position_history = block_copy(s, ::bmh::layout::LeagueRankHistory); + const auto results_by_opponent = block_copy(s, ::bmh::layout::ManagerMatchHistory); + table_source.position_history = position_history; + table_source.league_rounds = rounds; + project_table_position(d, table_source); + project_drawer_rows(d, exe, manager, s.pool(0), offsets, position_history, + results_by_opponent, rounds, std::nullopt); + d.source = "original_save_read_only"; return d; +} + +DeskState desk_from_game(const GameState& g, const LeImage& exe, uint64_t revision, + const std::vector* current_groups, + std::optional source_default_competition, + const DeskMatchCallargs* source_callargs) { + auto d = project(g.memory, {g.manager_records, g.tactics, g.manager_options, g.stocks, g.club_heap_78, g.club_names, + g.club_ids, g.squad_slots, g.players, g.team_morale, g.manager_teams, g.league_rounds}, + exe, g.level, g.date, g.season_day(), g.season, revision); + // DeskDate only auto-opens for an ordinary club manager; the national + // runtime (0x165) suppresses this consumer while manual mailbox access remains valid. + if (d.runtime_club != kNoTeam && d.manager_slot >= 0 && d.manager_slot < 32 && g.memory.has(::bmh::layout::MailboxRecipientMask)) + d.mailbox_notification_pending = (g.memory.u32(::bmh::layout::MailboxRecipientMask) & (uint32_t(1) << d.manager_slot)) != 0; + project_table_position(d, g); + if (!current_groups && g.date == 0 && g.season == 0 && g.season_day() == 0 && g.texts) { + const size_t title = (::bmh::layout::DeskState_DeskFromGame_TextPointer - ::bmh::layout::TextPointerTable) / 4 + 33; + if (title < g.texts->strings.size()) d.next_competition_label = g.texts->strings[title]; + } + if (current_groups) { + // DayCompetitions2 defaults to 33, changes the fallback to 34 on a day with + // active competition bits, and uses 32 for the season-end desk. The + // adapter supplies that already-known desk state; this projection never + // prepares a fixture or advances a calendar day. + d.next_competition = source_default_competition.value_or(current_groups->empty() ? 33 : 34); + d.next_opponent = -1; + d.next_match_away = false; + if (source_callargs) { + d.next_competition = source_callargs->competition; + d.next_opponent = source_callargs->opponent; + } else { + const int team = d.manager_teams.at(size_t(d.manager_slot)); + for (const MatchGroup& group : *current_groups) { + const int type = group.desc.empty() ? -1 : group.desc.at(0); + int mapped_competition = -1; + int league = -1; + if (type == 0) { + league = int(le32(group.desc, 0xcc)); + // FixturesFromGenerateFixtures receives one of the nine league IDs represented + // by LeagueCalendarBits; the prepared group descriptor carries that ID. + if (league >= 0 && league < 9) mapped_competition = exe.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league)); + } else if (type > 0) { + // setup_cup_groups stores Source type + 1 in descriptor byte 0; + // MatchdayNeedsManagerDesks writes cup type + 5 to the desk array. + mapped_competition = type + 4; + } + for (size_t match = 0; match < size_t(group.matches()); ++match) { + const int home = group.fixtures.at(match * 2); + const int away = group.fixtures.at(match * 2 + 1); + if (team != home && team != away) continue; + // MatchdayNeedsManagerDesks checks the raw league result byte before writing + // the competition code. setup_matchday does not populate + // MatchGroup::results; kick_off normalizes g.results later. Use + // the group copy when present, otherwise read the authoritative + // raw season result at league*0x17c + round*10 + match. + bool has_result = false; + uint8_t raw_result = 0xcc; + if (type == 0 && match < group.results.size()) { + has_result = true; + raw_result = group.results[match]; + } else if (type == 0 && league >= 0 && + league < int(g.league_rounds.size())) { + const int round = int(g.league_rounds[size_t(league)]); + const size_t result_at = size_t(league) * 0x17c + + size_t(round) * 10 + match; + if (round >= 0 && result_at < g.results.size()) { + has_result = true; + raw_result = g.results[result_at]; + } + } + if (type == 0 && has_result && raw_result != 0xcc) { + d.next_opponent = -1; + d.next_opponent_name.clear(); + d.next_opponent_badge.reset(); + d.next_opponent_badge_fallback = false; + d.next_match_away = false; + continue; + } + // Source MatchdayNeedsManagerDesks walks groups and fixture slots in this + // order; each later matching group overwrites the prior desk + // values. Preserve that behavior for unusual overlapping events. + const int opponent = team == home ? away : home; + d.next_opponent = opponent; + if (mapped_competition >= 0) d.next_competition = mapped_competition; + } + } + } + if (d.next_opponent && *d.next_opponent >= 0) { + const size_t manager_record = size_t(d.manager_slot) * 0xb0c; + d.next_match_away = manager_record + 0x28a < g.manager_records.size() && + g.manager_records[manager_record + 0x28a] != 0; + } + if (d.next_opponent && *d.next_opponent >= 0 && + *d.next_opponent < int(g.club_ids.size())) { + const int opponent = *d.next_opponent; + d.next_opponent_name = g.club_name(opponent); + const bool fallback = opponent == 0x0fff || + (opponent > 0x59 && (opponent < 0x8a || opponent > 0xa7) && opponent < 0x165); + d.next_opponent_badge_fallback = fallback; + if (!fallback) { + const size_t badge_at = size_t(opponent) * 2; + if (badge_at + 1 >= g.club_heap_78.size()) + throw FormatError("desk: missing Source opponent badge selector"); + d.next_opponent_badge = uint16_t(g.club_heap_78[badge_at] | + (uint16_t(g.club_heap_78[badge_at + 1]) << 8)) & 0x1ff; + } else d.next_opponent_badge.reset(); + } else { + d.next_opponent_name.clear(); + d.next_opponent_badge.reset(); + d.next_opponent_badge_fallback = d.next_opponent && *d.next_opponent >= 0; + } + const int competition = d.next_competition.value_or(-1); + if (competition >= 0 && competition < 5) { + const size_t name_id = size_t((::bmh::layout::Achievements_FormatError_TextPointer3 - ::bmh::layout::TextPointerTable) / 4 + competition); + const size_t league = exe.u8(::bmh::layout::DeskState_FormatError_RuntimeField + uint32_t(competition)); + if (g.texts && name_id < g.texts->strings.size() && league < g.league_rounds.size()) { + d.next_competition_label = g.texts->strings[name_id] + "\n" + + std::to_string(int(g.league_rounds[league]) + 1) + g.texts->strings.at((::bmh::layout::CupDraw_FormatError_TextPointer6 - ::bmh::layout::TextPointerTable) / 4); + } + } else if (competition >= 5) { + size_t label_id = 0; + const uint32_t calendar_at = ::bmh::layout::CompetitionCalendar + uint32_t(std::max(0, g.season_day())) * 2; + if (g.season_day() >= 0 && g.season_day() < 365 && g.memory.has(calendar_at + 1) && + g.memory.u16(calendar_at) == 0x4006) { + label_id = (::bmh::layout::DeskState_FormatError_RuntimeField4 - ::bmh::layout::TextPointerTable) / 4; + } else if (competition < 30) { + label_id = (::bmh::layout::DeskState_FormatError_ExecutableField4 - ::bmh::layout::TextPointerTable) / 4 + size_t(competition); + } else { + label_id = (::bmh::layout::DeskState_DeskFromGame_TextPointer - ::bmh::layout::TextPointerTable) / 4 + size_t(competition); + } + if (g.texts && label_id < g.texts->strings.size()) d.next_competition_label = g.texts->strings[label_id]; + if (competition == 34 && !current_groups->empty()) { + for (const MatchGroup& group : *current_groups) { + if (!group.desc.empty() && group.desc.at(0) == 0) { + const int fallback_league = int(le32(group.desc, 0xcc)); + if (fallback_league >= 0 && fallback_league < 9) { + d.next_competition_detail = "(" + league_name(g, fallback_league) + ")"; + } + break; + } else if (!group.desc.empty() && group.desc.at(0) > 0) { + // SourceDrawerTeam reads these through the runtime TEXTD + // pointer table. Do not substitute LE-executable strings; + // the decompile's repeated-dereference condition for the + // optional prefix is unverified and is intentionally omitted. + const size_t name_id = size_t((::bmh::layout::DeskState_FormatError_ExecutableField3 - ::bmh::layout::TextPointerTable) / 4) + group.desc.at(0); + if (g.texts && name_id < g.texts->strings.size() && + !g.texts->strings[name_id].empty()) + d.next_competition_detail = "(" + g.texts->strings[name_id] + ")"; + break; + } + } + } + } + } + std::optional authenticated_rival; + if (source_callargs && source_callargs->opponent >= 0) + authenticated_rival = source_callargs->opponent; + else if (current_groups && d.next_opponent && *d.next_opponent >= 0) + authenticated_rival = *d.next_opponent; + project_drawer_rows(d, exe, g.manager_records, g.club_names, g.club_ids, + g.position_history, g.manager_results, g.league_rounds, + authenticated_rival, &g); + d.source = "engine_projection"; return d; +} + +DeskState load_reference_desk(const std::filesystem::path& path, const LeImage& exe) { + auto fbm = load_savegame(path); + if (!fbm.checksum_ok) throw FormatError("desk: FBM checksum mismatch"); + if (fbm.version != "V2.24") throw FormatError("desk: unsupported FBM version"); + DbCounts counts{exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)}; + SaveState save(fbm.stream, counts); + auto d = desk_from_save(save, exe); + validate_desk_state(d); + return d; +} + +std::string desk_json(const DeskState& d) { + std::ostringstream out; + out << "{\"screen\":\"desktop\",\"source\":" << json_quote(d.source) << ",\"revision\":" << d.revision + << ",\"options\":" << setup_json(d.options) << ",\"manager_slot\":" << d.manager_slot + << ",\"manager_name\":" << json_quote(original_to_utf8(d.manager_name)) << ",\"runtime_club\":" << d.runtime_club + << ",\"national_team\":" << (d.national_team ? "true" : "false") + << ",\"national_coach_takeover\":" << (d.national_coach_takeover ? "true" : "false") + << ",\"manager_teams\":["; + for (size_t i = 0; i < d.manager_teams.size(); ++i) { + if (i) out << ','; + out << d.manager_teams[i]; + } + out << "],\"managers\":["; + for (size_t i = 0; i < d.managers.size(); ++i) { + if (i) out << ','; + const auto& manager = d.managers[i]; + out << "{\"slot\":" << i << ",\"runtime_club\":" << manager.runtime_club + << ",\"club_identity_key\":" << manager.club_identity_key + << ",\"name\":" << json_quote(original_to_utf8(manager.name)) << ",\"league\":" << manager.league + << ",\"portrait\":" << manager.portrait << ",\"badge\":" << manager.badge << '}'; + } + out << "]" + << ",\"club_name\":" << json_quote(original_to_utf8(d.club_name)) << ",\"date\":{\"year\":" << d.date.year + << ",\"month\":" << d.date.month << ",\"day\":" << d.date.day << "},\"day_counter\":" << d.day_counter + << ",\"season_index\":" << d.season_index << ",\"season_day\":" << d.season_day << ",\"league_matchday\":null" + << ",\"balance\":" << d.balance << ",\"savings\":" << d.savings << ",\"table_position\":"; + if (d.table_position) out << *d.table_position; else out << "null"; + out << ",\"strength\":"; + if (d.strength) out << *d.strength; else out << "null"; + // The desk title index of DayCompetitions2 (next_competition): 33 = no competition today + // ("Saisonbeginn" on the very first day), 34 = competitions without the own club, 32 = the + // season-end desk, any other value = a match of the own club (issue #9). + const char* phase = "matchday"; + if (!d.next_competition) phase = "unknown"; + else if (*d.next_competition == 32) phase = "season_end"; + else if (*d.next_competition == 33) phase = d.day_counter == 0 ? "season_begin" : "free_day"; + else if (*d.next_competition == 34) phase = "free_day"; + out << ",\"phase\":" << json_quote(phase) << ",\"next_competition\":"; + if (d.next_competition) out << *d.next_competition; else out << "null"; + out << ",\"next_opponent\":"; + if (d.next_opponent) out << *d.next_opponent; else out << "null"; + out << ",\"next_match_away\":" << (d.next_match_away ? "true" : "false") + << ",\"next_competition_label\":" << json_quote(original_to_utf8(d.next_competition_label)) + << ",\"next_competition_detail\":" << json_quote(original_to_utf8(d.next_competition_detail)) + << ",\"next_opponent_name\":" << json_quote(original_to_utf8(d.next_opponent_name)) + << ",\"next_opponent_badge\":"; + if (d.next_opponent_badge) out << *d.next_opponent_badge; else out << "null"; + out << ",\"next_opponent_badge_fallback\":" << (d.next_opponent_badge_fallback ? "true" : "false"); + out << ",\"warnings\":["; + for (size_t i = 0; i < d.warnings.size(); ++i) { + if (i) out << ','; + if (d.warnings[i]) out << (*d.warnings[i] ? "true" : "false"); else out << "null"; + } + out << "],\"shortcut_bar_always\":" << (d.shortcut_bar_always ? "true" : "false") + << ",\"mailbox_notification_pending\":" << (d.mailbox_notification_pending ? "true" : "false") + << ",\"mailbox_shortcut_item\":"; + if (d.mailbox_shortcut) out << d.mailbox_shortcut->id; else out << "null"; + out << ",\"menu_layout_shortcut_item\":"; + if (d.menu_layout_shortcut) out << d.menu_layout_shortcut->id; else out << "null"; + out << ",\"layout\":["; + for (size_t i = 0; i < d.items.size(); ++i) { + if (i) out << ','; + const auto& item = d.items[i]; + out << "{\"id\":" << item.id << ",\"kind\":" << item.kind << ",\"x\":" << item.x << ",\"y\":" << item.y + << ",\"open\":" << (item.open ? "true" : "false") << ",\"disabled\":" << (item.disabled ? "true" : "false") << '}'; + } + out << "],\"engine_attached\":false}"; + return out.str(); +} +} // namespace bmh::ui diff --git a/src/ui/desk_state.hpp b/src/ui/desk_state.hpp new file mode 100644 index 0000000..459e15f --- /dev/null +++ b/src/ui/desk_state.hpp @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include + +#include "ui/setup.hpp" + +namespace bmh { struct GameState; class SaveState; } +namespace bmh { struct MatchGroup; } + +namespace bmh::ui { + +struct DeskItem { + int id = 0, x = 0, y = 0, width = 0, height = 0, kind = 0; + uint8_t flags = 0, folder = 0; + bool open = false, disabled = false; +}; + +struct DeskDate { int year = 0, month = 0, day = 0, weekday = 0; }; +struct DeskManagerIdentity { + int runtime_club = -1, club_identity_key = -1, league = -1, portrait = 0; + uint16_t badge = 0; + std::string name; + bool operator==(const DeskManagerIdentity&) const = default; +}; +struct DeskMatchCallargs { + int competition = 33, opponent = -1; + bool operator==(const DeskMatchCallargs&) const = default; +}; +struct DeskRankSample { + int matchday = 0; + int source_rank = -1; // TablePosition's zero-based 5-bit value. +}; +struct DeskRankCurve { + int runtime_team = -1; + int league = -1; + std::string team_name; + std::optional current_position, strength; + std::vector samples; +}; +struct DeskRecentMatch { + int home_team = -1, away_team = -1; + std::string home_name, away_name; + uint8_t source_score = 0xff; // Original packed byte, without inferred home/away reversal. +}; +struct DeskOpponentHistory { + int runtime_team = -1; + std::string team_name; + std::array source_results{}; // 5 home + 5 away nibbled result bytes. +}; +// Copyable, read-only rendering boundary. Runtime club IDs are not master IDs. +struct DeskState { + SetupOptions options; + int manager_slot = 0, runtime_club = -1, league = -1, portrait = 0; + // Authoritative slot -> runtime team mapping, copied from GameState::manager_teams. + std::vector manager_teams; + std::vector managers; + // Original active-club roster retained across the temporary national takeover. + // In a multiplayer career the visible national desk has only the coach in slot 0. + std::vector national_return_roster; + bool national_team = false; + // SwapManagerSlots2 temporary coach assignment (CoachActive). This can make + // a league-only, single-manager career temporarily project team 0x165. + bool national_coach_takeover = false; + std::string manager_name, club_name; + uint16_t badge = 0; + uint32_t day_counter = 0; + int season_index = 0, season_day = 0; + std::optional league_round, table_position, strength; + // Desk call arguments are not fully saved in FBM. -1 = confirmed no opponent; + // nullopt = unknown. The initial reference title is known only at career day zero. + std::optional next_competition, next_opponent; + // SourceDrawerTeam swaps the two match labels when the active manager's + // record +0x28a marks the club as the away side. + bool next_match_away = false; + // SourceDrawerTeam's independent pair-count gate: DeskState_FormatError_RuntimeField2==0 and record+28a!=0. + // Retained even without a next opponent; that separate gate is resolved + // by the renderer. Match-label home/away semantics remain independent. + bool paired_drawers_away_order = false; + // Source SourceDrawerTeam case 15: resolved only from the current prepared event. + std::string next_competition_label, next_competition_detail, next_opponent_name; + std::optional next_opponent_badge; + bool next_opponent_badge_fallback = false; + // Read-only contents for SourceDrawerTeam switch-local cases 0..4, 9..10, + // 0x0c, 0x10..0x11, and 0x14..0x15. Cases 0x0d and 0x16 are source-empty. Portrait/name are + // already supplied by `portrait` / `manager_name` for cases 0x12/0x13. + // Folder entries are native layout record IDs (1..30); their displayed + // dimensions are derived from EXE count tables, while saved layout records + // remain untouched. Rank samples and result bytes retain native encodings. + std::array, 54> layout_records{}; + std::array, 3> folder_icon_slots; + bool layout_snap = true; // CareerSession_DispatchDesktopLayout_RuntimeField2 == 0: Source snaps desktop drags to its grid. + std::array rank_curves; // Own club and authenticated current rival. + std::vector recent_matches; + std::vector opponent_histories; + DeskDate date; + int32_t balance = 0, savings = 0; + int ticket_price = 0, fans = 0; + int32_t money_numerator = 1, money_denominator = 1; + bool decorated_background = true, gradient_text = true, drawer_handles = true; + bool shortcut_bar_always = true; // DeskDate: DeskState_FormatError_RuntimeField3 == 0 sets afb86 bit 1. + std::optional mailbox_shortcut; // original item 44 / kind 63, including a hidden/foldered record + bool mailbox_notification_pending = false; // MailboxRecipientMask active-manager bit; transient, non-FBM + std::optional menu_layout_shortcut; // final bar cell returns native record 53/kind 72, then dispatches MEN + std::array automation{}; + std::array, 10> warnings{}; + std::vector items; // Original linked-list drawing / hit-test order. + std::string source; + uint64_t revision = 0; +}; + +// Original DeskDate2, including its four-year leap cycle and Wednesday epoch. +DeskDate desk_date(uint32_t day_counter, const LeImage& executable); +DeskState desk_from_save(const SaveState&, const LeImage&, uint64_t revision = 0); +// Uses authoritative typed fields where StaticMemory contains stale copies. +// Does not call enter_desk(), RNG, finance transactions or any engine mutator. +DeskState desk_from_game(const GameState&, const LeImage&, uint64_t revision, + const std::vector* current_groups = nullptr, + std::optional source_default_competition = std::nullopt, + const DeskMatchCallargs* source_callargs = nullptr); +DeskState load_reference_desk(const std::filesystem::path& save, const LeImage& executable); +std::string desk_json(const DeskState&); +void validate_desk_profile(const SetupOptions&); +void validate_desk_state(const DeskState&); + +} // namespace bmh::ui diff --git a/src/ui/desktop.cpp b/src/ui/desktop.cpp new file mode 100644 index 0000000..f3eb608 --- /dev/null +++ b/src/ui/desktop.cpp @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/desktop.hpp" + +#include +#include +#include + +#include "ui/manager.hpp" +#include "game/state.hpp" +#include "game/messages.hpp" + +namespace bmh::ui { +namespace { +void rect(Image& out, int x, int y, int w, int h, uint8_t color) { + for (int yy = std::max(0, y); yy < std::min(out.height, y + h); ++yy) + for (int xx = std::max(0, x); xx < std::min(out.width, x + w); ++xx) out.at(xx, yy) = color; +} +void copy(Image& out, const Image& src, int sx, int sy, int x, int y, int w, int h, bool transparent = false) { + if (sx < 0 || sy < 0 || sx + w > src.width || sy + h > src.height) + throw FormatError("desktop: sprite outside original atlas"); + for (int yy = 0; yy < h; ++yy) for (int xx = 0; xx < w; ++xx) { + const auto color = src.pixels[size_t(sy + yy) * src.width + sx + xx]; + if (x + xx >= 0 && y + yy >= 0 && x + xx < out.width && y + yy < out.height && (!transparent || color)) + out.at(x + xx, y + yy) = color; + } +} +void border(Image& out, int x, int y) { + rect(out, x - 1, y - 1, 40, 1, 0x46); rect(out, x - 1, y - 1, 1, 40, 0x46); + rect(out, x - 1, y + 38, 40, 1, 0x40); rect(out, x + 38, y - 1, 1, 40, 0x40); +} +std::string money(int64_t value) { + const bool negative = value < 0; + auto digits = std::to_string(negative ? -value : value); + for (int at = int(digits.size()) - 3; at > 0; at -= 3) digits.insert(size_t(at), "."); + const int separators = int(std::count(digits.begin(), digits.end(), '.')); + const int padding = std::max(0, 8 + separators - int(negative) - int(digits.size())); + digits.insert(0, size_t(padding), '%'); + // FormatGroupedDigits(0x88): percent glyphs pad a field; remaining groups add spaces. + digits.insert(0, size_t(std::max(0, 2 - separators)), ' '); + if (negative) digits.insert(0, "-"); + return digits; +} +const char* request_name(DeskRequestKind kind) { + switch (kind) { + case DeskRequestKind::none: return "none"; + case DeskRequestKind::open_menu: return "open_menu"; + case DeskRequestKind::advance_turn: return "advance_turn"; + case DeskRequestKind::change_layout: return "change_layout"; + case DeskRequestKind::change_option: return "change_option"; + case DeskRequestKind::change_ticket_price: return "change_ticket_price"; + case DeskRequestKind::end_session: return "end_session"; + } + return "none"; +} +const char* layout_operation_name(DeskLayoutOperation operation) { + switch(operation) { + case DeskLayoutOperation::none:return "none"; + case DeskLayoutOperation::move_item:return "move_item"; + case DeskLayoutOperation::set_folder:return "set_folder"; + case DeskLayoutOperation::toggle_quickbar_drawer:return "toggle_quickbar_drawer"; + case DeskLayoutOperation::return_folder_child:return "return_folder_child"; + case DeskLayoutOperation::send_to_folder:return "send_to_folder"; + case DeskLayoutOperation::restore_folder_child:return "restore_folder_child"; + } + return "none"; +} +} // namespace + +std::string_view desk_menu_name(int kind) { + // These menu kinds have original hotkey + screen observations in the laboratory. + switch (kind) { + case 0: return "league_table"; + case 1: return "league_pairings"; + case 53: return "menu_layout"; + case 63: return "mailbox"; + case 19: return "settings"; + case 20: return "top_scorers"; + case 25: return "fair_play"; + case 26: return "highscore"; + case 23: return "opportunities"; + case 21: return "advertising"; + case 3: return "lineup"; + case 15: return "training_camp"; + case 16: return "training"; + case 18: return "tactics"; + case 22: return "stadium"; + case 13: return "toto"; + case 14: return "bank"; + case 17: return "transfer_market"; + case 10: return "load_game"; + case 11: return "save_game"; + case 12: return "advance_turn"; + default: return "unknown"; + } +} + +std::string desk_request_json(const DeskRequest& r) { + std::ostringstream out; + out << "{\"kind\":" << json_quote(request_name(r.kind)) << ",\"manager_slot\":" << r.manager_slot + << ",\"item_id\":" << r.item_id << ",\"menu_kind\":" << r.menu_kind << ",\"value\":" << r.value + << ",\"revision\":" << r.revision << ",\"menu\":" << json_quote(desk_menu_name(r.menu_kind)) + << ",\"layout_operation\":" << json_quote(layout_operation_name(r.layout_operation)) + << ",\"layout_target_item\":" << r.layout_target_item << '}'; + return out.str(); +} + +DesktopScreen::DesktopScreen(const std::filesystem::path& data, DeskState state) + : data_(data), state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), + background_(load_vga(asset_path(data / "KB", "129.VGA"))), + icons_(load_vga(asset_path(data / "KB", "3.VGA"))), widgets_(load_vga(asset_path(data / "KB", "0.VGA"))), + portraits_(load_vga(asset_path(data / "KB", "26.VGA"))), letters_(load_vga(asset_path(data / "KB", "54.VGA"))), + small_(load_font(asset_path(data / "F", "BMH3.FNT"))), texts_(load_textd(asset_path(data, "TEXTD.BLK"))), drawers_(data) { + validate_desk_state(state_); + if (background_.width != 320 || background_.height != 240 || state_.portrait < 0 || state_.portrait > 11) + throw FormatError("desktop: unsupported assets/state"); + badge_ = load_vga(asset_path(data / "W", std::to_string(state_.badge >> 3) + ".VGA")); + if (state_.next_opponent && *state_.next_opponent >= 0 && state_.next_opponent_badge && + !state_.next_opponent_badge_fallback) { + const int selector = *state_.next_opponent_badge & 0x1ff; + next_opponent_badge_ = load_vga(asset_path(data / "W", std::to_string(selector >> 3) + ".VGA")); + } + shortcut_bar_visible_ = state_.shortcut_bar_always; +} + +void DesktopScreen::text(Image& out, int x, int baseline, std::string_view value, uint8_t color, int right) const { + const int width = small_.text_width(value); + if (right >= 0) x += (right - x) / 2 - width / 2; + if (x < 0 || x + width > out.width || baseline < 5 || baseline >= out.height) return; + Image mask(std::max(1, width), 6); small_.draw(mask, 0, 0, value, 1); + int gradient = 0; + while (gradient < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + gradient) != color) ++gradient; + for (int yy = 0; yy < 6; ++yy) for (int xx = 0; xx < width; ++xx) + if (mask.at(xx, yy)) out.at(x + xx, baseline - 5 + yy) = state_.gradient_text ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + gradient * 6 + yy) : color; +} +void DesktopScreen::sprite_text(Image& out, int x, int baseline, std::string_view value, int font) const { + for (unsigned char c : value) { + if (c <= 31 || c >= 128) continue; + const int glyph = exe_.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c); + if (!glyph) { x += 2; continue; } + const int sx = exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2), width = exe_.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - sx; + copy(out, letters_, sx, (font - 4) * 7, x, baseline - 6, width, 7, true); x += width; + } +} +void DesktopScreen::frame(Image& out, int x, int y, int w, int h) const { + if (w < 8 || h < 8) throw FormatError("desktop: invalid drawer size"); + for (int yy = 4; yy < h - 3; ++yy) for (int xx = 4; xx < w - 3; ++xx) + if (x + xx >= 0 && y + yy >= 0 && x + xx < out.width && y + yy < out.height) + out.at(x + xx, y + yy) = exe_.u8(::bmh::layout::Advertising_PatternRect_RuntimeField + ((yy - 4) % 16) * 16 + (xx - 4) % 16); + copy(out, widgets_, 0, 0, x, y, 4, 4); copy(out, widgets_, 4, 0, x + w - 4, y, 4, 4); + copy(out, widgets_, 0, 4, x, y + h - 4, 4, 4); copy(out, widgets_, 4, 4, x + w - 4, y + h - 4, 4, 4); + for (int k = 4; k < w - 4; k += 74) { + const int n = std::min(74, w - 4 - k); + copy(out, widgets_, 0, 104, x + k, y, n, 4); copy(out, widgets_, 0, 108, x + k, y + h - 4, n, 4); + } + for (int k = 4; k < h - 4; k += 96) { + const int n = std::min(96, h - 4 - k); + copy(out, widgets_, 0, 8, x, y + k, 4, n); copy(out, widgets_, 4, 8, x + w - 4, y + k, 4, n); + } +} +void DesktopScreen::digits(Image& out, int value, int sx, int sy, int w, int h, int x, int y, int base, int gap) const { + int count = 1; + for (int n = value; n >= base; n /= base) ++count; + int cursor = x - w + (w + gap) * count - ((w + gap) * count) / 2; + do { + // SelectsTransparentIndex -> UsesForTheseSprites: DesktopRuntimeField selects transparent index 0. + for (int yy = 0; yy < h; ++yy) for (int xx = 0; xx < w; ++xx) { + const auto color = icons_.pixels.at(size_t(sy + yy) * icons_.width + sx + (value % base) * w + xx); + if (color != 0 && cursor + xx >= 0 && cursor + xx < out.width && y + yy >= 0 && y + yy < out.height) + out.at(cursor + xx, y + yy) = color; + } + value /= base; cursor -= w + gap; + } while (value); +} + +void DesktopScreen::draw_item(Image& out, const DeskItem& item) const { + int x = item.x, y = item.y; + if (item.kind < 50) { + copy(out, icons_, (item.kind % 8) * 32, (item.kind / 8) * 25, x, y, 32, 25); + return; + } + if (item.open) { + frame(out, x, y, item.width, item.height); + // SourceDrawerTeam: the 4x4 drawer handle replaces the upper-left frame corner. + if (state_.drawer_handles) copy(out, icons_, 192, 95, x, y, 4, 4); + x += 4; y += 4; + } + if (drawers_.handles(item.kind)) { + drawers_.draw(out, state_, item, badge_, next_opponent_badge_, widgets_); + return; + } + switch (item.kind - 50) { + case 6: + for (int i = 0; i < 10; ++i) { + if (state_.warnings[i]) copy(out, icons_, 0, *state_.warnings[i] ? 111 : 118, x + (i % 5) * 7, y + (i / 5) * 7, 7, 7); + else text(out, x + (i % 5) * 7, y + (i / 5) * 7 + 5, "?", 0x5f); + } + break; + case 7: + copy(out, icons_, 8, 111, x + 1, y + 1, 88, 17); + rect(out, x + 10, y + 8, (state_.fans * 69) / 100 + 1, 2, 0x7a); + break; + case 8: + copy(out, icons_, 210, 111, x + 1, y + 1, 51, 52); + digits(out, state_.date.day, 90, 146, 12, 12, x + 22, y + 22, 10, 1); + digits(out, state_.date.weekday, 90, 158, 17, 5, x + 24, y + 15, 7, 1); + digits(out, state_.date.month - 1, 0, 163, 20, 5, x + 22, y + 36, 12, 1); + digits(out, state_.date.year, 90, 141, 4, 5, x + 22, y + 43, 10, 1); + break; + case 5: + copy(out, icons_, 0, 129, x + 1, y + 1, 89, 26); + rect(out, x + 35, y + 26, (state_.ticket_price - 8) * 3 + 1, 1, 0x7a); + text(out, x + 25, y + 6, money(state_.balance), exe_.u8(::bmh::layout::Desktop_Copy_TextPointer + int(state_.balance >= 0)), x + 96); + text(out, x + 25, y + 14, money(int64_t(state_.savings) * state_.money_numerator / state_.money_denominator), exe_.u8(::bmh::layout::Desktop_Copy_TextPointer2), x + 96); + break; + case 14: + for (int i = 0; i < 5; ++i) { + copy(out, icons_, 97, 111, x + 3 + i * 33, y + 2, 32, 30); + const auto value = state_.automation[i]; + if ((i == 4 ? value & 1 : value) != 0) copy(out, icons_, 129 + i * 16, 111, x + i * 33 + 10, y + 4, 17, 11); + // Individual automatic-formation dots need a separately verified renderer. + } + break; + case 15: + if (!state_.next_competition || state_.next_competition_label.empty()) { + text(out, x, y + 6, "?", 0x6a, x + 141); + } else { + const auto split = state_.next_competition_label.find('\n'); + text(out, x, y + 6, std::string_view(state_.next_competition_label).substr(0, split), 0x6a, x + 141); + if (split != std::string::npos) + text(out, x, y + 13, std::string_view(state_.next_competition_label).substr(split + 1), 0x6a, x + 141); + if (!state_.next_competition_detail.empty()) + text(out, x, y + 21, state_.next_competition_detail, 0x5f, x + 141); + } + if (state_.next_opponent && *state_.next_opponent != -1) { + const std::string& home = state_.next_match_away ? state_.next_opponent_name : state_.club_name; + const std::string& away = state_.next_match_away ? state_.club_name : state_.next_opponent_name; + text(out, x, y + 21, home, 0x5f, x + 141); + text(out, x, y + 27, exe_.cstring(::bmh::layout::DeskDrawers_Recent_TextPointer), 0x5f, x + 141); + text(out, x, y + 33, away, 0x5f, x + 141); + } + break; + case 18: + border(out, x + 1, y + 1); + copy(out, portraits_, (state_.portrait % 6) * 38, (state_.portrait / 6) * 38, x + 1, y + 1, 38, 38); + break; + case 19: text(out, x, y + 6, state_.manager_name, 0x5f); break; + case 13: case 22: + break; // SourceDrawerTeam default: these native kinds have no content. + default: throw FormatError("desktop: unsupported drawer kind"); + } +} + +Image DesktopScreen::render() const { + const auto& visible = layout_preview_ ? *layout_preview_ : state_; + auto out = visible.decorated_background ? background_ : Image(320, 240); + if (!state_.decorated_background) { + rect(out, 0, 4, 320, 13, 0x44); rect(out, 1, 5, 318, 11, 0x39); + } + rect(out, 0, 228, 320, 11, 0x44); + // SourceDrawerTeam draws all shadows before the linked-list contents. + for (const auto& item : visible.items) if (item.kind < 50 || item.open) { + rect(out, item.x + 2, item.y + item.height, item.width, 2, 0x40); + rect(out, item.x + item.width, item.y + 2, 2, item.height, 0x40); + } + for (const auto& item : visible.items) draw_item(out, item); + // SourceDrawerTeam's compact drawer bar. Typed layout requests cover all + // native drawer records; MEN remains a separate file-picker action. + if (shortcut_bar_visible_) { + copy(out, icons_, 0, 100, 0x16, 0xd7, 0x114, 0xb); + copy(out, icons_, exe_.u8(::bmh::layout::Desktop_Render_RuntimeField + uint32_t(bin_mode_)), + exe_.u8(::bmh::layout::Desktop_Render_RuntimeField2 + uint32_t(bin_mode_)), 1, 0xcf, 0x14, 0x14); + copy(out, icons_, exe_.u8(::bmh::layout::Desktop_Render_RuntimeField3 + uint32_t(socket_confirmation_armed_)), + 0x4b, 299, 0xcf, 0x14, 0x14); + if (shortcut_hover_record_ >= 0) + text(out, 0, 235, texts_[text_id(::bmh::layout::Desktop_Render_TextPointer + uint32_t(shortcut_hover_record_) * 4)], 0x5f, 319); + } + return out; +} + +std::optional DesktopScreen::folder_child_at(int x,int y) const { + for(auto it=state_.items.rbegin();it!=state_.items.rend();++it) { + const auto& folder=*it; + // DeskDate LAB131af checks the current top record's bounds before + // looking for its children; LAB131a1 follows +6 only on a miss. + // An overlaid icon/drawer, including an empty part of another folder, + // therefore owns the hit instead of exposing a lower folder child. + const int inset = folder.kind >= 50 && !folder.open ? 8 : 0; + if (x < folder.x || y < folder.y || x >= folder.x + folder.width - inset || + y >= folder.y + folder.height - inset) continue; + if(folder.disabled||folder.kind<50||folder.kind>52||!folder.open) return std::nullopt; + const int folder_id=folder.kind-50,left=folder.x+9,top=folder.y+8,right=folder.x+folder.width-4,bottom=folder.y+folder.height-4; + int child_x=left,child_y=top; + for(uint8_t id:state_.folder_icon_slots[size_t(folder_id)]) { + if(child_x+32>right) child_x=left,child_y+=27; + if(child_y+25>bottom) break; + if(x>=child_x&&x=child_y&&y30) return std::nullopt; + const auto& raw=state_.layout_records[id]; + return DeskItem{int(id),child_x,child_y,32,25,raw[12],raw[0],uint8_t(raw[13]&0x7f),false,false}; + } + child_x+=34; + } + return std::nullopt; + } + return std::nullopt; +} + +DeskRequest DesktopScreen::pointer_down(int x, int y, bool right) { + if (pending_) return {}; + if (socket_release_pending_) return {}; // DeskDate waits here for the first RMB release. + sample_shortcut_pointer(x, y); + shortcut_hover_record_ = -1; // DeskDate clears its tooltip on event2/event8 before dispatch. + const bool socket_hit = shortcut_bar_visible_ && right && x > 0x12a && x < 0x13f && + y > 0xce && y < 0xe3; + if (socket_confirmation_armed_) { + if (socket_hit && !socket_release_pending_) { + DeskRequest action{DeskRequestKind::end_session, state_.manager_slot, -1, -1, -1, state_.revision}; + pending_ = action; + socket_confirmation_armed_ = false; + return action; + } + // DeskDate abandons the pressed socket when the next event is elsewhere. + if (!socket_hit) socket_confirmation_armed_ = false; + } + if (socket_hit) { + socket_confirmation_armed_ = true; + socket_release_pending_ = true; + return {}; + } + layout_drag_.reset(); layout_preview_.reset(); + if(const auto child=folder_child_at(x,y)) { + if(!right||!state_.drawer_handles||bin_mode_) return {}; + layout_drag_=LayoutDrag{child->id,x-child->x,y-child->y,child->x,child->y,child->folder,false,true,false,right}; + layout_preview_=state_; + auto& slots=layout_preview_->folder_icon_slots[size_t(child->folder)]; + slots.erase(std::remove(slots.begin(),slots.end(),uint8_t(child->id)),slots.end()); + layout_preview_->items.push_back(*child); + // RestoresChildBinMode restores the child, then LAB12dbc unlinks/appends it. + sound_ids_.insert(sound_ids_.end(), {15, 12, 15}); + return {}; + } + for (auto it = state_.items.rbegin(); it != state_.items.rend(); ++it) { + const auto& item = *it; + const int inset = item.kind >= 50 && !item.open ? 8 : 0; + if (item.disabled || x < item.x || y < item.y || x >= item.x + item.width - inset || + y >= item.y + item.height - inset) continue; + if (right && !state_.drawer_handles) return {}; + if (right && bin_mode_ && item.kind!=12) return {}; + if (!right && item.kind==55 && item.open && !state_.national_team && + x-item.x-4>34 && x-item.x-4<87) return {}; // Original ticket-price scale. + if (!right && item.kind==64 && item.open) return {}; // Source automation controls remain clicks. + const bool drawer_handle=item.kind>=50&&state_.drawer_handles&&x<=item.x+3&&y<=item.y+3; + if(item.kind>=50&&!drawer_handle&&!right) return {}; + if(!right&&!drawer_handle) return {}; // Source LMB activates; RMB starts a drag. + layout_drag_ = LayoutDrag{item.id, x - item.x, y - item.y, item.x, item.y, -1, false, false, drawer_handle, right}; + layout_preview_ = state_; + // RemovesBinModeIcon/RestoresChildBinMode run at RMB press, even if no motion follows. + // The existing LMB handle drag differs from that Source path; do not + // invent its sound mapping here. + if (right) sound_ids_.insert(sound_ids_.end(), {12, 15}); + return {}; + } + return {}; +} + +bool DesktopScreen::pointer_move(int x, int y) { + if (pending_ || socket_release_pending_) return false; + if (!layout_drag_ || !layout_preview_) return sample_shortcut_pointer(x, y); + auto& drag = *layout_drag_; + auto found = std::find_if(layout_preview_->items.begin(), layout_preview_->items.end(), + [&](const DeskItem& item) { return item.id == drag.item; }); + if (found == layout_preview_->items.end()) return false; + int next_x = x - drag.grab_x, next_y = y - drag.grab_y; + if (state_.layout_snap) { next_x = (next_x / 5) * 5; next_y = (next_y / 5) * 5; } + const int max_x=std::max(1,319-found->width), max_y=std::max(1,239-found->height); + next_x = std::clamp(next_x, 1, max_x); + next_y = std::clamp(next_y, 1, max_y); + drag.moved |= next_x != drag.start_x || next_y != drag.start_y; + const bool changed = found->x != next_x || found->y != next_y; + found->x = next_x; found->y = next_y; + return changed; +} + +DeskRequest DesktopScreen::pointer_up(int x, int y, bool right) { + if (socket_release_pending_) { + if (right) socket_release_pending_ = false; + return {}; // First socket RMB release is only the Source wait barrier. + } + if (!layout_drag_) return click(x, y, right); + const auto drag = *layout_drag_; + layout_drag_.reset(); + if (right!=drag.right_button) { layout_preview_.reset(); return {}; } + if (!drag.moved || !layout_preview_) { + layout_preview_.reset(); + if(drag.drawer_handle) return {}; // Source handle release is not a body click. + return click(x,y,right); + } + const auto source = std::find_if(state_.items.begin(), state_.items.end(), + [&](const DeskItem& item) { return item.id == drag.item; }); + const auto preview = std::find_if(layout_preview_->items.begin(), layout_preview_->items.end(), + [&](const DeskItem& item) { return item.id == drag.item; }); + const DeskItem* source_item=nullptr; + if(source!=state_.items.end()) source_item=&*source; + else if(drag.folder_child) { + const auto found=std::find_if(layout_preview_->items.begin(),layout_preview_->items.end(),[&](const DeskItem& item){return item.id==drag.item;}); + if(found!=layout_preview_->items.end()) source_item=&*found; + } + if (!source_item || preview == layout_preview_->items.end()) { layout_preview_.reset(); return {}; } + auto before = std::array{}; + auto after = before; + for (size_t i=0;i<54;++i) { + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),before.begin()+i*16); + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),after.begin()+i*16); + } + auto* record = after.data() + size_t(drag.item)*16; + const auto xflags = uint16_t(record[0]) | (uint16_t(record[1]) << 8); + const auto native_x = uint16_t((xflags & 0x1000) | uint16_t(preview->x)); + record[0]=uint8_t(native_x); record[1]=uint8_t(native_x>>8); record[2]=uint8_t(preview->y); + const DeskItem* drop = nullptr; + for (auto it=state_.items.rbegin();it!=state_.items.rend();++it) { + if (it->id == drag.item || it->disabled || it->kind < 50 || it->kind > 52) continue; + if (preview->x >= it->x && preview->x + 32 <= it->x+it->width && + preview->y >= it->y && preview->y + 25 <= it->y+it->height) { drop=&*it; break; } + } + DeskLayoutOperation op = DeskLayoutOperation::move_item; + int target = -1; + if (drop && source_item->kind < 50) { + // SourceDrawerTeam records drawer membership in the low seven bits of +13; + // a folder child is absent from the visible next-link chain (+5 == ff). + const int folder = drop->kind - 50; + const int folder_count=std::count_if(state_.layout_records.begin()+1,state_.layout_records.begin()+31, + [&](const auto& candidate){return candidate[5]==0xff && (candidate[1]&0x10)==0 && + (candidate[13]&0x7f)==folder;}); + const bool already_in_folder=drag.folder_child&&drag.folder==folder; + if (folder >= 0 && folder < 3 && drag.item <= 30 && + (state_.layout_records[size_t(drag.item)][1]&0x10)==0 && folder_count-(already_in_folder?1:0) < 12) { + const uint8_t previous = record[6], next = record[5]; + if (previous < 54) after[size_t(previous)*16+5] = next; + if (next > 0 && next < 54) after[size_t(next)*16+6] = previous; + record[13] = uint8_t((record[13] & 0x80) | folder); + record[5] = 0xff; + record[6] = 0xff; + op = DeskLayoutOperation::set_folder; target=drop->id; + } + } + auto req = request(DeskRequestKind::change_layout,*source_item); + if(drag.folder_child&&op==DeskLayoutOperation::move_item) { + op=DeskLayoutOperation::return_folder_child;target=drag.folder; + int tail=0;size_t guard=0; + while(after[size_t(tail)*16+5]!=0) { + if(++guard>=54) { layout_preview_.reset();return {}; } + tail=after[size_t(tail)*16+5];if(tail<0||tail>=54){layout_preview_.reset();return {};} + } + if(record[5]!=0xff||record[6]!=0xff) { layout_preview_.reset();return {}; } + record[5]=0;record[6]=uint8_t(tail);after[size_t(tail)*16+5]=uint8_t(drag.item); + } + req.layout_operation=op; req.layout_target_item=target; + req.layout_before=before; req.layout_after=after; + pending_=req; + if (op == DeskLayoutOperation::set_folder) sound_ids_.push_back(12); + layout_preview_.reset(); + return req; +} + +std::vector DesktopScreen::take_sound_ids() const { + std::vector result; + result.swap(sound_ids_); + return result; +} + +DeskRequest DesktopScreen::request(DeskRequestKind kind, const DeskItem& item, int value) { + DeskRequest r{kind, state_.manager_slot, item.id, item.kind, value, state_.revision}; + shortcut_hover_record_ = -1; + pending_ = r; last_rejection_.clear(); return r; +} +DeskRequest DesktopScreen::process_timer_expired() { + if (pending_ || layout_drag_ || socket_release_pending_) return {}; + // DeskDate consumes the shared Source event8 without selecting a menu icon. + pending_ = DeskRequest{DeskRequestKind::advance_turn, state_.manager_slot, + -1, 12, -1, state_.revision}; + shortcut_hover_record_ = -1; + last_rejection_.clear(); + return *pending_; +} +bool DesktopScreen::sample_shortcut_pointer(int x, int y) { + const bool visible_before = shortcut_bar_visible_; + const int hover_before = shortcut_hover_record_; + // DeskDate samples this before checking event2/event8. Only entry into + // y239 toggles afb86 bit0; the saved Always option owns independent bit1. + if (y == 239 && shortcut_last_y_ != 239) shortcut_bar_edge_toggle_ = !shortcut_bar_edge_toggle_; + shortcut_last_y_ = y; + shortcut_bar_visible_ = state_.shortcut_bar_always || shortcut_bar_edge_toggle_; + shortcut_hover_record_ = -1; + if (shortcut_bar_visible_ && x > 21 && x < 298 && y > 214 && y < 228) { + const int kind = (x - 22) / 12 + 50; + for (size_t i = 0; i < state_.layout_records.size(); ++i) + if (state_.layout_records[i][12] == kind) { shortcut_hover_record_ = int(i); break; } + } + return visible_before != shortcut_bar_visible_ || hover_before != shortcut_hover_record_; +} +DeskRequest DesktopScreen::click(int x, int y, bool right) { + if (pending_) return {}; + sample_shortcut_pointer(x, y); + if (shortcut_bar_visible_ && x > 0 && x < 0x15 && y > 0xce && y < 0xe3) { + bin_mode_ = !bin_mode_; + return {}; + } + if (y == 0xef) return {}; // Pointer sampling already handled the Source edge transition. + if (shortcut_bar_visible_ && x > 0x15 && x < 0x12a && y > 0xd6 && y < 0xe4) { + const int source_cell = (x - 0x16) / 12 + 50; + if (source_cell == 72 && state_.menu_layout_shortcut) { + auto action=request(DeskRequestKind::open_menu,*state_.menu_layout_shortcut,right ? 0 : 1); + action.menu_kind=53; pending_=action; return action; + } + if (!right && source_cell == 63 && state_.mailbox_shortcut) + return request(DeskRequestKind::open_menu, *state_.mailbox_shortcut); + if (source_cell >= 50 && source_cell <= 71) { + int record_id = -1; + for (size_t i = 0; i < state_.layout_records.size(); ++i) + if (state_.layout_records[i][12] == source_cell) { record_id = int(i); break; } + if (record_id >= 0) { + DeskItem target; target.id=record_id; target.kind=source_cell; + auto req=request(DeskRequestKind::change_layout,target,right ? 8 : 2); + req.layout_operation=DeskLayoutOperation::toggle_quickbar_drawer; + req.layout_target_item=record_id; + for(size_t i=0;i<54;++i) { + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),req.layout_before.begin()+i*16); + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),req.layout_after.begin()+i*16); + } + auto* record=req.layout_after.data()+size_t(record_id)*16; + const bool append = record[5]==0xff; + if(record[5]==0xff) { + int tail=0; + size_t guard=0; + while(req.layout_after[size_t(tail)*16+5]!=0) { + if(++guard>=54) return {}; + tail=req.layout_after[size_t(tail)*16+5]; + if(tail<0 || tail>=54) return {}; + } + record[5]=0; record[6]=uint8_t(tail); + req.layout_after[size_t(tail)*16+5]=uint8_t(record_id); + const bool opened=!(right && record_id>2); + record[13]=uint8_t((record[13]&0x7f)|(opened?0x80:0)); + } else { + const uint8_t previous=record[6],next=record[5]; + if(previous<54) req.layout_after[size_t(previous)*16+5]=next; + if(next!=0 && next<54) req.layout_after[size_t(next)*16+6]=previous; + record[5]=record[6]=0xff; + } + sound_ids_.push_back(append ? 15 : 12); + pending_=req; return req; + } + } + return {}; // Bar input must never leak into an underlying drawer. + } + if(const auto child=folder_child_at(x,y)) { + if(right&&bin_mode_&&state_.drawer_handles) { + auto req=request(DeskRequestKind::change_layout,*child); + req.layout_operation=DeskLayoutOperation::restore_folder_child; + req.layout_target_item=child->folder; + for(size_t i=0;i<54;++i) + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),req.layout_before.begin()+i*16); + req.layout_after=req.layout_before; + auto* record=req.layout_after.data()+size_t(child->id)*16; + int tail=0;size_t guard=0; + while(req.layout_after[size_t(tail)*16+5]!=0) { + if(++guard>=54) { pending_.reset();return {}; } + tail=req.layout_after[size_t(tail)*16+5]; + if(tail<0||tail>=54) { pending_.reset();return {}; } + } + record[5]=0;record[6]=uint8_t(tail); + req.layout_after[size_t(tail)*16+5]=uint8_t(child->id); + sound_ids_.push_back(15); // RestoresChildBinMode restores the child in bin mode. + pending_=req;return req; + } + if(right) return {}; + return request(child->kind==12?DeskRequestKind::advance_turn:DeskRequestKind::open_menu,*child); + } + for (auto it = state_.items.rbegin(); it != state_.items.rend(); ++it) { + const auto& item = *it; + const int inset = item.kind >= 50 && !item.open ? 8 : 0; + if (x < item.x || y < item.y || x >= item.x + item.width - inset || y >= item.y + item.height - inset) continue; + if(right&&bin_mode_&&state_.drawer_handles&&item.id>0&&item.id<=30&&item.kind<50&&item.kind!=12) { + const auto& record=state_.layout_records[size_t(item.id)]; + const int folder=int(record[13]&0x7f),previous=record[6],next=record[5]; + if(folder>=0&&folder<3&&record[5]!=0xff&&previous<54&&(next==0||next<54)) { + auto req=request(DeskRequestKind::change_layout,item); + req.layout_operation=DeskLayoutOperation::send_to_folder; + req.layout_target_item=folder; + for(size_t i=0;i<54;++i) + std::copy(state_.layout_records[i].begin(),state_.layout_records[i].end(),req.layout_before.begin()+i*16); + req.layout_after=req.layout_before; + req.layout_after[size_t(previous)*16+5]=uint8_t(next); + if(next!=0)req.layout_after[size_t(next)*16+6]=uint8_t(previous); + req.layout_after[size_t(item.id)*16+5]=req.layout_after[size_t(item.id)*16+6]=0xff; + sound_ids_.push_back(12); // RemovesBinModeIcon removes the bin-mode icon. + pending_=req;return req; + } + } + if (item.disabled || right) return {}; + if (item.kind < 50) return request(item.kind == 12 ? DeskRequestKind::advance_turn : DeskRequestKind::open_menu, item); + // DeskDate only handles Ticket/Calendar/Automation body clicks; + // drawer open/close is exclusively the compact quickbar operation. + if (item.open && state_.drawer_handles && x <= item.x + 3 && y <= item.y + 3) return {}; + if (item.kind == 58 && item.open) return request(DeskRequestKind::advance_turn, item); + if (item.kind == 55 && item.open && !state_.national_team && x - item.x - 4 > 34 && x - item.x - 4 < 87) + return request(DeskRequestKind::change_ticket_price, item, (x - item.x - 4 - 35) / 3 + 8); + if (item.kind == 64 && item.open) return request(DeskRequestKind::change_option, item, std::clamp((x - item.x - 4) / 33, 0, 4)); + return {}; // Noninteractive status fields must not invent layout/game changes. + } + return {}; +} +DeskRequest DesktopScreen::key(std::string_view key) { + if (pending_ || socket_release_pending_) return {}; + // DeskDate only confirms after the next event is the socket RMB; any key + // event after its first release abandons the confirmation state. + if (socket_confirmation_armed_) socket_confirmation_armed_ = false; + if (key.size() != 1) return {}; + auto c = uint8_t(key[0]); + if (c >= 'A' && c <= 'Z') c = uint8_t(c + ('a' - 'A')); + for (int menu = 0; menu < 30; ++menu) if (exe_.u8(::bmh::layout::Desktop_Key_RuntimeField + menu) == c && c) { + for (const auto& item : state_.items) + if (item.kind == menu && !item.disabled) + return request(menu == 12 ? DeskRequestKind::advance_turn : DeskRequestKind::open_menu, item); + } + return {}; +} +void DesktopScreen::acknowledge(DeskState updated) { + validate_desk_state(updated); + if (!pending_ || updated.revision <= state_.revision || + (updated.manager_slot != state_.manager_slot && pending_->kind != DeskRequestKind::advance_turn)) + throw FormatError("desktop: expected a newer state with the same manager roster"); + const bool turn_handoff = pending_->kind == DeskRequestKind::advance_turn; + const bool previous_national = state_.national_team && + (state_.options.world || state_.national_coach_takeover); + const bool incoming_national = updated.national_team && + (updated.options.world || updated.national_coach_takeover); + const bool national_transition = turn_handoff && (previous_national || incoming_national); + const bool options_match = updated.options == state_.options || + (national_transition && updated.options.duration == state_.options.duration && + updated.options.difficulty == state_.options.difficulty && updated.options.mode == state_.options.mode && + updated.options.league == state_.options.league && updated.options.world == state_.options.world); + if (!options_match) throw FormatError("desktop: career options changed during the turn"); + if (updated.manager_teams != state_.manager_teams && !turn_handoff) + throw FormatError("desktop: manager runtime mapping changed unexpectedly"); + const auto same_identity = [](const DeskManagerIdentity& a, const DeskManagerIdentity& b) { + return a.club_identity_key == b.club_identity_key && a.name == b.name && a.portrait == b.portrait; + }; + if (!turn_handoff && state_.national_coach_takeover && + (updated.national_return_roster.size() != state_.national_return_roster.size() || + !std::equal(state_.national_return_roster.begin(), state_.national_return_roster.end(), + updated.national_return_roster.begin(), same_identity))) + throw FormatError("desktop: national return roster changed unexpectedly"); + if (national_transition && incoming_national) { + const auto& baseline = previous_national && !state_.national_return_roster.empty() + ? state_.national_return_roster : state_.managers; + if ((updated.national_coach_takeover && baseline.size() != updated.national_return_roster.size()) || + updated.managers.size() != 1 || + (!updated.national_return_roster.empty() && + !std::equal(baseline.begin(), baseline.end(), updated.national_return_roster.begin(), same_identity)) || + std::none_of(baseline.begin(), baseline.end(), [&](const auto& manager) { + return same_identity(manager, updated.managers[0]); + })) + throw FormatError("desktop: national coach does not match the current manager roster"); + } else if (national_transition && previous_national) { + const auto& baseline = state_.national_return_roster.empty() ? state_.managers : state_.national_return_roster; + if (updated.managers.size() != baseline.size() || + !std::equal(updated.managers.begin(), updated.managers.end(), baseline.begin(), same_identity) || + std::none_of(baseline.begin(), baseline.end(), [&](const auto& manager) { + return same_identity(manager, state_.managers[0]); + })) + throw FormatError("desktop: handback does not restore the manager roster"); + } else { + if (updated.managers.size() != state_.managers.size()) + throw FormatError("desktop: manager roster changed unexpectedly"); + for (size_t slot=0;slot> 3) != (state_.badge >> 3)) + next_badge = load_vga(asset_path(data_ / "W", std::to_string(updated.badge >> 3) + ".VGA")); + shortcut_bar_visible_ = updated.shortcut_bar_always || shortcut_bar_edge_toggle_; + state_ = std::move(updated); badge_ = std::move(next_badge); + pending_.reset(); last_rejection_.clear(); +} +void DesktopScreen::acknowledge_mailbox_parent(DeskState updated) { + validate_desk_state(updated); + const bool revision_ok = updated.revision == state_.revision || + (state_.revision != std::numeric_limits::max() && updated.revision == state_.revision + 1); + if (pending_ || updated.source != "engine_projection" || + updated.manager_slot != state_.manager_slot || updated.runtime_club != state_.runtime_club || + !revision_ok || + (state_.mailbox_notification_pending == false && updated.mailbox_notification_pending)) + throw FormatError("desktop: mailbox parent refresh has a stale owner or revision"); + auto expected = state_; + expected.revision = updated.revision; + expected.mailbox_notification_pending = updated.mailbox_notification_pending; + if (desk_json(expected) != desk_json(updated)) + throw FormatError("desktop: mailbox parent refresh changed unrelated desk state"); + // Keep shortcut-bar visibility and bin mode: DeskDate returns from + // MailboxStateFromGame inside the existing desk loop, without reconstructing it. + state_ = std::move(updated); +} +void DesktopScreen::reject_action(std::string reason) { + if (!pending_ || reason.empty()) throw FormatError("desktop: rejection requires a pending action and reason"); + last_rejection_ = std::move(reason); pending_.reset(); +} +void DesktopScreen::resolve_local_menu() { + if (!pending_ || pending_->kind != DeskRequestKind::open_menu || + (pending_->menu_kind != 0 && pending_->menu_kind != 1 && pending_->menu_kind != 2 && pending_->menu_kind != 4 && pending_->menu_kind != 5 && pending_->menu_kind != 6 && pending_->menu_kind != 7 && pending_->menu_kind != 8 && pending_->menu_kind != 9 && pending_->menu_kind != 24 && pending_->menu_kind != 25 && pending_->menu_kind != 26 && pending_->menu_kind != 28 && pending_->menu_kind != 53 && pending_->menu_kind != 63 && pending_->menu_kind != 19 && pending_->menu_kind != 20 && pending_->menu_kind != 21 && pending_->menu_kind != 27 && pending_->menu_kind != 3 && pending_->menu_kind != 10 && pending_->menu_kind != 11 && pending_->menu_kind != 13 && pending_->menu_kind != 14 && pending_->menu_kind != 15 && pending_->menu_kind != 16 && pending_->menu_kind != 17 && pending_->menu_kind != 18 && pending_->menu_kind != 22 && pending_->menu_kind != 23 && pending_->menu_kind != 29)) + throw FormatError("desktop: no supported local-menu navigation pending"); + pending_.reset(); +} + +std::string DesktopScreen::state_json() const { + auto out = desk_json(state_); out.pop_back(); + out += ",\"shortcut_bar_visible\":" + std::string(shortcut_bar_visible_ ? "true" : "false") + + ",\"shortcut_hover_record\":" + std::to_string(shortcut_hover_record_) + + ",\"socket_confirmation_armed\":" + std::string(socket_confirmation_armed_ ? "true" : "false") + + ",\"bin_mode\":" + std::string(bin_mode_ ? "true" : "false") + + ",\"pending_action\":" + (pending_ ? desk_request_json(*pending_) : "null") + + ",\"last_rejection\":" + (last_rejection_.empty() ? "null" : json_quote(last_rejection_)) + "}"; + return out; +} +} // namespace bmh::ui diff --git a/src/ui/desktop.hpp b/src/ui/desktop.hpp new file mode 100644 index 0000000..69daa33 --- /dev/null +++ b/src/ui/desktop.hpp @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/textd.hpp" +#include "ui/desk_state.hpp" +#include "ui/desk_drawers.hpp" + +namespace bmh::ui { + +enum class DeskRequestKind { none, open_menu, advance_turn, change_layout, change_option, change_ticket_price, end_session }; +enum class DeskLayoutOperation : uint8_t { none, move_item, set_folder, toggle_quickbar_drawer, return_folder_child, send_to_folder, restore_folder_child }; +struct DeskRequest { + DeskRequestKind kind = DeskRequestKind::none; + int manager_slot = -1, item_id = -1, menu_kind = -1, value = -1; + uint64_t revision = 0; + DeskLayoutOperation layout_operation = DeskLayoutOperation::none; + int layout_target_item = -1; + std::array layout_before{}; + std::array layout_after{}; + bool operator==(const DeskRequest&) const = default; +}; +std::string desk_request_json(const DeskRequest&); +std::string_view desk_menu_name(int kind); + +// Read-only state + local UI presentation. Engine changes are explicit requests. +// A request waits for acknowledgement; repeated input never advances time twice. +class DesktopScreen { +public: + DesktopScreen(const std::filesystem::path& data, DeskState state); + Image render() const; + DeskRequest click(int x, int y, bool right = false); + DeskRequest pointer_down(int x, int y, bool right = false); + bool pointer_move(int x, int y); + DeskRequest pointer_up(int x, int y, bool right = false); + DeskRequest key(std::string_view key); + DeskRequest process_timer_expired(); // Original event8, no synthetic icon click + // Ordered Source sound-ID boundary; the application owns playback/options. + std::vector take_sound_ids() const; + const DeskState& state() const { return state_; } + const std::optional& pending() const { return pending_; } + bool socket_confirmation_armed() const { return socket_confirmation_armed_; } + void acknowledge(DeskState updated); // strictly newer authoritative revision + void acknowledge_mailbox_parent(DeskState updated); // refresh a mailbox's parent without losing local presentation state + void reject_action(std::string reason); // rejection changes no game state + void resolve_local_menu(); // consume only a verified open_menu presentation request + std::string state_json() const; +private: + std::filesystem::path data_; + DeskState state_; + LeImage exe_; + Image background_, icons_, widgets_, portraits_, badge_, letters_; + std::optional next_opponent_badge_; + Font small_; + TextDb texts_; + DeskDrawerRenderer drawers_; + std::optional pending_; + std::string last_rejection_; + bool shortcut_bar_visible_ = false; // presentation-local afb86; no saved-option mutation + bool shortcut_bar_edge_toggle_ = false; // afb86 bit0; always-visible option owns bit1 + int shortcut_last_y_ = 0; // DeskDate local_48, suppresses repeated samples at y239 + int shortcut_hover_record_ = -1; + bool socket_confirmation_armed_ = false; + bool socket_release_pending_ = false; + bool bin_mode_ = false; // DeskDate local_50; presentation-local transfer into/out of folders + mutable std::vector sound_ids_; + struct LayoutDrag { int item=-1, grab_x=0, grab_y=0, start_x=0, start_y=0, folder=-1; bool moved=false, folder_child=false, drawer_handle=false, right_button=false; }; + std::optional layout_drag_; + std::optional layout_preview_; + void text(Image&, int x, int baseline, std::string_view, uint8_t color, int right = -1) const; + void sprite_text(Image&, int x, int baseline, std::string_view, int font) const; + void frame(Image&, int x, int y, int width, int height) const; + void digits(Image&, int value, int sx, int sy, int width, int height, int x, int y, int base, int gap) const; + void draw_item(Image&, const DeskItem&) const; + bool sample_shortcut_pointer(int x, int y); + std::optional folder_child_at(int x, int y) const; + DeskRequest request(DeskRequestKind, const DeskItem&, int value = -1); +}; + +} // namespace bmh::ui diff --git a/src/ui/desktop_tests.cpp b/src/ui/desktop_tests.cpp new file mode 100644 index 0000000..cf4fc70 --- /dev/null +++ b/src/ui/desktop_tests.cpp @@ -0,0 +1,1369 @@ +#include "../../tests/runtime_fixture_tables.hpp" +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "../../tests/test_inputs.hpp" +#include "ui/flow.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "formats/fbm.hpp" +#include "formats/savestate.hpp" +#include "formats/vga.hpp" +#include "game/messages.hpp" +#include "game/matchday_setup.hpp" +#include "game/save.hpp" +#include "game/state.hpp" +#include "game/turn_driver.hpp" +#include "ui/calendar_state.hpp" +#include "ui/strengths_state.hpp" +#include "ui/desk_records.hpp" +#include "ui/desk_drawers.hpp" + +using namespace bmh; +using namespace bmh::ui; + +namespace { +void check(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); } +void rejected(const std::function& action) { + static int index = 0; ++index; + try { action(); } catch (const FormatError&) { return; } + throw std::runtime_error("expected rejected action #" + std::to_string(index)); +} +void write16(Bytes& b, size_t at, uint16_t value) { b.at(at) = uint8_t(value); b.at(at + 1) = uint8_t(value >> 8); } +void write32(Bytes& b, size_t at, uint32_t value) { write16(b, at, uint16_t(value)); write16(b, at + 2, uint16_t(value >> 16)); } +int calendar_rng_draws = 0; +void count_calendar_rng_draw(int) { ++calendar_rng_draws; } +void paired_closing_selection() { + DeskState state;state.runtime_club=29;state.next_opponent=-1; + state.items={{40,69,22,42,42,66,0,0,true,false}, + {41,213,22,42,42,67,0,0,true,false}}; + check(source_drawer_team(state,16)==29 && !source_drawer_team(state,17), + "Source closing drawers keep own badge first and no-opponent computer second"); +} +void paired_selection_matrix(const LeImage& exe) { + const std::array table{3,4,11,12,16,17,20,21}; + for(size_t i=0;i=2. + const int mask=shape<4?shape:3; + state.items.push_back({1,0,0,42,42,table[pair*2]+50,0,0,bool(mask&1),shape==4}); + state.items.push_back({2,50,0,42,42,table[pair*2+1]+50,0,0,bool(mask&2),shape==4}); + if(shape==5)state.items.push_back(state.items[0]); + int source_count=0; + if(gate && rival!=-1)for(const auto& item:state.items)if(item.open) { + for(size_t i=0;i{source_first}) && + source_drawer_team(state,table[pair*2+1])== + (source21<0?std::nullopt:std::optional{source21}), + "all four pairs follow Source count/gate/opponent/open/disabled rules"); + } + } + DeskState unknown;unknown.runtime_club=12;unknown.paired_drawers_away_order=true; + unknown.items={{1,0,0,42,42,66,0,0,true,false},{2,50,0,42,42,67,0,0,true,false}}; + check(source_drawer_team(unknown,16)==12 && !source_drawer_team(unknown,17), + "unknown opponent does not become a guessed away-side swap"); +} +void paired_saved_projection(const std::filesystem::path& path,const LeImage& exe) { + const auto fbm=load_savegame(path);check(fbm.checksum_ok,"real closing fixture checksum"); + const auto original=GameState::from_save(SaveState(fbm.stream)); + check(original.date==1461 && original.manager_teams==std::vector{29},"actual SIM/Bayern closing context"); + const std::vector groups; + for(int option:{0,1})for(int away:{0,1}) { + auto g=original;g.memory.set8(::bmh::layout::DeskState_FormatError_RuntimeField2,uint8_t(option));g.manager_records.at(0x28a)=uint8_t(away); + const auto native=save_stream(g);const bool expected=option==0 && away!=0; + const auto saved=desk_from_save(SaveState(native),exe,1); + const DeskMatchCallargs closing{32,-1}; + const auto live=desk_from_game(g,exe,1,&groups,32,&closing); + check(saved.paired_drawers_away_order==expected && live.paired_drawers_away_order==expected && + !live.next_match_away,"saved/raw pair gate is independent of absent closing match labels"); + check(source_drawer_team(live,16)==29 && !source_drawer_team(live,17), + "real closing badge remains own first for every option/raw-away combination"); + const DeskMatchCallargs match{34,13}; + const auto matched=desk_from_game(g,exe,1,&groups,34,&match); + check(matched.paired_drawers_away_order==expected && matched.next_match_away==bool(away), + "pair setting does not change actual match-label home/away semantics"); + check(save_stream(g)==native,"all Source gate projections preserve the complete Native state"); + } + auto g=original;g.memory.set8(::bmh::layout::DeskState_FormatError_RuntimeField2,0);g.manager_records.at(0x28a)=1; + const DeskMatchCallargs match{34,13}; + const auto both=desk_from_game(g,exe,1,&groups,34,&match); + check(source_drawer_team(both,16)==13 && source_drawer_team(both,17)==29, + "genuine away pair with two visible open badges reverses exactly once"); + const auto first=std::find_if(both.items.begin(),both.items.end(),[](const auto& i){return i.kind==66;}); + check(first!=both.items.end() && first->open,"real first badge exists and is open"); + const uint32_t at=::bmh::layout::Desktops+uint32_t(first->id)*16; + auto hidden=g;hidden.memory.set16(at,uint16_t(hidden.memory.u16(at)|0x1000)); + const auto hidden_desk=desk_from_game(hidden,exe,1,&groups,34,&match); + check(std::none_of(hidden_desk.items.begin(),hidden_desk.items.end(),[](const auto& i){return i.kind==66;}) && + source_drawer_team(hidden_desk,17)==13,"native hidden badge is omitted before Source pair counting"); + auto collapsed=g;collapsed.memory.set8(at+13,uint8_t(collapsed.memory.u8(at+13)&0x7f)); + const auto collapsed_desk=desk_from_game(collapsed,exe,1,&groups,34,&match); + check(source_drawer_team(collapsed_desk,17)==13,"native collapsed first badge leaves count1, not count2"); +} + +GameState fixture() { + GameState g; + for (auto [address, size] : std::vector>{{::bmh::layout::CareerDuration,1},{::bmh::layout::GameMode,1},{::bmh::layout::ManagerCount,1}, + {::bmh::layout::CompetitionSelection,4},{::bmh::layout::ActiveManager,1},{::bmh::layout::CareerSession_Save_RuntimeField,4},{::bmh::layout::LeaguePresentationOptions,0xb4},{::bmh::layout::FundBlock,0xa8},{::bmh::layout::Loans,0x1e0},{::bmh::layout::Desktops,0x10e0}, + {::bmh::layout::Difficulty,1},{::bmh::layout::CalendarDay,4},{::bmh::layout::CoachActive,1},{::bmh::layout::CareerSession_AnyOf_ExecutableField,10},{::bmh::layout::ClubShortNameOffsets,512}, + {::bmh::layout::Coupon,0x14},{::bmh::layout::CareerSession_DispatchToto_RuntimeField,1},{::bmh::layout::DeskRecords_Teams_RuntimeField,138*2}}) g.memory.add_block(address, size); + g.memory.set8(::bmh::layout::CareerDuration,5); g.memory.set8(::bmh::layout::GameMode,3); g.memory.set8(::bmh::layout::ManagerCount,1); g.memory.set32(::bmh::layout::CompetitionSelection,1); + g.level = 2; g.memory.set8(::bmh::layout::Difficulty,9); // typed level intentionally differs from stale memory copy + g.memory.set32(::bmh::layout::CareerSession_Save_RuntimeField,0x12345678); + g.manager_teams = {12}; g.manager_records.resize(5 * 0xb0c); + const std::string name = "Nobody"; std::copy(name.begin(), name.end(), g.manager_records.begin() + 0xa8); + write16(g.manager_records,0x290,2); // authoritative runtime club comes from manager_teams + g.club_ids.resize(419); std::iota(g.club_ids.begin(),g.club_ids.end(),0); + g.club_names.resize(419,0); std::copy_n("UNITFC",6,g.club_names.begin()+12); g.club_names[18]=0; + g.club_heap_78.resize(419 * 2); + g.stocks.resize(0x450); g.manager_options.resize(20); g.league_rounds.resize(9); + g.squad_slots.resize(3096,0x0fff); g.players.resize(24); g.team_morale.resize(419,25); + g.player_cards.resize(24); g.player_bonus.resize(24); g.player_name_offsets.resize(24,0); + g.player_names={'P','L','A','Y','E','R',0}; + g.tactics.resize(0x2940); g.formations.resize(0x160); + for (int row = 0; row < 24; ++row) { + g.squad_slots.at(12 * 24 + row) = uint16_t(row | (row < 11 ? 0x8000 : row < 16 ? 0x4000 : 0)); + g.players[row].w35c = 50 | (90 << 7) | (90 << 14); + g.tactics.at(size_t(row) * 0x58 + 0x0c) = 4; + } + // Layout: calendar, lineup, training, tactics, kickoff; no screen coordinates in controller code. + const std::array kinds = {58,3,16,18,12}; + g.memory.set8(::bmh::layout::Desktops + 5,1); + for (int i = 0; i < 5; ++i) { + const auto at = ::bmh::layout::DesktopsUnsigned + uint32_t(i + 1) * 16; + g.memory.set16(at,uint16_t(i == 0 ? 4 : i * 40)); g.memory.set8(at + 2,uint8_t(i == 0 ? 22 : 120)); + g.memory.set8(at + 3,uint8_t(i == 0 ? 61 : 32)); g.memory.set8(at + 4,uint8_t(i == 0 ? 62 : 25)); + g.memory.set8(at + 5,uint8_t(i == 4 ? 0 : i + 2)); g.memory.set8(at + 12,uint8_t(kinds[i])); + g.memory.set8(at + 13,uint8_t(i == 0 ? 0x80 : 0)); + } + return g; +} + +GameState calendar_fixture(const LeImage& exe, uint32_t season_start, uint32_t day_offset) { + auto game = fixture(); + game.season_start = season_start; + game.date = season_start + day_offset; + game.season = 0; + game.memory.add_block(::bmh::layout::CalendarState_FormatError_RuntimeField3, 2); + game.memory.set16(::bmh::layout::CalendarState_FormatError_RuntimeField3, uint16_t(season_start)); + game.memory.add_block(::bmh::layout::DaysIntoSeason, 2); + game.memory.set16(::bmh::layout::DaysIntoSeason, uint16_t(day_offset)); + game.memory.add_block(::bmh::layout::CompetitionCalendar, 366 * 2); + game.memory.add_block(::bmh::layout::CalendarState_FormatError_RuntimeField2, 1); + game.memory.add_block(::bmh::layout::CalendarState_FormatError_RuntimeField, 1); + game.memory.set8(::bmh::layout::CalendarState_FormatError_RuntimeField2, 0); + game.memory.set8(::bmh::layout::CalendarState_FormatError_RuntimeField, 0); + for (int league = 0; league < 9; ++league) + check(exe.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league)) <= 31,"league calendar class fits Source bitmap"); + return game; +} + +void calendar_projection_tests(const LeImage& exe) { + auto regular = calendar_fixture(exe, 0, 364); + regular.memory.set16(::bmh::layout::CompetitionCalendar, uint16_t(1u << exe.u8(::bmh::layout::LeagueCalendarBits))); + regular.memory.set16(::bmh::layout::CompetitionCalendar + 4, uint16_t(1u << exe.u8(::bmh::layout::LeagueCalendarBits))); + regular.memory.set16(::bmh::layout::CompetitionCalendar + 6, uint16_t(1u << exe.u8(::bmh::layout::FixtureCalendarSecondLeagueBit))); + const Bytes before_native = save_stream(regular); + GameRandom game_rng(1234); + WatcomRandom watcom_rng(5678); + const auto game_seed = game_rng.seed(); + const auto game_calls = game_rng.calls(); + const auto watcom_seed = watcom_rng.seed(); + const auto watcom_calls = watcom_rng.calls(); + calendar_rng_draws = 0; + auto previous_hook = draw_hook; + draw_hook = count_calendar_rng_draw; + const auto state = calendar_from_game(regular,exe); + draw_hook = previous_hook; + check(state.days.size() == 365 && state.current_day == 364 && state.days.back().current_day, + "regular season ends at June 30 with its final day included"); + check(state.days[0].date.month == 7 && state.days[0].date.day == 1 && + state.days[364].date.month == 6 && state.days[364].date.day == 30, + "calendar rows use the Source July-to-June date conversion"); + check(state.days[0].league_matchdays[0] == 1 && state.days[1].league_matchdays[0] == 0 && + state.days[2].league_matchdays[0] == 2, + "league matchday ordinals count effective Source class bits inclusively"); + check(state.days[0].raw_entry == uint16_t(1u << exe.u8(::bmh::layout::LeagueCalendarBits)) && + state.days[0].competitions == (1u << exe.u8(::bmh::layout::LeagueCalendarBits)), + "projection preserves the saved calendar word and its effective competition bitmap"); + check(calendar_rng_draws == 0 && game_rng.seed() == game_seed && game_rng.calls() == game_calls && + watcom_rng.seed() == watcom_seed && watcom_rng.calls() == watcom_calls && + save_stream(regular) == before_native, + "calendar projection leaves the complete serialized native state and RNG untouched"); + + // legacy routine starts native calendar word zero on the first Wednesday, while + // legacy routine draws from July 1. The two leading display cells have no word. + auto first_wednesday = calendar_fixture(exe,1463,262); + first_wednesday.memory.set16(::bmh::layout::CompetitionCalendar + 262 * 2, uint16_t(1u << exe.u8(::bmh::layout::LeagueCalendarBits))); + const auto wednesday_state = calendar_from_game(first_wednesday,exe); + check(wednesday_state.leading_days == 2 && wednesday_state.current_day == 264 && + wednesday_state.season_start_counter == 1461, + "cold-loaded first-Wednesday season keeps display and native cursors distinct"); + check(wednesday_state.days[0].date.month == 7 && wednesday_state.days[0].date.day == 1 && + wednesday_state.days[0].season_day == -2 && wednesday_state.days[0].raw_entry == 0 && + wednesday_state.days[2].date.day == 3 && wednesday_state.days[2].season_day == 0 && + wednesday_state.days[264].date.month == 3 && wednesday_state.days[264].date.day == 22 && + wednesday_state.days[264].season_day == 262 && wednesday_state.days[264].current_day && + wednesday_state.days[264].raw_entry == uint16_t(1u << exe.u8(::bmh::layout::LeagueCalendarBits)), + "native day 262 maps to displayed March 22 after two empty July cells"); + + auto marked = calendar_fixture(exe,0,0); + marked.memory.set16(::bmh::layout::CompetitionCalendar,uint16_t(0x8001)); + const auto marked_state = calendar_from_game(marked,exe); + check(marked_state.days[0].raw_entry == 0x8001 && marked_state.days[0].competitions == 1, + "saved high marker remains in raw word while the effective bitmap follows Source masking"); + + auto leap = calendar_fixture(exe,365,365); + leap.date = leap.season_start + 365; + const auto leap_state = calendar_from_game(leap,exe); + check(leap_state.days.size() == 366 && leap_state.current_day == 365 && + leap_state.days.back().season_day == 365 && leap_state.days.back().date.month == 6 && + leap_state.days.back().date.day == 30 && leap_state.days.back().current_day, + "leap season includes valid June 30 at season index 365"); + + for (int season = 0; season < 4; ++season) { + auto rotated = calendar_fixture(exe,0,0); + rotated.season = season; + rotated.memory.set16(::bmh::layout::CompetitionCalendar,0x1e00); + const auto rotated_state = calendar_from_game(rotated,exe); + const uint32_t expected = uint32_t(1) << (12 - season); + check(rotated_state.days[0].competitions == expected, + "rotating calendar competition follows the four-season Source cycle"); + } + auto one_rotation_bit = calendar_fixture(exe,0,0); + one_rotation_bit.memory.set16(::bmh::layout::CompetitionCalendar,0x0200); + auto one_rotation_state = calendar_from_game(one_rotation_bit,exe); + check(one_rotation_state.days[0].competitions == 0, + "a single rotation bit is absent when the current season selects another class"); + one_rotation_bit.season = 3; + one_rotation_state = calendar_from_game(one_rotation_bit,exe); + check(one_rotation_state.days[0].competitions == 0x0200, + "the same rotation bit appears in its selected Source season"); + + auto all_leagues = calendar_fixture(exe,0,0); + all_leagues.memory.set8(::bmh::layout::CompetitionSelection,3); + for (int league = 0; league < 9; ++league) { + const uint32_t mask = uint32_t(1) << exe.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league)); + uint16_t raw = 0; + bool found = false; + for (uint32_t candidate = 0; candidate <= 0xffff; ++candidate) { + const auto word = uint16_t(candidate); + if (day_competitions(all_leagues,word) == mask) { raw = word; found = true; break; } + } + check(found,"each executable league class has a representable calendar entry"); + all_leagues.memory.set16(::bmh::layout::CompetitionCalendar + uint32_t(league) * 2,raw); + } + const auto all_league_state = calendar_from_game(all_leagues,exe); + for (int league = 0; league < 9; ++league) { + const uint32_t mask = uint32_t(1) << exe.u8(::bmh::layout::LeagueCalendarBits + uint32_t(league)); + int inclusive_ordinal = 0; + for (int day = 0; day < 9; ++day) { + const uint16_t raw = all_leagues.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(day) * 2); + const bool plays = (day_competitions(all_leagues,raw) & mask) != 0; + if (plays) ++inclusive_ordinal; + check(all_league_state.days[size_t(day)].league_matchdays[size_t(league)] == + (plays ? inclusive_ordinal : 0), + "each league ordinal is the inclusive count of its class through a playing day"); + } + } + + auto specials = calendar_fixture(exe,0,0); + specials.memory.set16(::bmh::layout::CompetitionCalendar,0x4001); + specials.memory.set16(::bmh::layout::CompetitionCalendar+2,0x4002); + specials.memory.set16(::bmh::layout::CompetitionCalendar+4,0x4004); + specials.memory.set16(::bmh::layout::CompetitionCalendar+6,0x4006); + auto special_state = calendar_from_game(specials,exe); + check(special_state.days[0].competitions == 0x8000 && + special_state.days[1].competitions == 0x10000 && + special_state.days[2].competitions == 0x40000 && + special_state.days[3].competitions == 0, + "special calendar words preserve Source masks and disable tournament without its flag"); + specials.memory.set8(::bmh::layout::CompetitionSelection,3); + special_state = calendar_from_game(specials,exe); + check(special_state.days[3].competitions == 0x800000, + "0x4006 tournament entry is effective only when the saved tournament flag is set"); + specials.memory.set8(::bmh::layout::CalendarState_FormatError_RuntimeField,1); + special_state = calendar_from_game(specials,exe); + check(special_state.days[1].competitions == 0, + "saved special-event disable flag is applied by the Source competition projection"); + auto filtered = calendar_fixture(exe,0,0); + filtered.memory.set16(::bmh::layout::CompetitionCalendar,0x8010); + auto filtered_state = calendar_from_game(filtered,exe); + check(filtered_state.days[0].raw_entry == 0x8010 && filtered_state.days[0].competitions == 0x10, + "calendar raw high marker is retained while effective flags omit that marker"); + filtered.memory.set8(::bmh::layout::CalendarState_FormatError_RuntimeField2,1); + filtered_state = calendar_from_game(filtered,exe); + check(filtered_state.days[0].raw_entry == 0x8010 && filtered_state.days[0].competitions == 0, + "saved calendar mask 0xa2594 clears effective bit 0x10"); + + auto malformed = calendar_fixture(exe,0,0); + malformed.memory.set16(::bmh::layout::CalendarState_FormatError_RuntimeField3,1); + rejected([&]{ calendar_from_game(malformed,exe); }); + auto outside = calendar_fixture(exe,0,0); + outside.date = 365; + rejected([&]{ calendar_from_game(outside,exe); }); + auto missing = fixture(); + rejected([&]{ calendar_from_game(missing,exe); }); + auto present_table = calendar_fixture(exe,0,0); + LeImage missing_executable; + rejected([&]{ calendar_from_game(present_table,missing_executable); }); +} + +void source_sort_reference(std::vector>& rows, + size_t begin, size_t count, bool ascending) { + if (count <= 1) return; + std::ptrdiff_t left = -1, right = std::ptrdiff_t(count); + const uint32_t pivot = rows[begin + count / 2].first; + for (;;) { + if (!ascending) { + do { ++left; } while (pivot < rows[begin + size_t(left)].first); + do { --right; } while (rows[begin + size_t(right)].first < pivot); + } else { + do { ++left; } while (rows[begin + size_t(left)].first < pivot); + do { --right; } while (pivot < rows[begin + size_t(right)].first); + } + if (right <= left) break; + std::swap(rows[begin + size_t(left)], rows[begin + size_t(right)]); + } + source_sort_reference(rows, begin, size_t(left), ascending); + source_sort_reference(rows, begin + size_t(left), count - size_t(left), ascending); +} + +void strengths_projection_tests() { + const auto none = strengths_draw_words_source(0x0000); + check(none.raw_settings_word == 0 && none.row_settings_word == 0x00ff && + none.effective_average_flags == 0x00ff && none.post_draw_settings_word == 0x01ff, + "Strengths defaults row criteria and normalizes the persisted word after the draw"); + const auto full = strengths_draw_words_source(0x00ff); + check(full.row_settings_word == 0x00ff && full.post_draw_settings_word == 0x01ff, + "all eight filters set saved word bit 8 without changing row calculation flags"); + const auto header = strengths_draw_words_source(0x8000); + check(header.effective_average_flags == 0x01ff && header.post_draw_settings_word == 0x81ff, + "post-draw high-byte mask preserves Source header bit 15 before the zero-word default"); + const auto age_draw = strengths_draw_words_source(0x0200); + check(age_draw.row_settings_word == 0x00ff && age_draw.post_draw_settings_word == 0x0200, + "age-sort word is retained by the Source 0xf2 high-byte mask"); + + check(strengths_control_word_source(0x00ff, StrengthsControl::condition) == 0x00fe, + "filter control toggles its exact bit from normalized settings"); + check(strengths_control_word_source(0x01ff, StrengthsControl::condition) == 0x00fe, + "a changed filter clears Source's line-up bit unless the full low nine bits remain set"); + check(!strengths_control_word_source(0x02ff, StrengthsControl::condition), + "Source locks the eight filters while age sorting is active"); + check(strengths_control_word_source(0x02ff, StrengthsControl::age) == 0x0000, + "age control applies Source high-byte mask and toggle"); + check(strengths_control_word_source(0x8000, StrengthsControl::lineup) == 0x0000, + "line-up header control toggles word bit 15"); + check(strengths_control_word_source(0x2200, StrengthsControl::reset) == 0x01ff, + "zero-value control writes the full Source 0x1ff word"); + check(strengths_family_word_source(0xffff, 0) == 0xfd7f && + strengths_family_word_source(0xffff, 1) == 0xfdff, + "family entry preserves Source 0xfc0f bits and sets values from points mode"); + + auto game = fixture(); + game.memory.add_block(::bmh::layout::ManagerSettings, 10); + game.memory.add_block(::bmh::layout::DeskPosition, 1); + game.manager_records[0xa8] = 'A'; + game.manager_teams[0] = 12; + game.memory.set16(::bmh::layout::ManagerSettings, 0x8000); + game.memory.set8(::bmh::layout::ActiveManager, 0); + game.memory.set8(::bmh::layout::DeskPosition, 0); + for (size_t i = 0; i < game.players.size(); ++i) + game.players[i].w364 = (uint32_t(i % 24) << 21) | (i == 0 ? 0x00010000u : 0); + constexpr std::array foreign_titles{"ENGLAND", "ITALY", "SPAIN", "FRANCE"}; + for (size_t i = 0; i < foreign_titles.size(); ++i) { + const size_t title_team = size_t(0x166) + i; + const size_t title_offset = 300 + i * 16; + game.club_ids[title_team] = uint16_t(title_offset); + std::copy(foreign_titles[i].begin(), foreign_titles[i].end(), + game.club_names.begin() + std::ptrdiff_t(title_offset)); + game.club_names[title_offset + foreign_titles[i].size()] = 0; + } + static TextDb texts; + if (texts.strings.empty()) texts.strings.resize(TEXT_COUNT); + texts.strings.at((::bmh::layout::Achievements_FormatError_TextPointer3 - ::bmh::layout::TextPointerTable) / 4) = "League"; + texts.strings.at((::bmh::layout::Manager_FormatError_TextPointer2 - ::bmh::layout::TextPointerTable) / 4) = " "; + game.texts = &texts; + + const Bytes before = save_stream(game); + calendar_rng_draws = 0; + auto previous_hook = draw_hook; + draw_hook = count_calendar_rng_draw; + const auto projection = strengths_from_game(game, 0, 0); + draw_hook = previous_hook; + check(projection.rows.size() == 18 && projection.first_team == 0 && + projection.manager_slot == 0 && projection.age_scratch.basis == + StrengthsAgeBasis::entry_or_league_change_bit10 && + !projection.age_scratch.lineup_only, + "league zero projects its exact eighteen teams and uses raw bit 10 on entry"); + check(projection.rows.front().runtime_team == 12 && + projection.rows.front().team_name == "UNITFC" && + projection.rows.front().name_color == 0x7a, + "league projection carries save-remapped name and Source active-manager color"); + check(projection.rows.front().criterion_values == std::array{90,90,50,50} && + projection.rows.front().aggregate_value == 90, + "strength columns and aggregate honor the Source eleven-player lineup divisor"); + check(projection.age_scratch.tenths.at(12) == 115, + "Source age scratch averages all squad slots in byte tenths with integer truncation"); + check(save_stream(game) == before, + "Strengths projection leaves the complete serialized game state unchanged"); + check(calendar_rng_draws == 0, + "domestic Strengths projection does not call the random draw hook"); + auto high_identity = game; + high_identity.manager_records[0xa8] = 0; + high_identity.manager_teams[0] = 0x0100; + const auto high_identity_projection = strengths_from_game(high_identity, 0, 0); + const auto low_byte_alias = std::find_if(high_identity_projection.rows.begin(), + high_identity_projection.rows.end(), [](const StrengthsRow& row){ return row.runtime_team == 0; }); + check(low_byte_alias != high_identity_projection.rows.end() && low_byte_alias->name_color == 0x5f, + "Source current-club name highlight compares the complete 16-bit team identity"); + auto fallback_color = game; + fallback_color.manager_records[0xa8] = 0; + const auto fallback_projection = strengths_from_game(fallback_color, 0, 0); + const auto active_team_row = std::find_if(fallback_projection.rows.begin(), + fallback_projection.rows.end(), [](const StrengthsRow& row){ return row.runtime_team == 12; }); + check(active_team_row != fallback_projection.rows.end() && active_team_row->name_color == 0xf7, + "Source favorite-club fallback uses the active manager's complete runtime team ID"); + + const auto header_age = strengths_from_game(game, 0, 0, + StrengthsProjectionContext{std::nullopt, StrengthsAgeBasis::header_toggle_bit15}); + check(header_age.age_scratch.lineup_only && header_age.age_scratch.tenths.at(12) == 50, + "header-toggle age scratch uses bit 15 and only the eleven starting players"); + StrengthsProjectionContext cached_context{projection.age_scratch, + StrengthsAgeBasis::entry_or_league_change_bit10}; + const auto cached = strengths_from_game(game, 0, 0, cached_context); + check(cached.age_scratch.basis == StrengthsAgeBasis::entry_or_league_change_bit10 && + cached.age_scratch.tenths == projection.age_scratch.tenths, + "same-league redraw retains the original age-source basis and cached bytes"); + auto stale_context = cached_context; + stale_context.cached_age->tenths[12]++; + rejected([&]{ strengths_from_game(game, 0, 0, stale_context); }); + + auto hole = game; + const size_t squad = squad_range(12).first; + hole.squad_slots[squad + 2] = kEmptySlot; + const auto hole_projection = strengths_from_game(hole, 0, 0); + check(hole_projection.age_scratch.tenths.at(12) == 5, + "age scratch stops at the first empty slot rather than counting later squad entries"); + auto byte_wrap = game; + for (size_t i = 0; i < byte_wrap.players.size(); ++i) + byte_wrap.players[i].w364 = 31u << 21; + const auto wrapped_age = strengths_from_game(byte_wrap, 0, 0); + check(wrapped_age.age_scratch.tenths.at(12) == uint8_t(310), + "age scratch preserves Source byte narrowing after the tenths division"); + auto empty = game; + for (size_t i = 0; i < squad_range(12).count; ++i) empty.squad_slots[squad + i] = kEmptySlot; + const auto empty_projection = strengths_from_game(empty, 0, 0); + check(empty_projection.age_scratch.tenths.at(12) == 0x22, + "clubs with no qualifying players preserve Source age sentinel 0x22"); + + for (int league = 0; league < 9; ++league) { + const int expected_first = league < 5 ? league * 18 : 90 + (league - 5) * 12; + const int expected_count = league < 5 ? 18 : 12; + const auto rows = strengths_from_game(game, 0, league); + check(rows.first_team == expected_first && rows.rows.size() == size_t(expected_count), + "each of the nine Source domestic league bounds is exact"); + if (league >= 5) + check(rows.league_name == iso646de_to_utf8( + game.club_name(0x165 + league - 4).c_str()), + "foreign league title comes from its saved country-club name, not domestic TEXTD"); + } + auto foreign_without_textd = game; + foreign_without_textd.texts = nullptr; + check(strengths_from_game(foreign_without_textd, 0, 5).league_name == "ENGLAND", + "foreign league projection does not index the domestic league-name table"); + rejected([&]{ strengths_from_game(game, 0, -1); }); + rejected([&]{ strengths_from_game(game, 0, 9); }); + rejected([&]{ strengths_from_game(game, 5, 0); }); + rejected([&]{ strengths_from_game(GameState{}, 0, 0); }); + auto five_managers = game; + five_managers.memory.set8(::bmh::layout::ManagerCount, 5); + rejected([&]{ strengths_from_game(five_managers, 0, 0); }); + auto invalid_basis = StrengthsProjectionContext{ + std::nullopt, static_cast(0xff)}; + rejected([&]{ strengths_from_game(game, 0, 0, invalid_basis); }); + auto no_morale = game; + no_morale.team_morale.clear(); + rejected([&]{ strengths_from_game(no_morale, 0, 0); }); + + auto age_sorted_game = game; + age_sorted_game.memory.set16(::bmh::layout::ManagerSettings, 0x8200); + const auto age_sorted = strengths_from_game(age_sorted_game, 0, 0); + std::vector> two_equal{{5, 10}, {5, 11}}; + source_sort_reference(two_equal, 0, two_equal.size(), true); + check(two_equal[0].second == 11 && two_equal[1].second == 10, + "literal Source quicksort swaps a two-element equal-key pair"); + std::vector> expected; + for (int team = 0; team < 18; ++team) { + const auto row = std::find_if(age_sorted.rows.begin(), age_sorted.rows.end(), + [team](const StrengthsRow& r){ return r.runtime_team == team; }); + check(row != age_sorted.rows.end(), "age-sort rows retain every source team"); + expected.emplace_back(row->source_sort_key, team); + } + source_sort_reference(expected, 0, expected.size(), true); + for (size_t i = 0; i < expected.size(); ++i) + check(age_sorted.rows[i].runtime_team == expected[i].second, + "age ordering matches the independent literal Source quicksort including ties"); + + auto all_equal_game = game; + all_equal_game.memory.set16(::bmh::layout::ManagerSettings, 0x8000); + for (int team = 0; team < 18; ++team) { + const SquadRange range = squad_range(team); + for (size_t slot = 0; slot < range.count; ++slot) + all_equal_game.squad_slots[range.first + slot] = kEmptySlot; + } + const auto all_equal = strengths_from_game(all_equal_game, 0, 0); + constexpr std::array source_equal_order{ + 11,12,9,10,16,17,13,15,14,2,3,0,1,7,8,4,6,5 + }; + for (size_t index = 0; index < all_equal.rows.size(); ++index) + check(all_equal.rows[index].runtime_team == source_equal_order[index], + "Source quicksort follows its exact recursive 18-row equal-key order"); +} + +void begin(StartupFlow& flow) { + flow.click(150,215); flow.click(5,225,true); flow.click(5,225,true); + check(flow.click(90,169).request == FlowRequest::new_career,"one career request"); +} +void confirm_managers(StartupFlow& flow, int count, bool national = false) { + if (national) flow.click(95,215); // league off; world remains enabled, one manager only + else flow.click(150,215); // world off + for (int i = 1; i < count; ++i) flow.click(260,135); + flow.click(5,225,true); + for (int i = 0; i < count; ++i) { + flow.click(5,225,true); + const auto result = flow.click(90,169); + if (i + 1 < count) { + check(result.request == FlowRequest::manager_confirmed,"manager selection awaits the next club order"); + SelectionContext context; context.revision = uint64_t(i + 1); context.source = "test_fixture"; + context.club_order.resize(168); std::iota(context.club_order.begin(),context.club_order.end(),0); + flow.resume_manager_selection(context); + } else check(result.request == FlowRequest::new_career,"last manager confirms career request"); + } +} +GameState career_game(const LeImage& exe, const NewCareerRequest& request, bool national = false) { + auto game = fixture(); + const auto count = request.managers.size(); + game.memory.set8(::bmh::layout::ManagerCount,uint8_t(count)); + game.memory.set32(::bmh::layout::CompetitionSelection,national ? 2 : (request.options.league ? 1 : 0) | (request.options.world ? 2 : 0)); + game.manager_teams.resize(count); + const auto template_record = Bytes(game.manager_records.begin(),game.manager_records.begin()+0xb0c); + for(size_t i=0;i(25,choice.name.size()),game.manager_records.begin()+base+0xa8); + game.manager_records[base+0x210]=uint8_t(choice.start_league); + game.manager_records[base+0x221]=uint8_t(choice.portrait); + write16(game.manager_records,base+0x290,uint16_t(game.manager_teams[i])); + } + game.memory.set8(::bmh::layout::ActiveManager,0); + return game; +} +void set_preparation_revision_source(PreparationState& state, uint64_t revision, const std::string& source) { + state.desktop.revision=revision; state.desktop.source=source; + state.lineup.revision=state.tactics.revision=revision; + state.lineup.source=state.tactics.source=source; + if(state.training){state.training->revision=revision;state.training->source=source;} + if(state.training_camp){state.training_camp->revision=revision;state.training_camp->source=source;} + if(state.bank){state.bank->revision=revision;state.bank->source=source;} + if(state.stadium){state.stadium->revision=revision;state.stadium->source=source;} + if(state.toto){state.toto->revision=revision;state.toto->source=source;} + if(state.pitch){state.pitch->revision=revision;state.pitch->source=source;} + for(auto& card:state.player_cards){card.lineup.revision=revision;card.lineup.source=source;} +} +} // namespace + +int main(int argc, char** argv) { + try { + paired_closing_selection(); + if (argc < 2) throw std::runtime_error("data directory required"); + const std::filesystem::path data = argv[1]; const auto exe = bmh::test::load_executable(asset_path(data,"BMH.exe")); + paired_selection_matrix(exe); + if(argc>3)paired_saved_projection(argv[3],exe); + // Gregorian dates are an independent oracle for the original's observed year range. + using namespace std::chrono; + const sys_days epoch = year{2026}/7/1; + for (uint32_t i = 0; i < 1461; ++i) { + const auto d = desk_date(i,exe); const year_month_day oracle(epoch + days{i}); + check(d.year == int(oracle.year()) && d.month == int(unsigned(oracle.month())) && + d.day == int(unsigned(oracle.day())),"calendar/leap boundary mismatch"); + } + rejected([&]{ desk_date(0xffff,exe); }); + calendar_projection_tests(exe); + strengths_projection_tests(); + auto g = fixture(); const auto before_records = g.manager_records; const auto before_squads = g.squad_slots; + auto d = desk_from_game(g,exe,7); + DesktopScreen timed_desk(data,d); + const auto deadline=timed_desk.process_timer_expired(); + check(deadline.kind==DeskRequestKind::advance_turn&&deadline.manager_slot==d.manager_slot&& + deadline.revision==d.revision&&deadline.item_id==-1&&timed_desk.pending()==deadline, + "Original deadline owns one typed turn request without a guessed icon hit"); + check(timed_desk.process_timer_expired().kind==DeskRequestKind::none, + "repeated expired polls cannot duplicate the pending calendar turn"); + check(d.options.difficulty == 2 && d.runtime_club == 12 && d.strength == 90,"typed projection / strength"); + check(!d.table_position,"table rank stays absent before any league round is recorded"); + check(d.warnings[2] == true && d.warnings[5] == false && d.warnings[6] == false,"initial warnings"); + check(before_records == g.manager_records && before_squads == g.squad_slots,"projection must be read-only"); + check(desk_menu_name(25)=="fair_play"&&desk_menu_name(26)=="highscore", + "ordinary menu 25/26 names match their Original desk functions"); + auto fair_fixture=fixture(); + for(int team=0;team<18;++team) fair_fixture.memory.set16(::bmh::layout::DeskRecords_Teams_RuntimeField+uint32_t(team)*2,uint16_t(team)); + fair_fixture.memory.set16(::bmh::layout::DeskRecords_Teams_RuntimeField+uint32_t(4)*2,0); // avoid a tied four-point team in this ordering assertion + fair_fixture.memory.set16(::bmh::layout::DeskRecords_Teams_RuntimeField,0x0100); // one red card: four points, after scores 1..3 + const auto fair= fair_play_state_from_game(fair_fixture,0,{},0); + check(fair.fair_play_rows.size()==18&&fair.fair_play_rows.front().team==4&& + fair.fair_play_rows.front().points==0&&fair.fair_play_rows[4].team==0&& + fair.fair_play_rows[4].points==4&&fair.fair_play_rows.back().team==17&& + fair.fair_play_rows.back().points==17, + "legacy routine ascending fair-play ordering uses four points per red card"); + auto fair_view=fair;fair_view.underlay=Image(320,240); + DeskRecordsScreen fair_screen(data,std::move(fair_view)); + check(fair_screen.render().pixels.size()==320u*240u&&!fair_screen.closed(), + "menu-25 Original panel renders the full Source league row set"); + DeskRecordsState high_view;high_view.kind=DeskRecordKind::highscore;high_view.underlay=Image(320,240); + DeskRecordsScreen high_screen(data,std::move(high_view)); + check(high_screen.render().pixels.size()==320u*240u&&!high_screen.closed(), + "menu-26 uses the five-row highscore presentation, not the game-end calculator"); + const auto high_backdrop=high_screen.render(); + check(high_screen.key_input("ENTER"),"Source calculator ENTER accepts its value"); + while(high_screen.advance_point()) {} + check(high_screen.finish_points()&&high_screen.render().pixels!=high_backdrop.pixels, + "signature-zero acceptance advances every Original points frame and retains the points image"); + check(high_screen.pointer_down(4,4)&&high_screen.closed(), + "signature-zero points screen waits for its own mouse-down acknowledgement"); + DeskRecordsState ranked_high_view;ranked_high_view.kind=DeskRecordKind::highscore; + ranked_high_view.highscore.ranked=true; + ranked_high_view.underlay=Image(320,240); + DeskRecordsScreen ranked_high_screen(data,std::move(ranked_high_view)); + const auto ranked_high_frame=ranked_high_screen.render(); + const auto source_ranked_art=load_vga(asset_path(data/"KB","51.VGA")); + check(ranked_high_frame.pixels[size_t(50)*size_t(ranked_high_frame.width)+150]== + source_ranked_art.pixels[size_t(25)*size_t(source_ranked_art.width)+50], + "ranked menu-26 copies Source decimal asset 51 (legacy routine argument 0x33)"); + auto menu_game = fixture(); + menu_game.memory.set8(::bmh::layout::Desktops + 44 * 16 + 12, 63); // mailbox occurs before the menu shortcut in this scan + menu_game.memory.set8(::bmh::layout::Desktops + 53 * 16 + 12, 72); // final compact-bar cell dispatches MEN + auto menu_desk = desk_from_game(menu_game, exe, 6); + check(menu_desk.mailbox_shortcut && menu_desk.menu_layout_shortcut && + menu_desk.menu_layout_shortcut->id == 53, + "Source final compact-bar cell resolves record 53/kind 72 independently of linked drawers"); + menu_desk.shortcut_bar_always = false; + DesktopScreen edge_bar(data, menu_desk); + const auto edge_hidden = edge_bar.render(); + check(!edge_bar.pointer_move(160, 238), "Source quickbar edge requires exactly y239"); + check(edge_bar.pointer_move(160, 239) && edge_bar.render().pixels != edge_hidden.pixels && + !edge_bar.pending() && edge_bar.state().layout_records == menu_desk.layout_records, + "lower-edge motion shows quickbar without an action or Native layout edits"); + const auto edge_shown = edge_bar.render(); + const auto quickbar_art = load_vga(asset_path(data / "KB", "3.VGA")); + for (int y = 0; y < 20; ++y) for (int x = 0; x < 20; ++x) + check(edge_shown.pixels[size_t(207 + y) * 320 + 299 + x] == + quickbar_art.pixels[size_t(75 + y) * quickbar_art.width + exe.u8(::bmh::layout::Desktop_Render_RuntimeField3) + x], + "visible Source quickbar copies the complete normal socket sprite before any press"); + check(!edge_bar.pointer_move(250, 239) && edge_bar.click(250, 239).kind == DeskRequestKind::none && + edge_bar.render().pixels == edge_shown.pixels, + "motion along edge and click at the same edge do not toggle the Source y latch twice"); + check(edge_bar.pointer_move(292, 221), "MEN quickbar cell motion selects its Source hover label"); + const auto hover_frame = edge_bar.render(); + int hover_pixels = 0; + for (int y = 0; y < 240; ++y) for (int x = 0; x < 320; ++x) + if (hover_frame.pixels[size_t(y) * 320 + x] != edge_shown.pixels[size_t(y) * 320 + x]) { + check(y >= 230 && y <= 235, "Source quickbar label changes only the footer Font3 rows"); + ++hover_pixels; + } + check(hover_pixels > 0 && !edge_bar.pointer_move(291, 221), + "Source hover title renders once and stays stable inside the same cell"); + check(edge_bar.pointer_move(160, 238) && edge_bar.render().pixels == edge_shown.pixels, + "leaving the cell restores the footer without hiding the quickbar"); + check(edge_bar.pointer_move(160, 239) && edge_bar.render().pixels == edge_hidden.pixels, + "re-entering the lower edge toggles the quickbar off without a click"); + auto always_desk = menu_desk; always_desk.shortcut_bar_always = true; + DesktopScreen always_bar(data, always_desk); + const auto always_frame = always_bar.render(); + always_bar.pointer_move(160, 239); always_bar.pointer_move(160, 238); always_bar.pointer_move(160, 239); + check(always_bar.render().pixels == always_frame.pixels && !always_bar.pending(), + "format field bit1 keeps Always quickbar visible through both bit0 edge transitions"); + DesktopScreen menu_bar(data, menu_desk); + check(menu_bar.click(292,221).kind == DeskRequestKind::none, + "MEN shortcut is unavailable before the original compact bar is shown"); + menu_bar.pointer_move(64,239); + auto menu_save = menu_bar.click(292,221); + check(menu_save.kind == DeskRequestKind::open_menu && menu_save.menu_kind == 53 && + menu_save.item_id == 53 && menu_save.value == 1, + "compact last-cell left click opens the Original menu-layout save path from record 53"); + menu_bar.resolve_local_menu(); + auto menu_load = menu_bar.click(292,221,true); + check(menu_load.kind == DeskRequestKind::open_menu && menu_load.menu_kind == 53 && + menu_load.item_id == 53 && menu_load.value == 0, + "compact last-cell right click opens the Original menu-layout load path from record 53"); + auto quickbar_drawer = menu_desk; + quickbar_drawer.layout_records[50][5]=0xff; + quickbar_drawer.layout_records[50][6]=0xff; + quickbar_drawer.layout_records[50][12]=50; + DesktopScreen quickbar_open(data,quickbar_drawer); + quickbar_open.pointer_move(64,239); + const auto append_drawer=quickbar_open.click(22,221); + check(quickbar_open.take_sound_ids()==std::vector{15} && quickbar_open.take_sound_ids().empty(), + "Source drawer append emits ID15 exactly once through the application boundary"); + quickbar_open.render(); quickbar_open.pointer_move(23,221); quickbar_open.click(22,221); + check(quickbar_open.take_sound_ids().empty(),"render/hover/pending input never replay a drawer sound"); + check(append_drawer.kind==DeskRequestKind::change_layout&& + append_drawer.layout_operation==DeskLayoutOperation::toggle_quickbar_drawer&& + append_drawer.layout_after[50*16+5]==0&&append_drawer.layout_after[50*16+13]&0x80, + "Original quickbar LMB appends a hidden drawer record and sets its open bit"); + auto quickbar_close_state=menu_desk; + quickbar_close_state.layout_records[0][5]=50; + quickbar_close_state.layout_records[50][5]=0; + quickbar_close_state.layout_records[50][6]=0; + quickbar_close_state.layout_records[50][12]=50; + DesktopScreen quickbar_close(data,quickbar_close_state); + quickbar_close.pointer_move(64,239); + const auto unlink_drawer=quickbar_close.click(22,221,true); + check(quickbar_close.take_sound_ids()==std::vector{12},"Source drawer unlink emits ID12"); + check(unlink_drawer.kind==DeskRequestKind::change_layout&& + unlink_drawer.layout_operation==DeskLayoutOperation::toggle_quickbar_drawer&& + unlink_drawer.layout_after[0*16+5]==0&&unlink_drawer.layout_after[50*16+5]==0xff&& + unlink_drawer.layout_after[50*16+6]==0xff, + "Original quickbar RMB unlinks a visible drawer record with cleared links"); + auto child_desk=menu_desk; + child_desk.layout_records[3][5]=child_desk.layout_records[3][6]=0xff; + child_desk.layout_records[3][12]=2; + child_desk.layout_records[3][13]=0; + child_desk.layout_records[49][12]=50; + child_desk.layout_records[49][13]=0x80; + child_desk.layout_records[0][5]=49; + child_desk.layout_records[49][5]=child_desk.layout_records[49][6]=0; + child_desk.folder_icon_slots[0]={3}; + child_desk.drawer_handles=true; + child_desk.items.push_back(DeskItem{49,40,40,100,65,50,0,0,true,false}); + DesktopScreen folder_click(data,child_desk); + const auto child_action=folder_click.click(50,49); + check(child_action.kind==DeskRequestKind::open_menu&&child_action.item_id==3&&child_action.menu_kind==2, + "Source folder child uses its native record/kind on ordinary LMB activation"); + DesktopScreen folder_drag(data,child_desk); + folder_drag.pointer_down(50,49,true); + check(folder_drag.take_sound_ids()==std::vector({15,12,15}), + "folder-child RMB start preserves Source restore/unlink/append ordering"); + folder_drag.pointer_move(176,100); + const auto child_return=folder_drag.pointer_up(176,100,true); + check(child_return.kind==DeskRequestKind::change_layout&& + child_return.layout_operation==DeskLayoutOperation::return_folder_child&& + child_return.layout_before[3*16+5]==0xff&&child_return.layout_after[0*16+5]==49&& + child_return.layout_after[49*16+5]==3&&child_return.layout_after[3*16+5]==0&& + child_return.layout_after[3*16+6]==49, + "RMB drag from the rendered 32×25 folder tile returns it to the visible chain"); + check(folder_drag.take_sound_ids().empty(),"folder-child release cannot replay its down-event append"); + DesktopScreen folder_drop(data,child_desk); + folder_drop.pointer_down(50,49,true); folder_drop.take_sound_ids(); + folder_drop.pointer_move(55,52); + const auto dropped_child=folder_drop.pointer_up(55,52,true); + check(dropped_child.layout_operation==DeskLayoutOperation::set_folder && + folder_drop.take_sound_ids()==std::vector{12}, + "Source fully enclosed drop unlinks the dragged child exactly once"); + DesktopScreen unchanged_handle(data,child_desk); + unchanged_handle.pointer_down(41,41); + check(!unchanged_handle.pending() && unchanged_handle.take_sound_ids().empty(), + "existing LMB handle gesture has no invented RMB sound mapping"); + unchanged_handle.pointer_up(41,41); + check(unchanged_handle.take_sound_ids().empty(),"handle release remains silent at this Source boundary"); + auto covered_child=child_desk; + covered_child.items.push_back(DeskItem{6,60,48,32,25,21,0,0,false,false}); + covered_child.layout_records[49][5]=6; + covered_child.layout_records[6][5]=0; + covered_child.layout_records[6][6]=49; + covered_child.layout_records[6][12]=21; + DesktopScreen stacked_icon(data,covered_child); + const auto exposed_folder_frame=folder_click.render(); + const auto covered_folder_frame=stacked_icon.render(); + const auto desktop_atlas=load_vga(asset_path(data/"KB","3.VGA")); + for(int y=0;y<25;++y) for(int x=0;x<32;++x) + check(covered_folder_frame.pixels[size_t(48+y)*320+60+x]== + desktop_atlas.pixels[size_t(50+y)*desktop_atlas.width+160+x], + "top icon renders over the folder child using its own native KB3 tile"); + check(covered_folder_frame.pixels[size_t(49)*320+50]==exposed_folder_frame.pixels[size_t(49)*320+50], + "the uncovered part of a folder child remains visible below the stacked icon"); + const auto covering_icon_action=stacked_icon.click(65,49); + check(covering_icon_action.kind==DeskRequestKind::open_menu&&covering_icon_action.item_id==6&& + covering_icon_action.menu_kind==21&&stacked_icon.state().layout_records==covered_child.layout_records, + "LMB activates the rendered top icon rather than the covered folder child without layout edits"); + DesktopScreen stacked_drag(data,covered_child); + stacked_drag.pointer_down(65,49,true); + check(stacked_drag.take_sound_ids()==std::vector({12,15}), + "visible RMB drag starts with the Source unlink/append pair"); + stacked_drag.pointer_move(200,120); + const auto covering_icon_drag=stacked_drag.pointer_up(200,120,true); + check(covering_icon_drag.kind==DeskRequestKind::change_layout&&covering_icon_drag.item_id==6&& + covering_icon_drag.layout_operation==DeskLayoutOperation::move_item&& + covering_icon_drag.layout_after[3*16+5]==0xff&&covering_icon_drag.layout_after[3*16+6]==0xff, + "RMB drags the rendered top icon and leaves the covered child outside the visible link chain"); + check(stacked_drag.take_sound_ids().empty(),"ordinary move release adds no structural sound"); + DesktopScreen still_drag(data,covered_child); + still_drag.pointer_down(65,49,true); still_drag.pointer_up(65,49,true); + check(still_drag.take_sound_ids()==std::vector({12,15}), + "Source RMB reordering sounds happen even without pointer motion"); + DesktopScreen exposed_child(data,covered_child); + check(exposed_child.click(50,49).item_id==3,"an exposed folder tile still opens its native child action"); + auto status_cover=child_desk; + status_cover.items.push_back(DeskItem{48,48,48,42,35,56,0,0,true,false}); + DesktopScreen stacked_status(data,status_cover); + check(stacked_status.render().pixels!=exposed_folder_frame.pixels&& + stacked_status.pointer_down(50,49).kind==DeskRequestKind::none&& + stacked_status.pointer_up(50,49).kind==DeskRequestKind::none&&!stacked_status.pending(), + "an open status drawer covers a folder child and its inert body cannot activate that child"); + auto empty_folder_cover=child_desk; + empty_folder_cover.items.push_back(DeskItem{48,48,48,45,35,51,0,1,true,false}); + DesktopScreen stacked_empty_folder(data,empty_folder_cover); + check(stacked_empty_folder.click(50,49).kind==DeskRequestKind::none&&!stacked_empty_folder.pending(), + "an empty part of the top folder blocks a lower folder child"); + DesktopScreen covered_bin_restore(data,empty_folder_cover); + covered_bin_restore.pointer_move(160,239); + covered_bin_restore.click(10,215); + check(covered_bin_restore.pointer_down(50,49,true).kind==DeskRequestKind::none&& + covered_bin_restore.pointer_up(50,49,true).kind==DeskRequestKind::none&& + !covered_bin_restore.pending()&&covered_bin_restore.state().layout_records==empty_folder_cover.layout_records, + "bin-mode RMB on a covering empty folder cannot restore the lower child or change links"); + check(covered_bin_restore.take_sound_ids().empty(),"covered bin child cannot emit a restore sound"); + DesktopScreen exposed_bin_restore(data,covered_child); + exposed_bin_restore.pointer_move(160,239); + exposed_bin_restore.click(10,215); + const auto exposed_restore=exposed_bin_restore.click(50,49,true); + check(exposed_bin_restore.take_sound_ids()==std::vector{15},"bin-mode restore emits only append ID15"); + check(exposed_restore.layout_operation==DeskLayoutOperation::restore_folder_child&&exposed_restore.item_id==3, + "bin-mode RMB still restores an exposed folder child using its native owner"); + DesktopScreen bin_send(data,covered_child); + bin_send.pointer_move(160,239); bin_send.click(10,215); + const auto sent_icon=bin_send.click(65,49,true); + check(sent_icon.layout_operation==DeskLayoutOperation::send_to_folder && + bin_send.take_sound_ids()==std::vector{12},"bin-mode send emits only unlink ID12"); + auto closed_cover=child_desk; + closed_cover.items.push_back(DeskItem{48,48,48,14,14,63,0,0,false,false}); + DesktopScreen stacked_closed_drawer(data,closed_cover); + check(stacked_closed_drawer.click(50,49).kind==DeskRequestKind::none&&!stacked_closed_drawer.pending(), + "a closed drawer blocks hits inside its Source dimensions minus eight"); + DesktopScreen outside_closed_drawer(data,closed_cover); + check(outside_closed_drawer.click(55,49).item_id==3, + "the eight-pixel closed drawer inset allows hits on the exposed lower folder child"); + const auto menu_test_dir = std::filesystem::temp_directory_path() / + ("openbmh-menu-layout-picker-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::filesystem::create_directories(menu_test_dir / "load"); + std::filesystem::create_directories(menu_test_dir / "save"); + { std::ofstream(menu_test_dir / "load" / "LAYOUT.MEN") << "fixture"; + std::ofstream(menu_test_dir / "load" / "NOTGAME.FBM") << "fixture"; } + SaveLoadScreen menu_load_picker(data, menu_test_dir / "load", SaveLoadMode::load, 0, 6, + menu_bar.render(), true, SaveLoadFileKind::menu_layout, 52); + check(menu_load_picker.entries().size() == 1 && + menu_load_picker.entries()[0].path.extension() == ".MEN" && + !menu_load_picker.info_press(60,45), + "menu-layout picker filters to MEN and never interprets a layout as an FBM information header"); + menu_load_picker.click(60,45); menu_load_picker.click(60,45); + check(menu_load_picker.pending() && menu_load_picker.pending()->file_kind == SaveLoadFileKind::menu_layout && + menu_load_picker.pending()->origin_item_id == 52 && + menu_load_picker.pending()->path.extension() == ".MEN", + "MEN load request retains its typed file kind and source drawer identity"); + SaveLoadScreen menu_save_picker(data, menu_test_dir / "save", SaveLoadMode::save, 0, 6, + menu_bar.render(), true, SaveLoadFileKind::menu_layout, 52); + menu_save_picker.click(120,214); menu_save_picker.text("LAYOUT"); menu_save_picker.key("ENTER"); + check(menu_save_picker.pending() && menu_save_picker.pending()->file_kind == SaveLoadFileKind::menu_layout && + menu_save_picker.pending()->path.filename() == "LAYOUT.MEN" && + save_load_request_json(*menu_save_picker.pending()).find("\"file_kind\":\"menu_layout\"") != std::string::npos, + "MEN save request uses the native extension and an explicit JSON file-kind discriminator"); + std::filesystem::remove_all(menu_test_dir); + TextDb desk_texts = load_textd(asset_path(data,"TEXTD.BLK")); + auto match_game = g; match_game.texts = &desk_texts; + match_game.club_names.assign(32,0); + std::copy_n("UNITFC",6,match_game.club_names.begin()); + std::copy_n("TESTCITY",8,match_game.club_names.begin()+7); + std::copy_n("BREMEN",6,match_game.club_names.begin()+16); + match_game.club_ids[12]=0; match_game.club_ids[13]=7; match_game.club_ids[14]=16; + match_game.results.assign(9 * 0x17c, 0xcc); + check(desk_texts[(::bmh::layout::FixtureDesktopFirstLabelPointer-::bmh::layout::TextPointerTable)/4]==bmh::test::expected_text("desktop_tests.0") && + desk_texts[(::bmh::layout::FixtureDesktopSecondLabelPointer-::bmh::layout::TextPointerTable)/4]==bmh::test::expected_text("desktop_tests.1"), + "kind-61 rank suffix and strength label resolve from the Source TEXTD addresses"); + check(format_number(match_game,6,2)=="%6" && format_number(match_game,95,2)=="95", + "legacy routine width 2 keeps a transparent leading cell only for one-digit strength"); + const Font small_font=load_font(data/"F"/"BMH3.FNT"); + check(small_font.glyph('%').bit_width==0 && small_font.glyph('%').advance==5, + "FNT3 renders legacy routine's percent width placeholder as a leading space"); + auto ranked_game = match_game; + ranked_game.league_rounds[0] = 1; + ranked_game.position_history.resize(340); + write16(ranked_game.position_history, 12 * 13 * 2, 6); + write16(ranked_game.position_history, 13 * 13 * 2, 2); + auto ranked_desk = desk_from_game(ranked_game,exe,8); + check(ranked_desk.table_position==6 && ranked_desk.strength==90, + "desk projects Core table_position as a zero-based rank beside strength"); + auto current_club_game = ranked_game; + current_club_game.manager_teams[0] = 13; + write16(current_club_game.manager_records,0x290,13); + auto current_club_desk = desk_from_game(current_club_game,exe,8); + check(current_club_desk.runtime_club==13 && current_club_desk.club_name=="TESTCITY" && + current_club_desk.table_position==2, + "table rank follows the current runtime club identity after club remapping"); + auto rank_item_desk = ranked_desk; + rank_item_desk.items.clear(); + rank_item_desk.items.push_back({42,213,16,94,15,61,0,0,false,false}); + const auto ranked_image = DesktopScreen(data,rank_item_desk).render(); + auto unranked_item_desk = rank_item_desk; + unranked_item_desk.table_position.reset(); + const auto unranked_image = DesktopScreen(data,unranked_item_desk).render(); + int min_x=320, min_y=240, max_x=-1, max_y=-1; + for (int y=0;y<240;++y) for (int x=0;x<320;++x) + if (ranked_image.pixels[size_t(y)*320+x]!=unranked_image.pixels[size_t(y)*320+x]) { + min_x=std::min(min_x,x); min_y=std::min(min_y,y); + max_x=std::max(max_x,x); max_y=std::max(max_y,y); + } + check(max_x>=0 && min_x>=214 && max_x<307 && min_y==17 && max_y==22, + "rank changes only the centered Source kind-61 text line at its saved position and clip"); + auto flat_text_desk = rank_item_desk; + flat_text_desk.gradient_text=false; + check(DesktopScreen(data,flat_text_desk).render().pixels!=ranked_image.pixels, + "kind-61 rank and strength use the existing Source gradient text renderer"); + check(desk_json(ranked_desk).find("\"table_position\":6")!=std::string::npos && + desk_json(d).find("\"table_position\":null")!=std::string::npos, + "desk JSON reports the optional zero-based table position"); + MatchGroup league_fixture; league_fixture.desc.assign(0xd0,0); league_fixture.desc[0]=0; + write32(league_fixture.desc,0xcc,0); league_fixture.fixtures={12,13}; league_fixture.results={0xcc}; + std::vector prepared{league_fixture}; + auto matched = desk_from_game(match_game,exe,8,&prepared,34); + check(matched.next_opponent==13 && matched.next_competition==exe.u8(::bmh::layout::LeagueCalendarBits) && + matched.next_opponent_name=="TESTCITY" && matched.next_opponent_badge.has_value() && + !matched.next_opponent_badge_fallback, + "current prepared league fixture maps opponent, Source competition and badge"); + check(!matched.next_competition_label.empty(),"league fixture resolves Source label and matchday"); + auto setup_group = league_fixture; setup_group.results.clear(); + std::vector setup_groups{setup_group}; + auto setup_desk = desk_from_game(match_game,exe,8,&setup_groups,34); + check(setup_desk.next_opponent==13, + "fresh setup_matchday uses typed raw 0xCC season result when MatchGroup results are empty"); + auto played_game = match_game; played_game.results[0] = 0; + setup_desk = desk_from_game(played_game,exe,8,&setup_groups,34); + check(setup_desk.next_opponent==-1 && setup_desk.next_competition==34, + "fresh setup_matchday suppresses a fixture whose typed raw season result is played"); + matched.items.push_back({40,100,149,33,29,15,0,0,false,false}); + matched.items.push_back({41,140,149,33,29,17,0,0,false,false}); + check(DesktopScreen(data,matched).render().pixels.size()==320*240, + "resolved league opponent renders its Source competition, names and badge"); + auto played_league = league_fixture; + played_league.results={0}; played_league.kickoff_void_mask=0; + std::vector played_group{played_league}; + auto played_desk=desk_from_game(match_game,exe,8,&played_group,34); + check(played_desk.next_competition==34 && played_desk.next_opponent==-1 && + !played_desk.next_opponent_badge, + "Source played league result keeps competition default 34 and clears the opponent"); + auto later_played = played_league; later_played.fixtures={12,14}; + write32(later_played.desc,0xcc,2); + std::vector mixed_results{league_fixture,later_played}; + auto mixed_desk=desk_from_game(match_game,exe,8,&mixed_results,34); + check(mixed_desk.next_competition==exe.u8(::bmh::layout::LeagueCalendarBits) && mixed_desk.next_opponent==-1, + "later played fixture clears opponent while preserving the earlier competition write"); + auto away_game = match_game; + away_game.manager_records.at(0x28a) = 1; + auto away_fixture = league_fixture; away_fixture.fixtures={13,12}; + std::vector away_groups{away_fixture}; + auto away_desk = desk_from_game(away_game,exe,8,&away_groups,34); + check(away_desk.next_opponent==13 && away_desk.next_match_away, + "Source manager record +0x28a marks the manager's fixture as away"); + away_desk.items.push_back({40,100,149,33,29,15,0,0,false,false}); + auto rendered_away = DesktopScreen(data,away_desk).render(); + auto expected_order = away_desk; + std::swap(expected_order.club_name, expected_order.next_opponent_name); + expected_order.next_match_away = false; + check(rendered_away.pixels == DesktopScreen(data,expected_order).render().pixels, + "Source desk renders the home side before the away side for an away manager"); + MatchGroup cup_fixture; cup_fixture.desc.assign(0xd0,0); cup_fixture.desc[0]=6; + cup_fixture.fixtures={12,14}; cup_fixture.cup_results={0}; + prepared.push_back(cup_fixture); + matched = desk_from_game(match_game,exe,9,&prepared,34); + check(matched.next_opponent==14 && matched.next_competition==10 && + matched.next_opponent_name=="BREMEN", + "later matching group deterministically overrides earlier Source values"); + auto special_game=match_game;special_game.memory.add_block(::bmh::layout::CompetitionCalendar,2); + special_game.memory.set16(::bmh::layout::CompetitionCalendar,0x4006); + auto special=desk_from_game(special_game,exe,10,&prepared,34); + check(special.next_competition_label==desk_texts[(::bmh::layout::DeskState_FormatError_RuntimeField4-::bmh::layout::TextPointerTable)/4], + "Source calendar entry 4006 selects the special competition title"); + MatchGroup fallback_badge_group=cup_fixture;fallback_badge_group.fixtures={12,100}; + std::vector fallback_badge_groups{fallback_badge_group}; + auto fallback_badge=desk_from_game(match_game,exe,10,&fallback_badge_groups,34); + check(fallback_badge.next_opponent==100&&fallback_badge.next_opponent_badge_fallback&& + !fallback_badge.next_opponent_badge, + "legacy routine special team range uses its computer-portrait fallback"); + prepared.clear(); + auto other_fixture = league_fixture; other_fixture.fixtures={13,14}; prepared.push_back(other_fixture); + auto unmatched = desk_from_game(match_game,exe,10,&prepared,34); + check(unmatched.next_competition==34 && unmatched.next_opponent==-1, + "active-event fallback is competition 34 with the Source no-opponent portrait"); + check(unmatched.next_competition_label==desk_texts[(::bmh::layout::DeskState_DeskFromGame_TextPointer-::bmh::layout::TextPointerTable)/4+34] && + !unmatched.next_competition_detail.empty(), + "active-event no-opponent desk shows the Source free-day title and parenthesized first league"); + MatchGroup cup_fallback; cup_fallback.desc.assign(0xd0,0); cup_fallback.desc[0]=6; + cup_fallback.fixtures={13,14}; + std::vector cup_fallback_groups{cup_fallback}; + auto cup_day = desk_from_game(match_game,exe,10,&cup_fallback_groups,34); + const size_t cup_detail_id=(::bmh::layout::DeskState_FormatError_ExecutableField3-::bmh::layout::TextPointerTable)/4+cup_fallback.desc[0]; + check(cup_day.next_competition_detail=="("+desk_texts.strings.at(cup_detail_id)+")", + "free-day cup detail resolves its name through runtime TEXTD"); + check(!exe.cstring(::bmh::layout::DeskDrawers_Recent_TextPointer).empty(),"Source executable contains the opponent separator string"); + cup_day.items.push_back({40,100,149,33,29,15,0,0,false,false}); + cup_day.next_opponent=13; cup_day.next_opponent_name="TESTCITY"; + check(DesktopScreen(data,cup_day).render().pixels.size()==320*240, + "Source separator and runtime cup detail render on desk item 15"); + unmatched = desk_from_game(match_game,exe,11,&prepared,33); + check(unmatched.next_competition==33 && unmatched.next_opponent==-1, + "no-event desk retains Source defaults 33 and no opponent"); + unmatched = desk_from_game(match_game,exe,12,&prepared,32); + check(unmatched.next_competition==32 && unmatched.next_opponent==-1, + "season-end desk retains Source defaults 32 and no opponent"); + // The international-phase manager uses the special kNoTeam slot and + // the 24-player squad at 3072; projection is display-only. + auto nat = fixture(); nat.manager_teams[0] = kNoTeam; nat.memory.set32(::bmh::layout::CompetitionSelection,2); + nat.memory.set8(::bmh::layout::Desktops + 5 * 16 + 5,6); + for (int i=0;i<2;++i) { + const auto at=::bmh::layout::DesktopsUnsigned+uint32_t(i+6)*16; + nat.memory.set16(at,uint16_t(200+i*40)); nat.memory.set8(at+2,120); + nat.memory.set8(at+3,32); nat.memory.set8(at+4,25); nat.memory.set8(at+5,uint8_t(i?0:7)); + nat.memory.set8(at+12,uint8_t(i?22:14)); + } + nat.club_names = {'D','E','U','T','S','C','H','L','A','N','D',0}; + nat.club_ids[kNoTeam] = 0; nat.squad_slots.assign(3096,0x0fff); nat.players.resize(24); + nat.team_morale.resize(419,25); + for (int row=0; row<24; ++row) { + nat.squad_slots[3072 + row] = uint16_t(row | (row < 11 ? 0x8000 : row < 16 ? 0x4000 : 0)); + nat.players[row].w35c = 50 | (90 << 7) | (90 << 14); + nat.tactics[size_t(row)*0x58 + 0x0c] = 4; + } + const auto nat_seed = nat.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField); + const auto nat_records = nat.manager_records; + const auto nat_squads = nat.squad_slots; + auto nd = desk_from_game(nat,exe,41); + check(nd.national_team && nd.runtime_club==kNoTeam && nd.club_name=="DEUTSCHLAND" && nd.strength==90, + "national team identity and squad projection"); + check(nat_records==nat.manager_records && nat_squads==nat.squad_slots && nat.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)==nat_seed, + "national projection is read-only and drawless"); + check(std::count_if(nd.items.begin(),nd.items.end(),[](const DeskItem& item){return item.kind==14&&item.disabled;})==1 && + std::count_if(nd.items.begin(),nd.items.end(),[](const DeskItem& item){return item.kind==22&&item.disabled;})==1, + "national bank/stadium entries disabled"); + check(desk_json(nd).find("\"national_team\":true")!=std::string::npos,"national mode is exposed to UI clients"); + DesktopScreen national_desk(data,nd); + check(national_desk.key("A").kind==DeskRequestKind::open_menu,"national lineup remains available"); + national_desk.reject_action("test"); + check(national_desk.click(205,125).kind==DeskRequestKind::none,"national bank request is suppressed"); + check(national_desk.click(245,125).kind==DeskRequestKind::none,"national stadium request is suppressed"); + g.date = 1; g.memory.set32(::bmh::layout::CalendarDay,100); d = desk_from_game(g,exe,8); + check(d.date.day == 2 && d.day_counter == 1,"typed date overrides stale memory"); + g.date = 0; + g.tactics[0x0f] = 69; check(desk_from_game(g,exe,9).warnings[4] == false,"exhaustion 69"); + g.tactics[0x0f] = 70; check(desk_from_game(g,exe,9).warnings[4] == true,"exhaustion 70"); + g.tactics[0x0f] = 0; + g.manager_records[0xd9] = 8; check(desk_from_game(g,exe,9).warnings[7] == false,"important 8"); + g.manager_records[0xd9] = 9; check(desk_from_game(g,exe,9).warnings[7] == true,"important 9"); + g.manager_records[0xd9] = 0; + g.tactics[0x0c] = 3; check(desk_from_game(g,exe,9).warnings[8] == true,"contract below four months"); + g.tactics[0x0c] = 4; + g.manager_records[0xcb] = 14; check(desk_from_game(g,exe,9).warnings[3] == false,"training sum fourteen"); + g.manager_records[0xcb] = 15; check(desk_from_game(g,exe,9).warnings[3] == true,"training sum fifteen"); + g.manager_records[0xcb] = 0; + write16(g.stocks,0x50,2); write32(g.stocks,4,20); write16(g.stocks,0x4e,10); + check(desk_from_game(g,exe,9).warnings[0] == false,"stock break-even"); + write16(g.stocks,0x4e,11); check(desk_from_game(g,exe,9).warnings[0] == true,"stock profit"); + g.stocks.assign(0x450,0); + write32(g.manager_records,0x314,uint32_t(-6000000)); + check(desk_from_game(g,exe,9).warnings[9] == false,"licence six million boundary"); + write32(g.manager_records,0x314,uint32_t(-6000001)); + check(desk_from_game(g,exe,9).warnings[9] == true,"licence debt exceeds boundary"); + write32(g.manager_records,0x314,0); + auto invalid = fixture(); invalid.memory.set8(::bmh::layout::Desktops + 5 * 16 + 5,1); + rejected([&]{ desk_from_game(invalid,exe,0); }); + auto supported = d.options; supported.world = true; validate_desk_profile(supported); + supported.managers = 4; validate_desk_profile(supported); + auto wrong = d.options; wrong.managers = 5; rejected([&]{ validate_desk_profile(wrong); }); + wrong = d.options; wrong.world = false; wrong.league = false; rejected([&]{ validate_desk_profile(wrong); }); + + d = desk_from_game(g,exe,10); DesktopScreen desk(data,d); + const auto pixels = desk.render().pixels; + check(desk.render().pixels == pixels,"repeat render is deterministic"); + check(desk.click(5,23).kind == DeskRequestKind::none,"calendar handle must not advance a turn"); + auto action = desk.click(50,125); + check(action.kind == DeskRequestKind::open_menu && action.menu_kind == 3 && action.manager_slot == 0 && action.revision == 10,"lineup request"); + check(desk.click(20,40).kind == DeskRequestKind::none,"pending command blocks another turn"); + rejected([&]{ desk.acknowledge(d); }); + ++d.revision; desk.acknowledge(d); + check(desk.click(20,40).kind == DeskRequestKind::advance_turn,"open calendar advances"); + check(desk.click(20,40).kind == DeskRequestKind::none,"no duplicate advance request"); + ++d.revision; desk.acknowledge(d); + check(desk.click(165,125).kind == DeskRequestKind::advance_turn,"kickoff icon advances"); + check(desk.render().pixels == pixels,"commands cannot mutate the saved game view"); + desk.reject_action("unsupported_menu"); + check(!desk.pending() && desk.render().pixels == pixels,"rejected command preserves state"); + check(desk.key("A").menu_kind == 3,"original A hotkey opens lineup"); + desk.reject_action("not_implemented"); + check(desk.key("D").menu_kind == 18,"original D hotkey opens tactics"); + desk.reject_action("not_implemented"); + check(desk.key("I").menu_kind == 16 && desk_menu_name(16)=="training" && desk_menu_name(15)=="training_camp", + "original I and dispatch distinguish training from training camp"); + + StartupFlow flow(data); begin(flow); + auto result = CareerInitializationResult{d,{{0,0,12}}}; + result.desktop.source = "original_save_read_only"; + rejected([&]{ flow.attach_initialized_career(result); }); + + // The desk boundary accepts every UI-supported manager count only when + // all confirmed choices match contiguous engine slots and runtime clubs. + for(int count=1;count<=4;++count) { + StartupFlow multi_flow(data); confirm_managers(multi_flow,count); + const auto request=*multi_flow.pending_career(); + auto game=career_game(exe,request); auto career_desk=desk_from_game(game,exe,20); + std::vector initialized; + for(int slot=0;slot1) malformed.managers.back().slot=0; + else malformed.managers.clear(); + rejected([&]{multi_flow.attach_initialized_career(malformed);}); + check(multi_flow.pending_career()!=nullptr,"missing/duplicate slots leave the career request untouched"); + malformed=accepted; malformed.managers[0].master_club++; + rejected([&]{multi_flow.attach_initialized_career(malformed);}); + malformed=accepted; malformed.managers[0].runtime_club++; + rejected([&]{multi_flow.attach_initialized_career(malformed);}); + malformed=accepted; malformed.desktop.runtime_club++; + rejected([&]{multi_flow.attach_initialized_career(malformed);}); + if(count>1) { + auto duplicate_club=game; duplicate_club.manager_teams[1]=duplicate_club.manager_teams[0]; + rejected([&]{desk_from_game(duplicate_club,exe,20);}); + } + multi_flow.attach_initialized_career(accepted); + check(multi_flow.desktop() && multi_flow.desktop()->state().manager_teams.size()==size_t(count),"1-4 manager career attaches with explicit runtime map"); + if(count>=2) { + auto next_game=game; next_game.memory.set8(::bmh::layout::ActiveManager,1); + auto next=desk_from_game(next_game,exe,21); + next.league=uint8_t((request.managers[1].start_league+1)%9); + next.managers[1].league=next.league; + next.badge=8; next.managers[1].badge=8; // exercise a different W/*.VGA sheet + auto menu=multi_flow.send_key("A"); + check(menu.request==FlowRequest::desk_action,"manager action is pending before a handoff"); + rejected([&]{multi_flow.acknowledge_desk(next);}); + check(multi_flow.desktop()->pending().has_value() && multi_flow.desktop()->state().manager_slot==0,"ordinary action cannot switch managers"); + multi_flow.reject_desk_action("test action rejected"); + auto action=multi_flow.click(20,40); + check(action.request==FlowRequest::kickoff,"multi-manager turn action accepted"); + auto stale=next; stale.revision=20; + rejected([&]{multi_flow.acknowledge_desk(stale);}); + check(multi_flow.desktop()->pending().has_value() && multi_flow.desktop()->state().manager_slot==0,"stale handoff leaves request and previous manager intact"); + auto wrong_map=next; wrong_map.runtime_club=12; + rejected([&]{multi_flow.acknowledge_desk(wrong_map);}); + check(multi_flow.desktop()->pending().has_value(),"wrong runtime club does not consume handoff request"); + multi_flow.acknowledge_desk(next); + check(multi_flow.desktop()->state().manager_slot==1 && multi_flow.desktop()->state().runtime_club==13,"newer validated ACK can hand off to another manager"); + check(multi_flow.render().pixels.size()==320*240,"manager handoff loads the new badge sheet before rendering"); + } + } + StartupFlow national_flow(data); confirm_managers(national_flow,1,true); + auto national_request=*national_flow.pending_career(); + check(!national_request.options.league && national_request.options.world,"world-only UI setup is preserved"); + auto national_game=career_game(exe,national_request,true); + national_game.club_names={'D','E','U','T','S','C','H','L','A','N','D',0}; + national_game.club_ids[kNoTeam]=0; + national_game.squad_slots[3072]=0x8000; + auto national_projection=desk_from_game(national_game,exe,30); + auto national_manager=InitializedManager{0,national_request.managers[0].master_club,kNoTeam}; + national_flow.attach_initialized_career({national_projection,{national_manager},{}}); + check(national_flow.desktop()->state().national_team,"national career reaches the desktop with kNoTeam mapping"); + auto national_preparation=preparation_from_game(national_game,exe,30); + check(national_preparation.lineup.players.size()==24 && + national_preparation.lineup.runtime_club==kNoTeam && + national_preparation.tactics.runtime_club==kNoTeam, + "national career projects its special 24-player lineup and tactics"); + check(!national_preparation.training && !national_preparation.training_camp && + !national_preparation.bank && !national_preparation.stadium && + !national_preparation.toto && !national_preparation.pitch, + "national preparation omits club-only contexts"); + check(LineupScreen(data,national_preparation.lineup).render().pixels.size()==320*240 && + TacticsScreen(data,national_preparation.tactics).render().pixels.size()==320*240, + "national lineup and tactics render from the projected game state"); + check(national_preparation.player_cards.size()==1 && + national_preparation.player_cards[0].club_short_name=="DEUTSCHLAND", + "national player card retains the full country label"); + StartupFlow world_flow(data); confirm_managers(world_flow,1,true); + auto world_request=*world_flow.pending_career(); + auto world_game=career_game(exe,world_request); auto world_desk=desk_from_game(world_game,exe,40); + world_flow.attach_initialized_career({world_desk,{{0,world_request.managers[0].master_club,12}}, {}}); + check(world_flow.click(20,40).request==FlowRequest::kickoff,"world-only manager can reach an international phase"); + world_game.manager_teams[0]=kNoTeam; world_game.memory.set32(::bmh::layout::CompetitionSelection,2); + world_game.memory.set8(::bmh::layout::CoachActive,1); + world_game.memory.add_block(::bmh::layout::OriginalManagerCount,1); + world_game.memory.set8(::bmh::layout::OriginalManagerCount,1); + std::copy_n(world_game.manager_records.begin(),0xb0c,world_game.manager_records.begin()+4*0xb0c); + write16(world_game.manager_records,4*0xb0c+0x290,12); + std::copy_n("DEUTSCHLAND",11,world_game.club_names.begin()); + world_game.club_names[11]=0; + world_game.club_ids[kNoTeam]=0; + auto world_national=desk_from_game(world_game,exe,41); + check(world_national.managers[0].club_identity_key==world_desk.managers[0].club_identity_key, + "national duty preserves the stable home-club identity"); + world_flow.acknowledge_desk(world_national); + check(world_flow.desktop()->state().national_team && world_flow.desktop()->state().runtime_club==kNoTeam, + "single-manager world transition accepts the national runtime club"); + check(world_flow.click(20,40).request==FlowRequest::kickoff, + "national desk accepts the next turn request"); + auto other_home=world_game; other_home.manager_teams[0]=13; + write16(other_home.manager_records,0x290,13); + auto wrong_home=desk_from_game(other_home,exe,42); + rejected([&]{world_flow.acknowledge_desk(wrong_home);}); + check(world_flow.desktop()->pending().has_value() && world_flow.desktop()->state().national_team, + "national handback to another club is rejected without consuming the turn"); + world_game.manager_teams[0]=12; write16(world_game.manager_records,0x290,12); + auto home_handback=desk_from_game(world_game,exe,42); + world_flow.acknowledge_desk(home_handback); + check(!world_flow.desktop()->state().national_team && world_flow.desktop()->state().runtime_club==12, + "national duty returns to the same home club"); + check(flow.pending_career()!=nullptr,"rejected attachment preserves request"); + result.desktop.source = "engine_projection"; result.managers[0].master_club = 9; + rejected([&]{ flow.attach_initialized_career(result); }); + result.managers[0].master_club = 0; flow.attach_initialized_career(result); + check(flow.screen_name()=="desktop" && !flow.pending_career(),"accepted career reaches desktop"); + check(flow.state_json().find("\"engine_attached\":true") != std::string::npos,"engine attachment is explicit"); + rejected([&]{ flow.attach_initialized_career(result); }); + + StartupFlow results_flow(data); confirm_managers(results_flow,1); + const auto results_request=*results_flow.pending_career(); + auto results_game=career_game(exe,results_request); + std::fill_n(results_game.manager_records.begin()+0xc5,4,2); + std::fill_n(results_game.manager_records.begin()+0xc9,9,1); + auto results_desk=desk_from_game(results_game,exe,100); + results_flow.attach_initialized_career({results_desk, + {{0,results_request.managers[0].master_club,results_game.manager_teams[0]}},{}}); + results_flow.attach_preparation_context(preparation_from_game(results_game,exe,100)); + check(results_flow.click(20,40).request==FlowRequest::kickoff, + "prepared desktop emits one turn request before the result display"); + auto next_results_desk=desk_from_game(results_game,exe,101); + results_flow.acknowledge_desk(next_results_desk); + results_flow.attach_preparation_context(preparation_from_game(results_game,exe,101)); + MatchdayResults visible_results; visible_results.valid=true; visible_results.matchday=4; + visible_results.date=12; visible_results.date_label="12.07.2003"; + MatchdayResultGroup visible_group; visible_group.competition="Liga"; + visible_group.matches.push_back({"UNITFC","TESTCITY",2,1,MatchResultStatus::played}); + visible_results.groups.push_back(std::move(visible_group)); + results_flow.show_matchday_results(std::move(visible_results)); + check(results_flow.screen_name()=="matchday_results" && + results_flow.state_json().find("\"screen\":\"matchday_results\"")!=std::string::npos, + "results modal holds the prepared following desk"); + check(results_flow.click(20,40).request==FlowRequest::none && + results_flow.screen_name()=="matchday_results", + "desk input cannot start a second turn while results remain open"); + const auto closed_results=results_flow.send_key("ESC"); + check(closed_results.request==FlowRequest::results_closed && + results_flow.screen_name()=="desktop" && !results_flow.desktop()->pending(), + "Escape closes results without issuing another kickoff"); + + if (argc > 2 && std::string(argv[2]).size()) { + const auto original = read_file(argv[2]); + auto state = load_reference_desk(argv[2],exe); + check(state.manager_name=="BMHLAB" && state.runtime_club==12 && state.balance==6243300 && state.strength==86,"captured single-manager baseline"); + const std::array lamps{false,false,true,false,false,false,false,false,false,false}; + for (size_t i=0;i<10;++i) check(state.warnings[i]==lamps[i],"RAM-observed warning vector"); + StartupFlow reference(data); reference.load_reference(argv[2]); + check(reference.state_json().find("\"engine_attached\":false")!=std::string::npos,"reference is not a new career/attached engine"); + check(read_file(argv[2])==original,"original save unchanged after projection/render"); + // Loading replaces the confirmed-career choice source with the + // loaded runtime roster. Exercise a following turn and save ACK. + const auto temp_dir=std::filesystem::temp_directory_path() / + ("openbmh-u7b-load-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::filesystem::create_directories(temp_dir); + const auto staged_save=temp_dir/"BASELINE.FBM"; + std::filesystem::copy_file(argv[2],staged_save); + StartupFlow load_flow(data,temp_dir); + check(load_flow.click(214,215).request==FlowRequest::submenu_opened,"setup opens load dialog"); + load_flow.click(40,50); + check(load_flow.click(240,192).request==FlowRequest::file_action,"load dialog emits one file request"); + auto loaded=load_preparation_reference(staged_save,exe); + set_preparation_revision_source(loaded,1,"engine_projection"); + loaded.desktop.menu_layout_shortcut=DeskItem{53,286,215,12,11,53,0,0,false,false}; + loaded.desktop.shortcut_bar_always=false; + loaded.desktop.drawer_handles=true; + DeskItem calendar; calendar.id=50; calendar.kind=58; calendar.x=10; calendar.y=80; calendar.width=32; calendar.height=32; calendar.open=true; + DeskItem saver; saver.id=51; saver.kind=11; saver.x=60; saver.y=80; saver.width=32; saver.height=32; + loaded.desktop.items.push_back(calendar); loaded.desktop.items.push_back(saver); + { + DesktopScreen drag_screen(data,loaded.desktop); + drag_screen.pointer_down(65,85,true); + check(drag_screen.pointer_move(83,101),"desktop drag changes only the local preview before release"); + auto drag_request=drag_screen.pointer_up(83,101,true); + check(drag_request.kind==DeskRequestKind::change_layout && + drag_request.layout_operation==DeskLayoutOperation::move_item && + drag_request.layout_before!=drag_request.layout_after && drag_screen.pending().has_value(), + "desktop drag release emits an owner/revision-bound native layout request"); + DesktopScreen cancelled(data,loaded.desktop); + cancelled.pointer_down(65,85,true); cancelled.pointer_move(83,101); + check(cancelled.pointer_up(83,101,false).kind==DeskRequestKind::none && !cancelled.pending(), + "opposite-button release cancels the local drag without a native request"); + } + loaded.lineup.source=loaded.tactics.source="engine_projection"; + check(loaded.desktop.manager_teams.size()==size_t(loaded.desktop.options.managers),"loaded projection contains complete manager roster"); + auto stale_loaded=loaded; set_preparation_revision_source(stale_loaded,0,"engine_projection"); + rejected([&]{load_flow.attach_loaded_game(stale_loaded.desktop,stale_loaded);}); + check(load_flow.state_json().find("\"mode\":\"load\"")!=std::string::npos,"stale load leaves file request pending"); + load_flow.attach_loaded_game(loaded.desktop,loaded); + check(load_flow.desktop() && load_flow.state_json().find("\"engine_attached\":true")!=std::string::npos,"loaded projection attaches as authoritative manager baseline"); + auto turn=load_flow.click(15,85); + check(turn.request==FlowRequest::kickoff,"loaded desk accepts next-turn request"); + auto next_loaded=loaded; set_preparation_revision_source(next_loaded,2,"engine_projection"); + load_flow.acknowledge_desk(next_loaded.desktop); + auto open_save=load_flow.click(65,85); + check(open_save.request==FlowRequest::submenu_opened,"loaded manager can open save dialog"); + load_flow.click(240,192); load_flow.click(240,192); + check(load_flow.state_json().find("\"action\":\"save\"")!=std::string::npos,"save dialog emits save request"); + auto saved=next_loaded; set_preparation_revision_source(saved,3,"engine_projection"); + load_flow.acknowledge_saved_game(saved.desktop,saved); + check(load_flow.desktop()->state().revision==3,"save ACK retains loaded multi-view manager baseline"); + load_flow.click(64,239); + auto open_menu_save=load_flow.click(292,221); + check(open_menu_save.request==FlowRequest::submenu_opened && open_menu_save.desk_action.menu_kind==53 && + !load_flow.pending_file(), + "Source last-cell record-53 left action opens the MEN save picker before a request exists"); + load_flow.click(120,214); load_flow.text("MENU"); load_flow.send_key("ENTER"); + check(load_flow.pending_file() && load_flow.pending_file()->file_kind==SaveLoadFileKind::menu_layout && + load_flow.pending_file()->origin_item_id==53 && load_flow.pending_file()->action==SaveLoadAction::save && + load_flow.pending_file()->path.extension()==".MEN", + "submitting a filename emits a typed MEN save request with the Source suffix and record-53 origin"); + { std::ofstream(load_flow.pending_file()->path) << "menu-layout fixture"; } + auto menu_saved=saved; set_preparation_revision_source(menu_saved,4,"engine_projection"); + load_flow.acknowledge_menu_layout(menu_saved.desktop,menu_saved); + check(load_flow.desktop()->state().revision==4 && load_flow.desktop()->state().manager_teams==saved.desktop.manager_teams, + "MEN acknowledgement advances the UI revision while retaining active career ownership"); + load_flow.click(64,239); + auto open_menu_load=load_flow.click(292,221,true); + check(open_menu_load.request==FlowRequest::submenu_opened && !load_flow.pending_file(), + "Source last-cell record-53 right action opens the MEN load picker before a request exists"); + load_flow.click(60,49); load_flow.click(60,49); + check(load_flow.pending_file() && load_flow.pending_file()->file_kind==SaveLoadFileKind::menu_layout && + load_flow.pending_file()->origin_item_id==53 && load_flow.pending_file()->action==SaveLoadAction::load, + "selecting the saved MEN entry emits the typed load request"); + rejected([&]{load_flow.attach_loaded_game(menu_saved.desktop,menu_saved);}); + load_flow.reject_file_action("cancelled MEN fixture load"); + std::cout << "Original LABA0012 baseline verified.\n"; + } + std::cout << "Desktop projection, calendar, command boundary and career attachment tests passed.\n"; + return 0; + } catch (const std::exception& e) { std::cerr << "desktop test: " << e.what() << '\n'; return 1; } +} diff --git a/src/ui/environment.cpp b/src/ui/environment.cpp new file mode 100644 index 0000000..9ca40af --- /dev/null +++ b/src/ui/environment.cpp @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/environment.hpp" + +#include +#include + +#include "formats/savestate.hpp" +#include "game/messages.hpp" +#include "game/state.hpp" +#include "ui/manager.hpp" + +namespace bmh::ui { +namespace { +void crop(Image& dst, const Image& src, int sx, int sy, int dx, int dy, int w, int h, int transparent = -1) { + for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { + const int tx = dx + x, ty = dy + y, px = sx + x, py = sy + y; + if (tx < 0 || ty < 0 || tx >= dst.width || ty >= dst.height || + px < 0 || py < 0 || px >= src.width || py >= src.height) continue; + const uint8_t c = src.pixels[size_t(py) * size_t(src.width) + size_t(px)]; + if (c != transparent) dst.at(tx, ty) = c; + } +} + +int text_width(const LeImage& exe, std::string_view text) { + int width = 0; + for (unsigned char c : text) { + const unsigned glyph = c < 128 ? exe.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c) : 0; + width += glyph ? int(exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2)) : 2; + } + return width; +} + +void sprite_text(Image& out, const Image& atlas, const LeImage& exe, int x, int baseline, + std::string_view value, int font) { + for (unsigned char c : value) { + if (c <= 31 || c >= 128) { x += 2; continue; } + const int glyph = exe.u8(::bmh::layout::ClubInfo_Raw_RuntimeField3 + c); + if (!glyph) { x += 2; continue; } + const int sx = exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField + glyph * 2); + const int w = exe.u16(::bmh::layout::ClubInfo_Raw_RuntimeField2 + glyph * 2) - sx; + crop(out, atlas, sx, (font - 4) * 7, x, baseline - 6, w, 7, 0); + x += w; + } +} + +const char* result_name(EnvironmentRequestKind kind) { + return kind == EnvironmentRequestKind::set_item ? "set_environment" : "none"; +} +bool generic_badge(int club) { + // SourceBadgeFallback gates on the runtime club ID, before looking up its W sprite. + const unsigned team = unsigned(club) & 0xfff; + return team == 0xfff || (team >= 90 && team <= 137) || (team >= 168 && team <= 356); +} +} // namespace + +EnvironmentView environment_from_game(const bmh::GameState& game, uint64_t revision) { + const int manager = game.memory.u8(::bmh::layout::ActiveManager); + if (manager < 0 || size_t(manager) >= game.manager_teams.size()) + throw FormatError("environment: active manager is outside the source roster"); + const int team = game.manager_teams[size_t(manager)]; + if (team < 0 || team == kNoTeam) throw FormatError("environment: no club environment for this manager"); + EnvironmentView view; + view.manager_slot = manager; + view.runtime_club = team; + view.revision = revision; + view.club_name = game.club_name(team); + if (game.club_heap_78.size() < size_t(team + 1) * 2) + throw FormatError("environment: missing Source club badge mapping"); + view.badge_sprite = (uint16_t(game.club_heap_78[size_t(team) * 2]) | + uint16_t(game.club_heap_78[size_t(team) * 2 + 1]) << 8) & 0x1ff; + view.values = bmh::environment_state(game, manager); + for (int i = 0; i < kEnvironmentItems; ++i) + view.cost_text[size_t(i)] = bmh::format_number(game, view.values.monthly[size_t(i)], 0x185); + view.decorated_background = !game.memory.has(::bmh::layout::PlainBackground) || game.memory.u8(::bmh::layout::PlainBackground) == 0; + view.gradient_text = (!game.memory.has(::bmh::layout::TextGradientDisabled) || game.memory.u8(::bmh::layout::TextGradientDisabled) == 0); + view.solid_panel_background = game.memory.has(::bmh::layout::SolidPanelBackground) && game.memory.u8(::bmh::layout::SolidPanelBackground) != 0; + view.plain_background = game.memory.has(::bmh::layout::PlainBackground) && game.memory.u8(::bmh::layout::PlainBackground) != 0; + return view; +} + +TaxDialogProjection environment_notice_dialog(const bmh::GameState& game, int manager, + std::string body) { + if (manager < 0 || size_t(manager) >= game.manager_teams.size()) + throw FormatError("environment notice: invalid manager"); + const size_t record = size_t(manager) * 0xb0c; + if (record + 0x222 >= game.manager_records.size()) + throw FormatError("environment notice: truncated manager record"); + TaxDialogProjection view; + view.kind = TaxDialogKind::acknowledgement; + // Uint8T6 -> SDLFlushEvents3 adds the active manager's 0x40 timed-notice flags. + view.source_manager_flags = uint8_t(manager) | 0x40; + view.source_flags = 0; + view.compact_dialog_frame = game.memory.has(::bmh::layout::CompactDialogFrame) && game.memory.u8(::bmh::layout::CompactDialogFrame) != 0; + view.body = std::move(body); + const auto first = game.manager_records.begin() + static_cast(record + 0xa8); + const auto last = std::find(first, first + 26, uint8_t(0)); + view.manager_name.assign(first, last); + view.portrait = game.manager_records[record + 0x221]; + // PresentManagerDialog delegates to SourceBadgeFallback: fallback depends on the runtime club, + // not the W-atlas selector. W/0 sprite 0 is a valid club badge. + const int team = game.manager_teams[size_t(manager)] & 0xfff; + view.badge_fallback = generic_badge(team); + if (!view.badge_fallback) { + if (game.club_heap_78.size() < size_t(team + 1) * 2) + throw FormatError("environment notice: truncated club badge table"); + view.badge_sprite = (uint16_t(game.club_heap_78[size_t(team) * 2]) | + uint16_t(game.club_heap_78[size_t(team) * 2 + 1]) << 8) & 0x1ff; + } + return view; +} + +std::string environment_view_json(const EnvironmentView& s) { + std::ostringstream out; + out << "{\"manager_slot\":" << s.manager_slot << ",\"runtime_club\":" << s.runtime_club + << ",\"revision\":" << s.revision << ",\"badge_sprite\":" << s.badge_sprite << ",\"monthly\":["; + for (size_t i = 0; i < s.values.monthly.size(); ++i) { if (i) out << ','; out << s.values.monthly[i]; } + out << "],\"level\":["; + for (size_t i = 0; i < s.values.level.size(); ++i) { if (i) out << ','; out << s.values.level[i]; } + out << "],\"youth_price\":" << s.values.youth_price << ",\"youth_paid\":" + << (s.values.youth_paid ? "true" : "false") << ",\"youth_open\":" + << (s.values.youth_open ? "true" : "false") << '}'; + return out.str(); +} + +std::string environment_request_json(const EnvironmentRequest& r) { + std::ostringstream out; + out << "{\"kind\":" << json_quote(result_name(r.kind)) << ",\"manager_slot\":" << r.manager_slot + << ",\"runtime_club\":" << r.runtime_club << ",\"revision\":" << r.revision + << ",\"request_id\":" << r.request_id << ",\"item\":" << r.item << ",\"level\":" << r.level + << ",\"owner\":" << desk_request_json(r.owner) << '}'; + return out.str(); +} + +EnvironmentScreen::EnvironmentScreen(const std::filesystem::path& data, EnvironmentView state, Image underlay) + : state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + background_(load_vga(asset_path(data / "KB", "129.VGA"))), + tiles_(load_vga(asset_path(data / "KB", "19.VGA"))), panel_(load_vga(asset_path(data / "KB", "56.VGA"))), + letters_(load_vga(asset_path(data / "KB", "54.VGA"))), + badge_atlas_(load_vga(asset_path(data / (generic_badge(state_.runtime_club) ? "KB" : "W"), + generic_badge(state_.runtime_club) ? "0.VGA" : std::to_string(state_.badge_sprite >> 3) + ".VGA"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))) { + if (state_.manager_slot < 0 || state_.manager_slot > 3 || state_.runtime_club < 0 || + underlay.width != 320 || underlay.height != 240 || background_.width != 320 || + background_.height != 240 || tiles_.width != 306 || tiles_.height != 111 || + panel_.width <= 0 || texts_.strings.size() != TEXT_COUNT) + throw FormatError("environment: unsupported owner or Original assets"); +} + +void EnvironmentScreen::text(Image& out, int x, int baseline, std::string_view value, + uint8_t color, bool gradient) const { + const int y = baseline - font_.baseline; + if (x < 0 || y < 0 || y + font_.height > out.height || + x + font_.text_width(value) > out.width) return; + if (!gradient || !state_.gradient_text || exe_.u8(::bmh::layout::TextGradientMode) != 2 || color == 0x40) { + font_.draw(out, x, y, value, color); + return; + } + unsigned slot = 0; + while (slot < 32 && exe_.u8(::bmh::layout::Advertising_Text_RuntimeField2 + slot) != color) ++slot; + if (slot >= 32) { font_.draw(out, x, y, value, color); return; } + Image mask(std::max(1, font_.text_width(value)), font_.height, 0); + font_.draw(mask, 0, 0, value, 1); + for (int row = 0; row < mask.height; ++row) + for (int col = 0; col < mask.width; ++col) + if (mask.at(col, row)) out.at(x + col, y + row) = exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + slot * 6 + std::min(row, 5)); +} + +Image EnvironmentScreen::render() const { + // Image -> PlainWindowFrameUsedBy starts a new player background, not the desk's + // controls. Its null CareerSession_ApplyBalanceSourceStyle_ExecutableField path chooses KB129 or the PlainBackground flat frame. + Image out = state_.decorated_background && !state_.plain_background ? background_ : Image(320, 240, 0); + if (!state_.decorated_background || state_.plain_background) { + for (int y = 4; y <= 16; ++y) for (int x = 0; x < 320; ++x) out.at(x, y) = 0x44; + for (int y = 5; y <= 15; ++y) for (int x = 1; x <= 318; ++x) out.at(x, y) = 0x39; + for (int y = 228; y <= 237; ++y) for (int x = 0; x < 320; ++x) out.at(x, y) = 0x44; + for (int y = 229; y <= 236; ++y) for (int x = 1; x <= 318; ++x) out.at(x, y) = 0x39; + } + sprite_text(out, letters_, exe_, 172 + (282 - 172) / 2 - text_width(exe_, texts_[text_id(::bmh::layout::Environment_Render_TextPointer)]) / 2, + 13, texts_[text_id(::bmh::layout::Environment_Render_TextPointer)], 5); + sprite_text(out, letters_, exe_, 5, 235, state_.club_name, 5); + // CopyCrop -> UsesForTheseSprites compares DesktopRuntimeField=0; ff is its blit mode. + crop(out, tiles_, 0, 0, 0x7d, 0x52, 0x47, 0x46, 0); + // SourceBadgeFallback first adds its PaintsFourBorderEdges frame, then an opaque FormatError2 crop. + for (int y = 96; y <= 135; ++y) out.at(139, y) = 0x46; + for (int x = 139; x <= 178; ++x) out.at(x, 96) = 0x46; + for (int x = 139; x <= 178; ++x) out.at(x, 135) = 0x40; + for (int y = 96; y <= 135; ++y) out.at(178, y) = 0x40; + // KB0 has a narrower atlas than W; validate the selected crop, not the + // full eight-cell W strip, before drawing the generic Source badge. + const int badge_x = generic_badge(state_.runtime_club) ? 8 : int(state_.badge_sprite & 7) * 38; + if (badge_atlas_.width < badge_x + 38 || badge_atlas_.height < 38) + throw FormatError("environment: Original badge crop outside atlas"); + crop(out, badge_atlas_, badge_x, 0, 0x8c, 0x61, 0x26, 0x26); + for (int item = 0; item < kEnvironmentItems; ++item) { + // OpenBMH deviates from the original: omits the two discontinued youth groups from the environment screen. +// supported rule profile BypassesTwoDiscontinuedYouthGroups bypasses the two discontinued youth groups. + if (item < 3 && item != kYouthAcademy) continue; + const int x = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField + item), y = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + item); + crop(out, tiles_, item * 0x33, 0x46, x, y, 0x33, 0x29); + // CallsTwiceForUpperLowerCaptionStrips calls LoadGameEndTaxAnimationAssets twice for the upper and lower caption strips. + // Match its KB/56-backed panel mode and its SolidPanelBackground flat-fill branch. + const auto panel = [&](int left, int top, int right, int bottom) { + if (state_.solid_panel_background) { + for (int yy = top + 1; yy < bottom; ++yy) + for (int xx = left + 1; xx < right; ++xx) out.at(xx, yy) = 0x42; + } else { + crop(out, panel_, left, top - 19, left + 1, top + 1, + right - left - 1, bottom - top - 1); + } + for (int xx = left; xx <= right; ++xx) out.at(xx, top) = 0x46; + for (int yy = top; yy <= bottom; ++yy) out.at(left, yy) = 0x46; + for (int xx = left; xx <= right; ++xx) out.at(xx, bottom) = 0x40; + for (int yy = top; yy <= bottom; ++yy) out.at(right, yy) = 0x40; + }; + panel(x - 4, y - 10, x + 0x36, y - 1); + panel(x - 4, y + 0x29, x + 0x36, y + 0x31); + const int unit = item == kYouthAcademy ? 1 : item >= 3 ? 5000 : 1; + const int count = item == kYouthAcademy ? (state_.values.monthly[size_t(item)] != 0 ? 6 : 0) + : std::clamp(state_.values.monthly[size_t(item)] / unit, 0, 6); + for (int star = 0; star < count; ++star) + crop(out, tiles_, 0x1e, 0x1e, x + star * 9, y - 8, 7, 6, 0); + // The tile artwork already contains its Source caption. CallsTwiceForUpperLowerCaptionStrips draws + // the dynamic expense in the lower strip at baseline y+0x30; a second + // invented TEXTD caption here overwrote the baked-in names and shifted + // the cost down into the hit area. + const auto& cost = state_.cost_text[size_t(item)]; + text(out, x + 0x32 / 2 - font_.text_width(cost) / 2, y + 0x30, cost, 0x6b); + } + return out; +} + +bool EnvironmentScreen::pointer_down(int x, int y, bool right) { + press_seen_ = true; + pending_.reset(); + pressed_item_ = pressed_level_ = -1; + pressed_right_ = right; + if (right) return true; + for (int item = 0; item < kEnvironmentItems; ++item) { + const int left = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField + item), top = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + item); + if (x >= left - 9 && x <= left + 0x36 && y >= top - 10 && y <= top + 0x29) { + pressed_item_ = item; + pressed_level_ = std::clamp((x - left + 4) / 9, 0, 6); + return true; + } + } + return false; +} + +EnvironmentRequest EnvironmentScreen::release(int x, int y, bool right) { + const bool had_press = press_seen_; + const bool was_right = pressed_right_; + press_seen_ = false; + if (had_press && was_right && right) { close_requested_ = true; pressed_right_ = false; return {}; } + if (!had_press || was_right || right || pressed_item_ < 0) { pressed_right_ = false; pressed_item_ = -1; return {}; } + const int item = pressed_item_, level = pressed_level_; + pressed_item_ = pressed_level_ = -1; + const int left = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField + item), top = exe_.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + item); + if (x < left - 9 || x > left + 0x36 || y < top - 10 || y > top + 0x29) return {}; + EnvironmentRequest r{EnvironmentRequestKind::set_item, state_.manager_slot, state_.runtime_club, + item, level, state_.revision, next_request_id_++}; + r.owner = state_.owner; + pending_ = r; + return r; +} + +EnvironmentRequest EnvironmentScreen::click(int x, int y, bool right) { + if (!press_seen_) pointer_down(x, y, right); + return release(x, y, right); +} + +EnvironmentRequest EnvironmentScreen::key(std::string_view key) { + // Keep an issued level change or a physical press with its own ACK/release. + if (pending_ || press_seen_) return {}; + if (key == "ESC" || key == "Escape") close_requested_ = true; + return {}; +} + +void EnvironmentScreen::acknowledge(EnvironmentView updated) { + const bool unchanged = pending_ && updated.revision == state_.revision && + environment_view_json(updated) == environment_view_json(state_); + if (!pending_ || pending_->manager_slot != updated.manager_slot || pending_->runtime_club != updated.runtime_club || + pending_->revision != state_.revision || (!unchanged && updated.revision != state_.revision + 1) || + updated.owner.manager_slot != state_.owner.manager_slot || updated.owner.menu_kind != 24 || + updated.owner.revision != updated.revision) + throw FormatError("environment: acknowledgement does not match the pending action"); + state_ = std::move(updated); + pending_.reset(); + feedback_.clear(); +} + +void EnvironmentScreen::reject_action(std::string reason) { + if (!pending_) throw FormatError("environment: rejection without a pending action"); + pending_.reset(); feedback_ = std::move(reason); +} + +std::string EnvironmentScreen::state_json() const { + return "{\"screen\":\"environment\",\"state\":" + environment_view_json(state_) + + ",\"close_requested\":" + (close_requested_ ? "true" : "false") + + ",\"pending\":" + (pending_ ? environment_request_json(*pending_) : "null") + "}"; +} + +} // namespace bmh::ui diff --git a/src/ui/environment.hpp b/src/ui/environment.hpp new file mode 100644 index 0000000..c2c3472 --- /dev/null +++ b/src/ui/environment.hpp @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/environment.hpp" +#include "ui/game_end.hpp" +#include "ui/desktop.hpp" + +namespace bmh::ui { + +struct EnvironmentView { + EnvironmentState values; + int manager_slot = -1; + int runtime_club = -1; + uint64_t revision = 0; + std::string club_name; + uint16_t badge_sprite = 0; + std::array cost_text{}; + bool decorated_background = true; + bool gradient_text = true; + bool solid_panel_background = false; + bool plain_background = false; + DeskRequest owner{}; +}; + +EnvironmentView environment_from_game(const bmh::GameState&, uint64_t revision); +TaxDialogProjection environment_notice_dialog(const bmh::GameState&, int manager_slot, + std::string exact_source_body); + +enum class EnvironmentRequestKind : uint8_t { none, set_item }; +struct EnvironmentRequest { + EnvironmentRequestKind kind = EnvironmentRequestKind::none; + int manager_slot = -1, runtime_club = -1, item = -1, level = -1; + uint64_t revision = 0, request_id = 0; + DeskRequest owner{}; + bool operator==(const EnvironmentRequest&) const = default; +}; + +std::string environment_view_json(const EnvironmentView&); +std::string environment_request_json(const EnvironmentRequest&); + +class EnvironmentScreen { +public: + EnvironmentScreen(const std::filesystem::path& data, EnvironmentView state, Image underlay); + Image render() const; + bool pointer_down(int x, int y, bool right = false); + EnvironmentRequest release(int x, int y, bool right = false); + EnvironmentRequest click(int x, int y, bool right = false); + EnvironmentRequest key(std::string_view key); + const EnvironmentView& state() const { return state_; } + const std::optional& pending() const { return pending_; } + bool close_requested() const { return close_requested_; } + void acknowledge(EnvironmentView); + void reject_action(std::string); + void set_feedback(std::string text) { feedback_ = std::move(text); } + std::string state_json() const; +private: + EnvironmentView state_; + LeImage exe_; + TextDb texts_; + Image background_, tiles_, panel_, letters_, badge_atlas_; + Font font_; + bool close_requested_ = false; + bool pressed_right_ = false; + bool press_seen_ = false; + int pressed_item_ = -1, pressed_level_ = -1; + uint64_t next_request_id_ = 1; + std::optional pending_; + std::string feedback_; + void text(Image&, int, int, std::string_view, uint8_t, bool gradient = true) const; +}; + +} // namespace bmh::ui diff --git a/src/ui/environment_tests.cpp b/src/ui/environment_tests.cpp new file mode 100644 index 0000000..e803023 --- /dev/null +++ b/src/ui/environment_tests.cpp @@ -0,0 +1,234 @@ +#include "../../tests/runtime_fixture_tables.hpp" +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/environment.hpp" + +#include +#include +#include + +#include "formats/savestate.hpp" +#include "formats/fbm.hpp" +#include "game/career.hpp" +#include "game/messages.hpp" +#include "game/state.hpp" +#include "ui/desk_state.hpp" +#include "ui/manager.hpp" +#include "ui/sprite_font.hpp" + +using namespace bmh; +using namespace bmh::ui; + +namespace { +void check(bool ok, const char* message) { + if (!ok) throw std::runtime_error(message); +} +uint8_t pixel(const Image& image, int x, int y) { + return image.pixels.at(size_t(y) * size_t(image.width) + size_t(x)); +} +void original_pixels(const std::filesystem::path& data, const LeImage& exe, + const TextDb& texts, EnvironmentView state) { + const auto player = load_vga(asset_path(data / "KB", "129.VGA")); + const auto art = load_vga(asset_path(data / "KB", "19.VGA")); + const auto panel = load_vga(asset_path(data / "KB", "56.VGA")); + const auto body = load_font(asset_path(data / "F", "BMH3.FNT")); + SpriteFont sprite(data); + // All four visible groups exercise an empty and an occupied star rail. + state.values.monthly[1] = 0; + for (int item = 3; item < 6; ++item) state.values.monthly[size_t(item)] = 10000; + for (int mode = 0; mode < 3; ++mode) { + state.decorated_background = mode != 1; + state.plain_background = mode == 2; + state.solid_panel_background = mode == 2; + state.gradient_text = mode != 2; + auto actual = EnvironmentScreen(data, state, Image(320, 240, 0xe1)).render(); + const auto other_desk = EnvironmentScreen(data, state, Image(320, 240, 0x31)).render(); + check(actual.pixels == other_desk.pixels, "environment never inherits desk controls or notices"); + Image base = mode == 0 ? player : Image(320, 240, 0); + if (mode != 0) { + for (int y = 4; y <= 16; ++y) for (int x = 0; x < 320; ++x) + base.at(x, y) = x > 0 && x < 319 && y > 4 && y < 16 ? 0x39 : 0x44; + for (int y = 228; y <= 237; ++y) for (int x = 0; x < 320; ++x) + base.at(x, y) = x > 0 && x < 319 && y > 228 && y < 237 ? 0x39 : 0x44; + } + const auto title = original_to_utf8(texts[text_id(::bmh::layout::Environment_Render_TextPointer)]); + sprite.draw(base, 227 - sprite.text_width(title) / 2, 13, title, 5); + sprite.draw(base, 5, 235, original_to_utf8(state.club_name), 5); + for (int y = 0; y < 240; ++y) for (int x = 0; x < 320; ++x) { + bool foreground = x >= 125 && x <= 195 && y >= 82 && y <= 151; + for (int item : {1, 3, 4, 5}) { + const int tx = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField + item), ty = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + item); + foreground |= x >= tx - 4 && x <= tx + 54 && y >= ty - 10 && y <= ty + 49; + } + if (!foreground) check(pixel(actual, x, y) == pixel(base, x, y), + "Source KB129/flat background, centered title and active club footer"); + } + int transparent_center = 0, center_ink = 0; + for (int y = 0; y < 70; ++y) for (int x = 0; x < 71; ++x) { + const int dx = 125 + x, dy = 82 + y; + if (dx >= 139 && dx <= 178 && dy >= 96 && dy <= 135) continue; + const auto ink = pixel(art, x, y); + transparent_center += ink == 0; + center_ink += ink != 0; + check(pixel(actual, dx, dy) == (ink ? ink : pixel(base, dx, dy)), + "legacy routine central art compares index0, preserving player background"); + } + check(transparent_center > 0 && center_ink > 0, "central crop oracle covers transparent and ink pixels"); + check(actual.at(139, 96) == 0x46 && actual.at(178, 96) == 0x40 && + actual.at(139, 135) == 0x40, "Source badge frame and corner overwrite order"); + for (int item : {1, 3, 4, 5}) { + const int tx = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField + item), ty = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + item); + for (int y = 0; y < 41; ++y) for (int x = 0; x < 51; ++x) + check(pixel(actual, tx + x, ty + y) == pixel(art, item * 51 + x, 70 + y), + "legacy routine tile is opaque, without a fabricated c0 comparekey"); + // The Source upper panel is copied first; each nonzero star pixel + // replaces it. A zero in the star bitmap exposes that panel. + const int stars = item == 1 ? 0 : 2; + for (int y = ty - 9; y <= ty - 2; ++y) for (int x = tx - 3; x <= tx + 53; ++x) { + uint8_t expected = state.solid_panel_background ? 0x42 : pixel(panel, x - 1, y - 20); + for (int n = 0; n < stars; ++n) + if (x >= tx + n * 9 && x < tx + n * 9 + 7 && y >= ty - 8 && y < ty - 2) { + const auto ink = pixel(art, 30 + x - tx - n * 9, 30 + y - ty + 8); + if (ink) expected = ink; + } + check(pixel(actual, x, y) == expected, "Source star zero pixels expose the opaque KB56/flat rail"); + } + const auto& cost = state.cost_text[size_t(item)]; + const int width = body.text_width(cost), left = tx + 25 - width / 2; + Image mask(width, body.height); + body.draw(mask, 0, 0, cost, 1); + unsigned ramp = 0; + while (ramp < 32 && exe.u8(::bmh::layout::Advertising_Text_RuntimeField2 + ramp) != 0x6b) ++ramp; + for (int y = ty + 42; y <= ty + 48; ++y) for (int x = tx - 3; x <= tx + 53; ++x) { + uint8_t expected = state.solid_panel_background ? 0x42 : pixel(panel, x - 1, y - 20); + const int mx = x - left, my = y - (ty + 48 - body.baseline); + if (mx >= 0 && mx < width && my >= 0 && my < body.height && pixel(mask, mx, my)) + expected = state.gradient_text && exe.u8(::bmh::layout::TextGradientMode) == 2 && ramp < 32 + ? exe.u8(::bmh::layout::Advertising_Text_RuntimeField + ramp * 6 + unsigned(my)) : 0x6b; + check(pixel(actual, x, y) == expected, "Source cost strip uses Font3, exact centering and gradient toggle"); + } + } + } +} +void original_badges(const std::filesystem::path& data, EnvironmentView state) { + const auto source_w = load_vga(asset_path(data / "W", std::to_string(state.badge_sprite >> 3) + ".VGA")); + const auto source_kb0 = load_vga(asset_path(data / "KB", "0.VGA")); + // Explicit boundary cases from legacy routine; the expected selection does not + // call or recreate the presenter's gate. The W sprite stays identical. + struct Case { int team; bool generic; }; + const Case fixtures[]{{0, false}, {89, false}, {90, true}, {137, true}, + {138, false}, {167, false}, {168, true}, {356, true}, {357, false}, + {4094, false}, {4095, true}, {0x1000 + 89, false}, {0x1000 + 90, true}}; + for (const Case fixture : fixtures) { + state.runtime_club = fixture.team; + auto frame = EnvironmentScreen(data, state, Image(320, 240, 0xe1)).render(); + const auto& expected = fixture.generic ? source_kb0 : source_w; + const int sx = fixture.generic ? 8 : int(state.badge_sprite & 7) * 38; + for (int y = 0; y < 38; ++y) for (int x = 0; x < 38; ++x) + check(pixel(frame, 140 + x, 97 + y) == pixel(expected, sx + x, y), + "Source runtime team gate selects the complete opaque KB0 or W badge crop"); + check(frame.at(139, 96) == 0x46 && frame.at(178, 96) == 0x40 && + frame.at(139, 135) == 0x40, "both badge paths retain the Source frame"); + } + // A generic club must not try to load its irrelevant W sprite at all. + state.runtime_club = 90; + state.badge_sprite = 0xffff; + auto generic = EnvironmentScreen(data, state, Image(320, 240)).render(); + for (int y = 0; y < 38; ++y) for (int x = 0; x < 38; ++x) + check(pixel(generic, 140 + x, 97 + y) == pixel(source_kb0, 8 + x, y), + "generic Source badge ignores the W sprite mapping"); +} +} + +int main(int argc, char** argv) { + try { + check(argc == 3, "usage: ui_environment_tests ORIGINAL_DATA SAVEGAME"); + const std::filesystem::path data(argv[1]); + const auto exe = bmh::test::load_executable(asset_path(data, "BMH.exe")); + const auto saved = load_savegame(argv[2]); + const DbCounts counts{exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)}; + GameState game = GameState::from_save(SaveState(saved.stream, counts), counts); + competition_pointers(game.memory, exe); + const auto texts = load_textd(asset_path(data, "TEXTD.BLK")); + game.texts = &texts; + + auto state = environment_from_game(game, 17); + DeskRequest owner; + owner.kind = DeskRequestKind::open_menu; + owner.menu_kind = 24; + owner.manager_slot = state.manager_slot; + owner.revision = state.revision; + state.owner = owner; + original_pixels(data, exe, texts, state); + original_badges(data, state); + EnvironmentScreen screen(data, state, Image(320, 240, 0)); + auto frame = screen.render(); + check(frame.width == 320 && frame.height == 240, "Original environment frame dimensions"); + + const int x = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField + 3), y = exe.u8(::bmh::layout::Environment_FormatError_RuntimeField2 + 3); + check(screen.pointer_down(x + 31, y + 5), "Source co-trainer tile owns the press"); + const auto held = screen.state_json(); + check(screen.key("ESC").kind == EnvironmentRequestKind::none && !screen.close_requested() && + screen.state_json() == held, "back cannot steal a held staff control before its release"); + const auto request = screen.release(x + 31, y + 5); + check(request.kind == EnvironmentRequestKind::set_item && request.item == 3 && request.level == 3 && + request.manager_slot == state.manager_slot && request.runtime_club == state.runtime_club && + request.revision == 17 && request.owner == owner, + "tile release emits a typed, manager/revision-owned level request"); + const auto pending = screen.state_json(); + check(screen.key("ESC").kind == EnvironmentRequestKind::none && screen.pending() && + !screen.close_requested() && screen.state_json() == pending, + "back cannot discard an issued staff mutation before its ACK"); + + auto updated = state; + updated.revision = 18; + updated.values.level[3] = 3; + updated.values.monthly[3] = 15000; + updated.cost_text[3] = format_number(game, 15000, 0x185); + updated.owner.revision = 18; + screen.acknowledge(updated); + check(!screen.pending() && screen.state().revision == 18 && + screen.state().values.monthly[3] == 15000, + "valid source mutation ACK refreshes the screen and clears the pending action"); + + const auto notice = environment_notice_dialog(game, state.manager_slot, + "Unit academy notice"); + check(notice.kind == TaxDialogKind::acknowledgement && + notice.source_manager_flags == (uint8_t(state.manager_slot) | 0x40) && + notice.source_flags == 0 && notice.body == "Unit academy notice", + "academy rejection uses the exact Source timed-notice call shape and body"); + + // Independent legacy routine boundary expectations; selector zero is valid + // and a generic runtime club must not dereference the W table. + auto identity=game; + identity.club_heap_78.assign(4095*2,0); + const struct {int club;bool fallback;} cases[]{{0,false},{45,false},{89,false}, + {90,true},{137,true},{138,false},{167,false},{168,true},{356,true}, + {357,false},{4094,false},{4095,true},{0x1000+45,false}}; + for(const auto entry:cases) { + identity.manager_teams[size_t(state.manager_slot)]=entry.club; + auto projected=environment_notice_dialog(identity,state.manager_slot,"Hinweis"); + check(projected.badge_fallback==entry.fallback && projected.badge_sprite==0, + "Source runtime club gate preserves valid W sprite zero and fallback boundaries"); + if(entry.fallback) { + auto no_table=identity;no_table.club_heap_78.clear(); + check(environment_notice_dialog(no_table,state.manager_slot,"Hinweis").badge_fallback, + "Source generic badge does not depend on any W-table bytes"); + } + } + identity.manager_teams[size_t(state.manager_slot)]=45; + identity.club_heap_78.clear();bool truncated=false; + try {(void)environment_notice_dialog(identity,state.manager_slot,"Hinweis");} + catch(const FormatError&) {truncated=true;} + check(truncated,"missing real badge table is rejected without inventing a fallback"); + + check(screen.pointer_down(10, 10, true), "right-button close is owned by environment screen"); + (void)screen.release(10, 10, true); + check(screen.close_requested(), "matched right-button release closes the source menu"); + std::cout << "ui environment tests: ok\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "ui environment tests: " << error.what() << "\n"; + return 1; + } +} diff --git a/src/ui/finance_totals.cpp b/src/ui/finance_totals.cpp new file mode 100644 index 0000000..52e4b7a --- /dev/null +++ b/src/ui/finance_totals.cpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "finance_totals.hpp" + +#include +#include + +#include "ui/advertising.hpp" +#include "ui/manager.hpp" +#include "game/messages.hpp" + +namespace bmh::ui { +namespace { +constexpr size_t kManagerRecord = 0xb0c; + +uint32_t require_memory(const GameState& g, uint32_t address, size_t bytes) { + if (bytes == 0 || !g.memory.has(address) || !g.memory.has(address + uint32_t(bytes - 1))) + throw FormatError("statistics finance: save lacks Source asset memory"); + return address; +} +uint16_t read16(const std::vector& b, size_t at) { + if (at + 1 >= b.size()) throw FormatError("statistics finance: truncated stock block"); + return uint16_t(b[at]) | uint16_t(b[at + 1]) << 8; +} +uint32_t read32(const std::vector& b, size_t at) { + if (at + 3 >= b.size()) throw FormatError("statistics finance: truncated stock block"); + return uint32_t(b[at]) | uint32_t(b[at + 1]) << 8 | + uint32_t(b[at + 2]) << 16 | uint32_t(b[at + 3]) << 24; +} +int32_t original_mask_1e(const GameState& g, int manager) { + const size_t rec = size_t(manager) * kManagerRecord; + if (rec + 0x31b >= g.manager_records.size()) + throw FormatError("statistics finance: manager cash record is truncated"); + const uint32_t values = require_memory(g, ::bmh::layout::FundBlock, 6 * 0x1c); + const uint32_t quantities = require_memory(g, ::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField, + uint32_t(manager) * 2 + 5 * 0x1c + 2); + const uint32_t loans = require_memory(g, ::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField, + uint32_t(manager) * 0x78 + 4 * 0x18 + 4); + if (g.stocks.size() < 12 * 0x5c) + throw FormatError("statistics finance: stock table is truncated"); + + uint32_t total = read32(g.manager_records, rec + 0x318); // HighscoreScore bit 1, Source +b6f30. + for (uint32_t i = 0; i < 6; ++i) { + const uint32_t quantity = g.memory.u16(quantities + i * 0x1c + uint32_t(manager) * 2); + const uint32_t value = g.memory.u32(values + i * 0x1c); + total += quantity * value; // bit 2: u16 quantity times u32 unit value, wrapping u32. + } + for (uint32_t i = 0; i < 12; ++i) { + const size_t at = size_t(i) * 0x5c; + const uint32_t quantity = read16(g.stocks, at + 0x50 + size_t(manager) * 2); + const uint32_t price = read16(g.stocks, at + 0x4e); + total += quantity * price; // bit 3, Source stock value. + } + for (uint32_t i = 0; i < 5; ++i) + total -= g.memory.u32(loans + uint32_t(manager) * 0x78 + i * 0x18); // bit 4, debt subtracts. + return int32_t(total); +} +} + +FinanceTotals finance_totals_from_game(const GameState& g, int manager) { + if (manager < 0 || manager > 3 || size_t(manager + 1) * kManagerRecord > g.manager_records.size()) + throw FormatError("statistics finance: invalid manager record"); + if (!g.memory.has(::bmh::layout::ActiveManager) || g.memory.u8(::bmh::layout::ActiveManager) != manager) + throw FormatError("statistics finance: manager is not the active Original manager"); + const size_t rec = size_t(manager) * kManagerRecord; + FinanceTotals out; + out.manager_slot = manager; + const auto rd32 = [&](size_t offset) { + const size_t at = rec + offset; + if (at + 3 >= g.manager_records.size()) + throw FormatError("statistics finance: manager finance field is truncated"); + return int32_t(read32(g.manager_records, at)); + }; + // FinanceTotalsFromGame's source globals relative to manager record base *ManagerRecords. + out.rows[0] = rd32(0x314); // MonthRuntimeField9 + out.rows[1] = original_mask_1e(g, manager); + out.rows[2] = int32_t(uint32_t(out.rows[0]) - + (uint32_t(rd32(0x324)) + uint32_t(rd32(0x30c)))); // b6f3c + b6f24 + out.rows[3] = rd32(0x320); // b6f38 + out.rows[4] = 0; // Source group heading only. + out.rows[5] = rd32(0x338); // b6f50 + out.rows[6] = rd32(0x334); // b6f4c + out.rows[7] = rd32(0x33c); // b6f54 + + // Reuse the established read-only implementation of FinanceTotalsFromGame3/OriginalFinancePreview through + // its public advertising projection. It uses the same exact Original preview path. + const AdvertisingFinancePreview monthly = original_finance_preview(g, manager); + out.rows[8] = monthly.income; + out.rows[9] = monthly.expenses; + out.rows[10] = int32_t(uint32_t(out.rows[8]) - uint32_t(out.rows[9])); + for (size_t i = 0; i < out.rows.size(); ++i) + if (i != 4) out.amounts[i] = format_number(g, out.rows[i], 0x108); + return out; +} + +FinanceTotalsScreen::FinanceTotalsScreen(const std::filesystem::path& data, + FinanceTotals state, Image underlay) + : state_(std::move(state)), underlay_(std::move(underlay)), + texts_(load_textd(asset_path(data, "TEXTD.BLK"))), + font_(load_font(asset_path(data / "F", "BMH3.FNT"))) { + if (state_.manager_slot < 0 || state_.manager_slot > 3 || + underlay_.width != 320 || underlay_.height != 240) + throw FormatError("statistics finance: incomplete Source projection"); +} + +Image FinanceTotalsScreen::render() const { + Image out = underlay_; + for (size_t i = 0; i < state_.rows.size(); ++i) { + const std::string& label = texts_[27 + i]; // FinanceTotalsRuntimeField: TEXTD entries 27..37. + const int baseline = 79 + int(i) * 8; // FinanceTotalsFromGame, 0x4f + 8 per row. + const int label_x = (i >= 4 && i <= 6) ? 80 : 70; + font_.draw(out, label_x, baseline - font_.baseline, label, 0x6b); // Source literal, not EXE color. + if (i != 4) font_.draw(out, 190, baseline - font_.baseline, state_.amounts[i], 0x6b); + } + return out; +} + +} // namespace bmh::ui diff --git a/src/ui/finance_totals.hpp b/src/ui/finance_totals.hpp new file mode 100644 index 0000000..e9beeea --- /dev/null +++ b/src/ui/finance_totals.hpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "formats/textd.hpp" +#include "formats/vga.hpp" +#include "game/state.hpp" + +namespace bmh::ui { + +// FinanceTotalsFromGame rows 0..10. Row 4 is the source's group separator and has no value. +struct FinanceTotals { + int manager_slot = -1; + std::array rows{}; + std::array amounts{}; // FormatNumber Source formatting with the game's currency settings. +}; + +// Read-only projection for the Original page. Monthly values reuse the public wrapper for +// advertising.cpp's exact FinanceTotalsFromGame3(0)/OriginalFinancePreview(0) implementation. +FinanceTotals finance_totals_from_game(const GameState&, int manager_slot); + +class FinanceTotalsScreen { +public: + FinanceTotalsScreen(const std::filesystem::path& data, FinanceTotals, Image underlay); + Image render() const; +private: + FinanceTotals state_; + Image underlay_; + TextDb texts_; + Font font_; +}; + +} // namespace bmh::ui diff --git a/src/ui/finance_totals_tests.cpp b/src/ui/finance_totals_tests.cpp new file mode 100644 index 0000000..479410f --- /dev/null +++ b/src/ui/finance_totals_tests.cpp @@ -0,0 +1,50 @@ +#include "../../tests/runtime_fixture_tables.hpp" +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "finance_totals.hpp" +#include +#include +#include +#include +#include "formats/fbm.hpp" +#include "formats/savestate.hpp" +#include "game/messages.hpp" +#include "game/save.hpp" +#include "ui/advertising.hpp" +#include "ui/setup.hpp" + +namespace { +void check(bool b,const char* what){if(!b)throw std::runtime_error(what);} +uint32_t u32(const std::vector& b,size_t at){return uint32_t(b.at(at))|uint32_t(b.at(at+1))<<8|uint32_t(b.at(at+2))<<16|uint32_t(b.at(at+3))<<24;} +uint16_t u16(const std::vector& b,size_t at){return uint16_t(b.at(at))|uint16_t(b.at(at+1))<<8;} +int32_t si32(const std::vector& b,size_t at){return int32_t(u32(b,at));} +} +int main(int argc,char**argv){try{ + if(argc!=3)throw std::runtime_error("usage: finance_totals_w196_test DATA_DIR WEEK196.FBM"); + const std::filesystem::path data=argv[1];const auto exe=bmh::test::load_executable(bmh::ui::asset_path(data,"BMH.exe")); + const auto raw=bmh::load_savegame(argv[2]);check(raw.checksum_ok&&raw.version=="V2.24","W196 save checksum/version"); + const bmh::DbCounts counts{exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField),exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3),exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2),exe.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)}; + const bmh::SaveState save(raw.stream,counts);auto game=bmh::GameState::from_save(save,counts); + const auto texts=bmh::load_textd(bmh::ui::asset_path(data,"TEXTD.BLK"));game.texts=&texts;game.currency_suffix=exe.cstring(::bmh::layout::CurrencySuffixText); + const int m=game.memory.u8(::bmh::layout::ActiveManager);check(m>=0&&m<4,"W196 active manager");const size_t rec=size_t(m)*0xb0c; + const auto before=bmh::save_stream(game);const auto totals=bmh::ui::finance_totals_from_game(game,m); + check(totals.manager_slot==m,"manager ownership"); + check(totals.rows[0]==si32(game.manager_records,rec+0x314),"Source row 0 b6f2c"); + check(totals.rows[2]==int32_t(uint32_t(totals.rows[0])-(u32(game.manager_records,rec+0x324)+u32(game.manager_records,rec+0x30c))),"Source row 2 b6f3c/b6f24"); + check(totals.rows[3]==si32(game.manager_records,rec+0x320),"Source row 3 b6f38"); + check(totals.rows[5]==si32(game.manager_records,rec+0x338),"Source row 5 b6f50"); + check(totals.rows[6]==si32(game.manager_records,rec+0x334),"Source row 6 b6f4c"); + check(totals.rows[7]==si32(game.manager_records,rec+0x33c),"Source row 7 b6f54"); + uint32_t expected=u32(game.manager_records,rec+0x318); + for(uint32_t i=0;i<6;++i)expected+=uint32_t(game.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField+i*0x1c+uint32_t(m)*2))*game.memory.u32(::bmh::layout::FundBlock+i*0x1c); + for(uint32_t i=0;i<12;++i){size_t at=size_t(i)*0x5c;expected+=uint32_t(u16(game.stocks,at+0x50+size_t(m)*2))*u16(game.stocks,at+0x4e);} + for(uint32_t i=0;i<5;++i)expected-=game.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField+uint32_t(m)*0x78+i*0x18); + check(totals.rows[1]==int32_t(expected),"legacy routine mask 1e fixed assets, stocks and loan subtraction"); + const auto monthly=bmh::ui::original_finance_preview(game,m); + check(totals.rows[8]==monthly.income&&totals.rows[9]==monthly.expenses,"Original monthly preview rows"); + check(totals.rows[10]==int32_t(uint32_t(monthly.income)-uint32_t(monthly.expenses)),"Original monthly balance row"); + for(size_t i=0;i +#include +#include + +namespace bmh::ui { +FlowResult StartupFlow::move_action(int x, int y) { + if (indoor_standings_ || indoor_standings_release_barrier_) return {}; + if(world_cup_statistics_)return {world_cup_statistics_->move(x,y)}; + if(achievements_)return {achievements_->move(x,y)}; + if(family_table_dispatch_pending_)return {}; + if(family_table_range_dialog_) { + const bool changed=family_table_range_dialog_->move(x,y); + return {changed}; + } + if(other_games_)return {other_games_->move(x,y)}; + if(balance_)return {balance_->move(x,y)}; + if(top_scorers_)return {top_scorers_->move(x,y)}; + if(analytics_)return {}; + if(statistics_rankings_)return {statistics_rankings_->move(x,y)}; + if(transfer_history_)return {}; + if(opportunities_)return {opportunities_->move(x,y)}; + if(statistics_menu_)return {}; + if(strengths_)return {strengths_->move(x,y)}; + if(in_family_table())return {league_table_->move(x,y)}; + if (calendar_) return {calendar_->move(x,y)}; + if (friendly_match_) return {friendly_match_->move(x,y)}; + if(league_pairings_)return {league_pairings_->move(x,y)}; + if(stadium_)return {stadium_->pointer_move(x,y)}; + if(environment_)return {}; + if (outgoing_transfer_) return {}; + if (transfer_market_ && !player_card_) { + const auto before = transfer_market_->state_json(); + const auto request = transfer_market_->move(x, y); + if (request.kind != TransferMarketRequestKind::none) + return finish_preparation_input(request, true); + return {before != transfer_market_->state_json()}; + } + if (desktop_ && screen_name() == "desktop") return {desktop_->pointer_move(x,y)}; + const bool changed = joining_ + ? manager_ && !join_options_pending_ && !join_choice_pending_ && manager_->move(x, y) + : contracts_ && !player_card_ ? contracts_->move(x, y) + : matchday_results_ || in_readonly_view() || friendly_match_ ? false + : player_card_ ? false : pitch_ ? pitch_->move(x, y) + : lineup_ ? lineup_->move(x, y) : training_camp_ ? training_camp_->move(x, y) + : toto_ ? toto_->move(x, y) + : bank_ || stadium_ ? false + : !desktop_ && manager_ && !pending_ && !awaiting_context_ && manager_->move(x, y); + return {changed}; +} + + +namespace { +void validate_confirmed_manager_projection(const std::vector& choices, + const std::vector& managers, + const DeskState& desk) { + validate_desk_state(desk); + if (choices.size() != size_t(desk.options.managers) || managers.size() != choices.size()) + throw FormatError("career attachment: manager count does not match confirmed setup"); + std::vector by_slot(choices.size(), nullptr); + std::set chosen_master_clubs, chosen_portraits; + for (const auto& choice : choices) { + if (!chosen_master_clubs.insert(choice.master_club).second || + !chosen_portraits.insert(choice.portrait).second) + throw FormatError("career attachment: confirmed choices contain duplicate club/portrait"); + } + for (const auto& manager : managers) { + if (manager.slot < 0 || size_t(manager.slot) >= by_slot.size() || by_slot[size_t(manager.slot)]) + throw FormatError("career attachment: sparse or duplicate manager slot"); + by_slot[size_t(manager.slot)] = &manager; + } + for (size_t slot = 0; slot < choices.size(); ++slot) { + const auto& choice = choices[slot]; + const auto* manager = by_slot[slot]; + const auto& identity = desk.managers[slot]; + if (!manager || choice.slot != int(slot) || manager->master_club != choice.master_club || + manager->runtime_club != desk.manager_teams[slot] || identity.name != choice.name || + identity.portrait != choice.portrait || identity.league != choice.start_league) + throw FormatError("career attachment: manager identity does not match confirmed slot mapping"); + } + const auto& active = choices[size_t(desk.manager_slot)]; + if (desk.manager_name != active.name || desk.portrait != active.portrait || + desk.league != active.start_league) + throw FormatError("career attachment: active manager identity does not match confirmed choice"); +} +void validate_confirmed_desk(const std::vector& choices, + const std::vector& runtime_teams, + const std::vector& previous, + bool previous_national_coach_takeover, + const std::vector& previous_national_roster, + bool allow_turn_handoff, const DeskState& desk) { + validate_desk_state(desk); + const bool previous_national = previous.size() == 1 && previous[0].runtime_club == kNoTeam && + (desk.options.world || previous_national_coach_takeover); + const bool incoming_national = desk.national_team && + (desk.options.world || desk.national_coach_takeover); + const bool national_transition = allow_turn_handoff && (previous_national || incoming_national); + if (!allow_turn_handoff && previous_national_coach_takeover && + previous_national_roster.size() != desk.national_return_roster.size()) + throw FormatError("desk acknowledgement: national return roster changed unexpectedly"); + if (!allow_turn_handoff && previous_national_coach_takeover && + !std::equal(previous_national_roster.begin(), previous_national_roster.end(), + desk.national_return_roster.begin(), [](const auto& before, const auto& after) { + return before.club_identity_key == after.club_identity_key && before.name == after.name && + before.portrait == after.portrait; + })) + throw FormatError("desk acknowledgement: national return roster changed unexpectedly"); + if (national_transition && incoming_national) { + if (desk.managers.size() != 1) + throw FormatError("desk acknowledgement: invalid temporary national roster size"); + const auto& active = desk.managers[0]; + const auto& baseline = previous_national && !previous_national_roster.empty() + ? previous_national_roster : previous; + if ((desk.national_coach_takeover && desk.national_return_roster.size() != baseline.size()) || + (!desk.national_return_roster.empty() && + !std::equal(baseline.begin(), baseline.end(), desk.national_return_roster.begin(), + [](const auto& before, const auto& after) { + return before.club_identity_key == after.club_identity_key && before.name == after.name && + before.portrait == after.portrait; + })) || std::none_of(baseline.begin(), baseline.end(), [&](const auto& manager) { + return manager.club_identity_key == active.club_identity_key && manager.name == active.name && + manager.portrait == active.portrait; + })) + throw FormatError("desk acknowledgement: national coach is not from the confirmed roster"); + } else if (national_transition && previous_national) { + const auto& baseline = previous_national_roster.empty() ? previous : previous_national_roster; + if (desk.managers.size() != baseline.size() || + !std::equal(desk.managers.begin(), desk.managers.end(), baseline.begin(), [](const auto& after, const auto& before) { + return before.club_identity_key == after.club_identity_key && before.name == after.name && + before.portrait == after.portrait; + })) + throw FormatError("desk acknowledgement: handback does not restore the confirmed manager roster"); + } else if (previous.size() != desk.managers.size()) { + throw FormatError("desk acknowledgement: manager identity baseline changed"); + } + if (!national_transition || (!incoming_national && !previous_national)) { + for (size_t slot=0; slot= size_t(desk.options.managers)) + throw FormatError("desk acknowledgement: manager roster/mapping changed unexpectedly"); + if (desk.national_team) { + if (std::none_of(choices.begin(), choices.end(), [&](const ManagerChoice& choice) { + return desk.manager_name == choice.name && desk.portrait == choice.portrait; + })) + throw FormatError("desk acknowledgement: temporary national coach is not a confirmed manager"); + } else { + const auto& active = choices[size_t(desk.manager_slot)]; + if (desk.manager_name != active.name || desk.portrait != active.portrait) + throw FormatError("desk acknowledgement: active slot does not match its confirmed manager"); + } +} +} + +void StartupFlow::show_manager_join(std::vector existing, SelectionContext context) { + if (!desktop_ || !engine_attached_ || joining_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || + !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || + desktop_->pending()->menu_kind != 29 || desktop_->state().national_team || + existing.size() != desktop_->state().managers.size() || context.revision != desktop_->state().revision) + throw FormatError("join: expected the running career's new-manager request"); + for (size_t slot=0; slotstate().managers[slot]; + if (choice.slot != int(slot) || choice.name != identity.name || choice.portrait != identity.portrait || + choice.start_league != identity.league || choice.selection_club != identity.runtime_club || + choice.selection_club < 0 || size_t(choice.selection_club) >= context.club_order.size() || + context.club_order[size_t(choice.selection_club)] != choice.master_club) + throw FormatError("join: existing identity does not match the engine roster"); + } + auto setup=std::make_unique(data_, desktop_->state().options); + join_origin_=*desktop_->pending(); join_choices_=std::move(existing); + join_context_revision_=context.revision; join_setup_=std::move(setup); + manager_.reset(); joining_=true; join_options_pending_=join_choice_pending_=false; +} + +void StartupFlow::resume_manager_join(SelectionContext context) { + if (!joining_ || (!join_options_pending_ && !join_choice_pending_) || + context.revision < join_context_revision_ || + (join_choice_pending_ && context.revision == join_context_revision_) || + join_choices_.size() >= size_t(join_setup_->options().managers)) + throw FormatError("join: stale or incomplete manager-selection context"); + auto next=std::make_unique(data_,int(join_choices_.size()),join_choices_,context); + manager_=std::move(next); join_context_revision_=context.revision; + join_options_pending_=join_choice_pending_=false; +} + +void StartupFlow::acknowledge_manager_join(CareerInitializationResult result) { + if (!joining_ || (!join_options_pending_ && !join_choice_pending_) || !desktop_ || + !desktop_->pending() || *desktop_->pending() != join_origin_ || + result.desktop.source != "engine_projection" || result.desktop.revision != join_origin_.revision+1 || + result.desktop.options != join_setup_->options() || + result.desktop.manager_slot != desktop_->state().manager_slot || + result.desktop.day_counter != desktop_->state().day_counter || + desk_json(result.desktop) != desk_json(result.preparation.desktop)) + throw FormatError("join: acknowledgement does not match the pending selection"); + validate_confirmed_manager_projection(join_choices_,result.managers,result.desktop); + for (size_t slot=0; slotstate().managers.size(); ++slot) { + const auto& before=desktop_->state().managers[slot]; const auto& after=result.desktop.managers[slot]; + if (before.club_identity_key != after.club_identity_key || before.name != after.name || before.portrait != after.portrait) + throw FormatError("join: existing manager identity changed"); + } + // All renderers must accept the new projection before exposing it to the player. + StartupFlow candidate(data_,save_directory_); + candidate.desktop_=std::make_unique(data_,result.desktop); + candidate.engine_attached_=true; candidate.attach_preparation_context(std::move(result.preparation)); + auto next_choices=join_choices_; + auto next_teams=result.desktop.manager_teams; + desktop_=std::move(candidate.desktop_); preparation_=std::move(candidate.preparation_); + confirmed_=std::move(next_choices); confirmed_runtime_teams_=std::move(next_teams); + manager_.reset(); join_setup_.reset(); join_choices_.clear(); + joining_=join_options_pending_=join_choice_pending_=false; +} + +void StartupFlow::reject_manager_join(std::string reason) { + if (!joining_) return; + if (reason.empty()) desktop_->resolve_local_menu(); + else desktop_->reject_action(std::move(reason)); + manager_.reset(); join_setup_.reset(); join_choices_.clear(); + joining_=join_options_pending_=join_choice_pending_=false; +} + +std::optional StartupFlow::pitch_formation_save_feedback(bool restored)const{ + return pitch_?pitch_->formation_save_feedback(restored):std::nullopt; +} + +FlowResult StartupFlow::pitch_held_left(int x,int y,uint64_t source_ticks){ + if(!pointer_source_hold_ready(source_ticks)||!pitch_||player_card_|| + pitch_release_barrier_||pitch_hold_release_barrier_|| + x<240||x>=320||y<112||y>=208)return {}; + const auto before=pitch_->state_json();const auto request=pitch_->save_formation(x,y); + PreparationRequest action; + if(request.kind!=PitchRequestKind::none){ + action=request; + // PitchScreen redraws through SDLFlushEvents after saving: the old held input + // cannot write another template, including on its eventual release. + pitch_hold_release_barrier_=true; + } + return finish_preparation_input(std::move(action),before!=pitch_->state_json()); +} + +FlowResult StartupFlow::hold(int x,int y,int milliseconds){ + if(milliseconds<0||milliseconds>60000)throw FormatError("hold duration must be 0..60000 ms"); + if(pitch_hold_release_barrier_){pitch_hold_release_barrier_=false;return {};} + if(pitch_release_barrier_){pitch_release_barrier_=false;return {};} + if(balance_release_barrier_){balance_release_barrier_=false;return {};} + if(other_games_)return finish_other_games_input(other_games_->release(x,y)); + if(balance_)return finish_balance_input(balance_->release(x,y)); + if(top_scorers_)return finish_top_scorers_input(top_scorers_->release(x,y)); + if(opportunities_)return finish_opportunities_input(opportunities_->release(x,y)); + if(strengths_)return finish_strengths_input(strengths_->release(x,y)); + if(milliseconds<2000||!pitch_||player_card_||x<240||x>=320||y<112||y>=208)return click(x,y); + const auto before=state_json();const auto request=pitch_->save_formation(x,y); + PreparationRequest action; + if(request.kind!=PitchRequestKind::none)action=request; + return finish_preparation_input(std::move(action),before!=state_json()); +} + +FlowResult StartupFlow::click(int x, int y, bool right, bool double_click) { + if(pitch_hold_release_barrier_&&!right){pitch_hold_release_barrier_=false;return {};} + if(friendly_question_release_barrier_&&!right) { + friendly_question_release_barrier_=false;return {}; + } + if (indoor_standings_release_barrier_) { + indoor_standings_release_barrier_ = false; + return {}; + } + if (indoor_standings_) return {}; + if(desk_records_release_barrier_){desk_records_release_barrier_=false;return {};} + if(desk_records_)return {desk_records_->pointer_up(x,y,right)}; + if(family_table_dispatch_pending_)return {}; + if (reschedule_release_barrier_) { reschedule_release_barrier_ = false; return {}; } + if(achievements_release_barrier_){achievements_release_barrier_=false;return {};} + if(achievements_)return {}; + if (settings_readme_release_barrier_) { + settings_readme_release_barrier_ = false; + return {}; + } + if (settings_readme_) return {}; // Mouse UP is consumed by the viewer's wait. + if (settings_release_barrier_) { + settings_release_barrier_ = false; + if (settings_) settings_->consume_release(); + return {}; + } + if(national_friendly_release_barrier_){national_friendly_release_barrier_=false;return {};} + if(pitch_release_barrier_){pitch_release_barrier_=false;return {};} + if(family_table_range_dialog_) { + const bool changed=family_table_range_dialog_->pointer_up(x,y,right); + // A consumed release ends drag ownership; it does not start a new + // DecodeTaxAnimationScript2 wait or restart one already anchored at its pressed frame. + return {changed}; + } + if(family_table_release_barrier_){family_table_release_barrier_=false;return {};} + if(balance_release_barrier_){balance_release_barrier_=false;return {};} + if(other_games_)return right?FlowResult{}:finish_other_games_input(other_games_->release(x,y)); + if(world_cup_statistics_&&national_friendly_picker_) + return statistics_menu_&&!right ? finish_statistics_menu_input(statistics_menu_->release(x,y)) : FlowResult{}; + if(alltime_table_) { + const bool changed=alltime_table_->release(x,y); + if(const auto& request=alltime_table_->pending();request) { + statistics_page_action_=StatisticsPageAction{request->owner,3, + request->kind==AllTimeRequestKind::close?StatisticsPageActionKind::close:StatisticsPageActionKind::alltime, + request->nation,request->relative}; + return finish_statistics_page_input(true); + } + if(changed)return {true}; + return statistics_menu_ && !right ? finish_statistics_menu_input(statistics_menu_->release(x,y)) : FlowResult{}; + } + if(world_cup_statistics_||finance_totals_||series_records_) + return statistics_menu_ && !right ? finish_statistics_menu_input(statistics_menu_->release(x,y)) : FlowResult{}; + if(balance_)return right?FlowResult{}:finish_balance_input(balance_->release(x,y)); + if(top_scorers_)return right?FlowResult{}:finish_top_scorers_input(top_scorers_->release(x,y)); + if(analytics_) { + if(analytics_->pending())return {}; + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + return {}; + } + if(statistics_rankings_) { + if(statistics_rankings_->release(x,y))return finish_statistics_rankings_input(true); + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + return {}; + } + if(minute_statistics_) { + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + return {}; + } + if(transfer_history_) { + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + return {}; + } + if(opportunities_) { + if(opportunities_->release(x,y))return finish_opportunities_input(true); + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + return {}; + } + if(statistics_menu_)return right?FlowResult{}:finish_statistics_menu_input(statistics_menu_->release(x,y)); + if(strengths_)return right?FlowResult{}:finish_strengths_input(strengths_->release(x,y)); + if (stadium_) { + const auto request = stadium_->release(x,y,right); + PreparationRequest action; + if (request.kind != StadiumRequestKind::none) action = request; + // A release also restores the pressed button or changes the local view. + return finish_preparation_input(std::move(action), true); + } + if (environment_) { + (void)environment_->click(x,y,right); + if (environment_->close_requested()) { environment_.reset(); return {true,FlowRequest::submenu_closed}; } + if (environment_->pending()) { + FlowResult result{true,FlowRequest::environment_action}; + result.environment_action=*environment_->pending(); return result; + } + return {}; + } + // Familyclose is Source event8 on DOWN; an orphan UP has no action. + if(league_pairings_)return right?FlowResult{}:finish_league_pairings_input(league_pairings_->release(x,y)); + if (joining_) { + if (join_options_pending_ || join_choice_pending_) return {}; + if (!manager_) { + auto input = join_setup_->click(x,y,right); + if (input.request == SetupRequest::new_game) { + join_options_pending_ = true; + FlowResult result{true,FlowRequest::join_options}; + result.desk_action = join_origin_; result.join_options = join_setup_->options(); + return result; + } + return {input.changed}; + } + const bool changed = manager_->click(x,y,right); + if (manager_->view() != ManagerView::accepted) return {changed}; + join_choices_.push_back(manager_->choice()); join_choice_pending_ = true; + FlowResult result{true,FlowRequest::join_manager}; + result.desk_action = join_origin_; result.join_manager = join_choices_.back(); + return result; + } + if (contracts_ && !player_card_) { + const bool changed = contracts_->click(x, y, right); + if (contracts_->close_requested()) { contracts_.reset(); return {true, FlowRequest::contracts_closed}; } + if (contracts_->pending()) { + FlowResult result{true, FlowRequest::contract_action}; + result.contract_action = *contracts_->pending(); + return result; + } + const int info_row=contracts_->take_player_info_request(); + if(info_row>=0 && preparation_) for(auto card:preparation_->player_cards) { + if(card.row==info_row && card.unsupported_record.empty()) { + player_card_=std::make_unique(data_,std::move(card),contracts_->render()); + return {true,FlowRequest::submenu_opened}; + } + } + return {changed}; + } + if (friendly_match_) { + const auto before = state_json(); + auto request = friendly_match_->click(x, y, right); + if (friendly_match_->close_requested()) { + friendly_match_.reset(); pending_friendly_action_.reset(); + return {true, FlowRequest::submenu_closed}; + } + if (request) { + pending_friendly_action_ = *request; + next_friendly_request_id_ = std::max(next_friendly_request_id_, request->request_id + 1); + FlowResult result{true, FlowRequest::friendly_action}; + result.friendly_action = *request; + return result; + } + return {before != state_json()}; + } + if (calendar_) { + const bool changed = calendar_->click(x,y,right); + if (calendar_->pending_reschedule()) { + FlowResult result{true, FlowRequest::reschedule_action}; + result.reschedule_action = *calendar_->pending_reschedule(); + return result; + } + return finish_readonly_input(changed); + } + if (league_table_) { + const bool changed = right ? league_table_->key("ESC") : league_table_->click(x, y); + if(const auto* family=pending_league_family_action()) { + FlowResult result{changed,FlowRequest::league_family_action}; + result.league_family_action=*family;return result; + } + return finish_readonly_input(changed); + } + if (mailbox_) return finish_readonly_input(mailbox_->click(x, y, right)); + if (settings_ && !save_load_) return finish_settings_input(settings_->click(x, y, right)); + if (advertising_) return finish_readonly_input(right ? advertising_->key("ESC") : advertising_->click(x, y)); + if (matchday_results_) { + const bool changed = matchday_results_->click(x, y); + if (matchday_results_->close_requested()) { + matchday_results_.reset(); + return {true, FlowRequest::results_closed}; + } + return {changed}; + } + if (save_load_) { + const auto before = state_json(); + const bool changed = save_load_->click(x, y, right); + return finish_file_input(changed || before != state_json()); + } + if (in_preparation_menu()) { + const auto before = state_json(); + const bool statistics_before = player_card_ && player_card_->in_statistics(); + PreparationRequest action; + if (player_card_) player_card_->click(x, y, right); + else if (pitch_) { auto r = pitch_->click(x, y, right); if (r.kind != PitchRequestKind::none) action = r; } + else if (lineup_) { auto r = lineup_->click(x, y, right); if (r.kind != LineupRequestKind::none) action = r; } + else if (training_) { auto r = training_->click(x, y, right); if (r.kind != TrainingRequestKind::none) action = r; } + else if (training_camp_) { auto r = training_camp_->click(x, y, right); if (r.kind != TrainingCampRequestKind::none) action = r; } + else if (bank_) { auto r = bank_->click(x, y, right); if (r.kind != BankRequestKind::none) action = r; } + else if (stadium_) { auto r = stadium_->click(x, y, right); if (r.kind != StadiumRequestKind::none) action = r; } + else if (environment_) { auto r=environment_->click(x,y,right); if(environment_->close_requested()) { environment_.reset(); return {true,FlowRequest::submenu_closed}; } if(r.kind!=EnvironmentRequestKind::none) { FlowResult result{true,FlowRequest::environment_action}; result.environment_action=r; return result; } } + else if (toto_) { auto r = toto_->click(x, y, right); if (r.kind != TotoRequestKind::none) action = r; } + else if (outgoing_transfer_) { auto r = outgoing_transfer_->click(x, y, right, double_click); if (r.kind != OutgoingTransferRequestKind::none) action = r; } + else if (transfer_market_) { auto r = transfer_market_->click(x, y, right); if (r.kind != TransferMarketRequestKind::none) action = r; } + else if (tactics_) { auto r = tactics_->click(x, y, right); if (r.kind != TacticsRequestKind::none) action = r; } + auto result = finish_preparation_input(std::move(action), before != state_json()); + if (player_card_ && statistics_before != player_card_->in_statistics()) + result.request = player_card_->in_statistics() ? FlowRequest::submenu_opened : FlowRequest::submenu_closed; + return result; + } + if (desktop_) { + const auto before = desktop_->state_json(); + auto result = route_desk(desktop_->pointer_up(x, y, right)); + result.changed |= before != desktop_->state_json(); + return result; + } + if (pending_ || awaiting_context_) return {}; // One request, then wait for an engine adapter. + if (!manager_) { + auto r = setup_.click(x, y, right); + if (r.request == SetupRequest::load_game) { + save_load_ = std::make_unique(data_, save_directory_, SaveLoadMode::load, -1, 0, setup_.render()); + return {true, FlowRequest::submenu_opened}; + } + if (r.request == SetupRequest::new_game) { + manager_ = std::make_unique(data_, 0); + return {true, FlowRequest::none}; + } + return {r.changed, FlowRequest::none}; + } + bool changed = manager_->click(x, y, right); + if (manager_->view() != ManagerView::accepted) return {changed, FlowRequest::none}; + confirmed_.push_back(manager_->choice()); + if (int(confirmed_.size()) == setup_.options().managers) { + pending_ = std::make_unique(NewCareerRequest{setup_.options(), confirmed_}); + return {true, FlowRequest::new_career}; + } + awaiting_context_ = true; + return {true, FlowRequest::manager_confirmed}; +} + +FlowResult StartupFlow::send_key(std::string_view value) { + if (indoor_standings_ || indoor_standings_release_barrier_) return {}; + if(achievements_)return {}; // AchievementsFromGame waits for its Source mouse event. + if (settings_readme_) return {}; // SDLFlushEvents2 waits for mouse input, not ESC. + if(desk_records_)return {desk_records_->key_input(value)}; + if(family_table_dispatch_pending_)return {}; + if(family_table_range_dialog_) { + if(!family_table_range_dialog_->source_input_ready())return {}; + const bool changed=family_table_range_dialog_->key(value); + if(changed)family_table_reset_clock_after_present_=true; + return {changed}; + } + if(balance_)return finish_balance_input(balance_->key(value)); + if(other_games_)return {}; // CupGroupOverviewEffects has no keyboard control mapping. + if(top_scorers_)return {}; // Copy3 has no keyboard control mapping. + if(opportunities_)return finish_opportunities_input(opportunities_->key(value)); + if(statistics_menu_)return {}; + if(strengths_)return {}; // Original has no keyboard control mapping. + if (calendar_) return finish_readonly_input(calendar_->key(value)); + if(league_pairings_)return {}; // No invented ESC or keyboard arrows. + if (joining_) { + if (manager_ && manager_->view() == ManagerView::name_edit) return {manager_->key(value)}; + if (value == "ESC") { + FlowResult result{true,FlowRequest::join_cancel}; result.desk_action = join_origin_; return result; + } + return {manager_ && !join_options_pending_ && !join_choice_pending_ && manager_->key(value)}; + } + if (contracts_ && !player_card_) { + const bool changed = contracts_->key(value); + if (contracts_->close_requested()) { contracts_.reset(); return {true, FlowRequest::contracts_closed}; } + if (contracts_->pending()) { + FlowResult result{true, FlowRequest::contract_action}; + result.contract_action = *contracts_->pending(); + return result; + } + return {changed}; + } + if (friendly_match_) { + const auto before = state_json(); + auto request = friendly_match_->key(value); + if (friendly_match_->close_requested()) { + friendly_match_.reset(); pending_friendly_action_.reset(); + return {true, FlowRequest::submenu_closed}; + } + if (request) { + pending_friendly_action_ = *request; + next_friendly_request_id_ = std::max(next_friendly_request_id_, request->request_id + 1); + FlowResult result{true, FlowRequest::friendly_action}; + result.friendly_action = *request; + return result; + } + return {before != state_json()}; + } + if (league_table_) return finish_readonly_input(league_table_->key(value)); + if (mailbox_) return finish_readonly_input(mailbox_->key(value)); + if (settings_ && !save_load_) return finish_settings_input(settings_->key(value)); + if (advertising_) return finish_readonly_input(advertising_->key(value)); + if (environment_) { environment_->key(value); if(environment_->close_requested()) { environment_.reset(); return {true,FlowRequest::submenu_closed}; } return {}; } + if (matchday_results_) { + const bool changed = matchday_results_->key(value); + if (matchday_results_->close_requested()) { + matchday_results_.reset(); + return {true, FlowRequest::results_closed}; + } + return {changed}; + } + if (save_load_) { + const auto before = state_json(); + const bool changed = save_load_->key(value); + return finish_file_input(changed || before != state_json()); + } + if (in_preparation_menu()) { + const auto before = state_json(); + const bool statistics_before = player_card_ && player_card_->in_statistics(); + PreparationRequest action; + if (player_card_) player_card_->key(value); + else if (pitch_) { auto r = pitch_->key(value); if (r.kind != PitchRequestKind::none) action = r; } + else if (lineup_) { auto r = lineup_->key(value); if (r.kind != LineupRequestKind::none) action = r; } + else if (training_) { auto r = training_->key(value); if (r.kind != TrainingRequestKind::none) action = r; } + else if (training_camp_) { auto r = training_camp_->key(value); if (r.kind != TrainingCampRequestKind::none) action = r; } + else if (bank_) { auto r = bank_->key(value); if (r.kind != BankRequestKind::none) action = r; } + else if (stadium_) { auto r = stadium_->key(value); if (r.kind != StadiumRequestKind::none) action = r; } + else if (toto_) { auto r = toto_->key(value); if (r.kind != TotoRequestKind::none) action = r; } + else if (outgoing_transfer_) { auto r = outgoing_transfer_->key(value); if (r.kind != OutgoingTransferRequestKind::none) action = r; } + else if (transfer_market_) { auto r = transfer_market_->key(value); if (r.kind != TransferMarketRequestKind::none) action = r; } + else if (tactics_) { auto r = tactics_->key(value); if (r.kind != TacticsRequestKind::none) action = r; } + auto result = finish_preparation_input(std::move(action), before != state_json()); + if (player_card_ && statistics_before != player_card_->in_statistics()) + result.request = player_card_->in_statistics() ? FlowRequest::submenu_opened : FlowRequest::submenu_closed; + return result; + } + if (desktop_) { + return route_desk(desktop_->key(value)); + } + return {manager_ && !pending_ && !awaiting_context_ && manager_->key(value)}; +} + +bool StartupFlow::text(std::string_view value) { + if(desk_records_)return desk_records_->text_input(value); + if(family_table_dispatch_pending_)return false; + if(family_table_range_dialog_) { + if(!family_table_range_dialog_->source_input_ready())return false; + const bool changed=family_table_range_dialog_->text(value); + if(changed)family_table_reset_clock_after_present_=true; + return changed; + } + if(balance_)return balance_->text(value); + if (joining_) return manager_ && !join_options_pending_ && !join_choice_pending_ && manager_->text(value); + if (contracts_ && !player_card_) return contracts_->text(value); + if (advertising_) return advertising_->text(value); + // A retained Settings parent must not block its active file dialog. + if (save_load_) return save_load_->text(value); + if (matchday_results_ || in_readonly_view() || friendly_match_) return false; + return bank_ ? bank_->text(value) : toto_ ? toto_->text(value) : outgoing_transfer_ ? outgoing_transfer_->text(value) : transfer_market_ ? transfer_market_->text(value) : + stadium_ ? stadium_->text(value) : !desktop_ && manager_ && !pending_ && !awaiting_context_ && manager_->text(value); +} + +FlowResult StartupFlow::finish_file_input(bool changed) { + if (save_load_->close_requested()) { + const bool settings_file = save_load_->file_kind() == SaveLoadFileKind::settings; + save_load_.reset(); + if (settings_file && settings_) settings_->cancel_file_request(); + return {true, FlowRequest::submenu_closed}; + } + if (save_load_->pending()) { + FlowResult result{true, save_load_->pending()->file_kind == SaveLoadFileKind::settings ? + FlowRequest::settings_file_action : FlowRequest::file_action}; + result.file_action = *save_load_->pending(); + result.settings_owner_sequence = settings_owner_sequence_; + return result; + } + return {changed}; +} + +FlowResult StartupFlow::finish_settings_input(bool changed) { + if (!settings_) return {changed}; + if (settings_->readme_requested()) { + settings_->consume_readme_request(); + settings_readme_ = std::make_unique(data_, settings_->state().decorated_background); + return {true}; + } + if (settings_->close_requested()) { + FlowResult result{true, FlowRequest::settings_close}; + result.settings_owner_sequence = settings_owner_sequence_; + return result; + } + if (settings_->pending_file()) { + if (!save_load_) { + const auto request = *settings_->pending_file(); + save_load_ = std::make_unique(data_, save_directory_, + request.action == SaveLoadAction::load ? SaveLoadMode::load : SaveLoadMode::save, + request.manager_slot, request.revision, settings_->render(), true, + SaveLoadFileKind::settings, request.origin_item_id); + return {true, FlowRequest::submenu_opened}; + } + } + if (settings_->pending()) { + FlowResult result{true, FlowRequest::settings_action}; + result.settings_action = *settings_->pending(); + result.settings_owner_sequence = settings_owner_sequence_; + return result; + } + return {changed}; +} + +void StartupFlow::load_reference(const std::filesystem::path& save, std::optional indoor) { + if (manager_ || desktop_) throw FormatError("reference load requires a fresh startup flow"); + auto state = std::make_unique(load_preparation_reference(save, load_le(asset_path(data_, "BMH.exe")))); + if (state->pitch && indoor) state->pitch->indoor = indoor; + auto desktop = std::make_unique(data_, state->desktop); + desktop_ = std::move(desktop); preparation_ = std::move(state); +} + +void StartupFlow::attach_initialized_career(CareerInitializationResult result) { + if (!pending_ || desktop_) throw FormatError("career attachment requires a pending new-career request"); + validate_desk_profile(pending_->options); + const auto& state = result.desktop; + if (state.source != "engine_projection" || state.options != pending_->options) + throw FormatError("career attachment: engine result does not match confirmed setup"); + validate_confirmed_manager_projection(pending_->managers, result.managers, state); + const auto runtime_teams = state.manager_teams; + auto desktop = std::make_unique(data_, std::move(result.desktop)); + desktop_ = std::move(desktop); pending_.reset(); engine_attached_ = true; + confirmed_runtime_teams_ = runtime_teams; +} + +void StartupFlow::acknowledge_desk(DeskState state) { + if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || state.source != "engine_projection") + throw FormatError("desk acknowledgement requires an attached engine projection"); + const bool turn_handoff = desktop_->pending() && desktop_->pending()->kind == DeskRequestKind::advance_turn; + validate_confirmed_desk(confirmed_, confirmed_runtime_teams_, desktop_->state().managers, + desktop_->state().national_coach_takeover, desktop_->state().national_return_roster, + turn_handoff, state); + desktop_->acknowledge(std::move(state)); + confirmed_runtime_teams_ = desktop_->state().manager_teams; + preparation_.reset(); // Require a fresh same-revision context after any desk command. +} + +void StartupFlow::show_notified_mailbox(MailboxState state) { + if (!desktop_ || !engine_attached_ || desktop_->pending() || in_preparation_menu() || + in_readonly_view() || matchday_results_ || !desktop_->state().mailbox_notification_pending || + desktop_->state().national_team || state.manager_slot != desktop_->state().manager_slot || + state.revision != desktop_->state().revision) + throw FormatError("mailbox: automatic notification requires the idle active club desk"); + mailbox_ = std::make_unique(data_, std::move(state), + original_to_utf8(desktop_->state().manager_name), desktop_->render()); +} + +void StartupFlow::acknowledge_mailbox_close(const MailboxCloseRequest& request, DeskState desk, + PreparationState preparation) { + if (!mailbox_ || !pending_mailbox_close_ || *pending_mailbox_close_ != request || !desktop_ || + !engine_attached_ || request.manager_slot != desktop_->state().manager_slot || + request.manager_slot != mailbox_->state().manager_slot || request.revision != desktop_->state().revision || + request.revision != mailbox_->state().revision || desk.source != "engine_projection" || + desk.revision != request.revision || preparation.desktop.revision != request.revision || + desk.manager_slot != request.manager_slot || desk.runtime_club != desktop_->state().runtime_club || + desk.day_counter != desktop_->state().day_counter || desk.mailbox_notification_pending) + throw FormatError("mailbox: mismatched notification close acknowledgement"); + auto expected = desktop_->state(); + expected.mailbox_notification_pending = false; + if (desk_json(expected) != desk_json(desk) || desk_json(desk) != desk_json(preparation.desktop)) + throw FormatError("mailbox: close acknowledgement changed unrelated desk state"); + validate_preparation_context(preparation); + auto next_preparation = std::make_unique(std::move(preparation)); + desktop_->acknowledge_mailbox_parent(std::move(desk)); + preparation_ = std::move(next_preparation); + mailbox_.reset(); + pending_mailbox_close_.reset(); +} + +void StartupFlow::reject_mailbox_close(std::string reason) { + if (!pending_mailbox_close_ || !mailbox_) throw FormatError("mailbox: no pending close to reject"); + pending_mailbox_close_.reset(); + mailbox_->cancel_close_request(); + mailbox_->reject(std::move(reason)); +} + +void StartupFlow::acknowledge_desk_notice(const DeskRequest& owner) { + if(!desktop_||!desktop_->pending()||*desktop_->pending()!=owner|| + owner.kind!=DeskRequestKind::open_menu||owner.menu_kind!=4) + throw FormatError("desk notice: mismatched achievements owner"); + desktop_->resolve_local_menu(); +} + +void StartupFlow::reject_desk_action(std::string reason) { + if (!desktop_) throw FormatError("no desktop action context"); + desktop_->reject_action(std::move(reason)); +} + +bool StartupFlow::acknowledge_friendly_quote(FriendlyQuoteProjection quote) { + if (!friendly_match_ || !pending_friendly_action_ || + pending_friendly_action_->kind != FriendlyRequestKind::quote || + !friendly_match_->acknowledge_quote(std::move(quote))) return false; + pending_friendly_action_.reset(); + return true; +} + +bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack) { + if (!friendly_match_ || !pending_friendly_action_ || + pending_friendly_action_->kind != FriendlyRequestKind::book || ack.accepted || + !friendly_match_->acknowledge_booking(ack)) return false; + pending_friendly_action_.reset(); + return true; +} + +bool StartupFlow::acknowledge_friendly_booking(FriendlyBookingAck ack, DeskState desk, + PreparationState preparation) { + if (!friendly_match_ || !pending_friendly_action_ || + pending_friendly_action_->kind != FriendlyRequestKind::book || !ack.accepted || !desktop_ || !engine_attached_) + return false; + if (desk.source != "engine_projection" || desk.revision != desktop_->state().revision + 1 || + desk.revision != ack.revision || desk.manager_slot != desktop_->state().manager_slot || + desk.manager_teams != desktop_->state().manager_teams || + preparation.desktop.revision != desk.revision || preparation.desktop.manager_slot != desk.manager_slot || + preparation.desktop.manager_teams != desk.manager_teams || + preparation.desktop.runtime_club != desk.runtime_club || preparation.desktop.source != desk.source) + return false; + validate_confirmed_desk(confirmed_, confirmed_runtime_teams_, desktop_->state().managers, + desktop_->state().national_coach_takeover, desktop_->state().national_return_roster, + false, desk); + validate_desk_state(desk); + validate_preparation_context(preparation); + auto next_desktop = std::make_unique(data_, desk); + auto next_preparation = std::make_unique(std::move(preparation)); + if (!friendly_match_->acknowledge_booking(ack)) return false; + desktop_ = std::move(next_desktop); + preparation_ = std::move(next_preparation); + confirmed_runtime_teams_ = desktop_->state().manager_teams; + pending_friendly_action_.reset(); + // Source menu6 exits after Max succeeds; it has no success dialog. + friendly_match_.reset(); + return true; +} + +void StartupFlow::reject_friendly_action(std::string reason) { + if (!friendly_match_ || !pending_friendly_action_ || reason.empty()) + throw FormatError("friendly match rejection requires a pending request"); + friendly_match_->reject(std::move(reason)); + pending_friendly_action_.reset(); +} + +void StartupFlow::acknowledge_saved_game(DeskState desk, PreparationState preparation) { + if (!save_load_ || !save_load_->pending() || save_load_->pending()->file_kind != SaveLoadFileKind::game || + save_load_->pending()->action != SaveLoadAction::save || + !desktop_ || !engine_attached_ || desk.source != "engine_projection" || + desk.manager_slot != save_load_->pending()->manager_slot || desk.revision <= save_load_->pending()->revision || + preparation.desktop.revision != desk.revision || preparation.desktop.manager_slot != desk.manager_slot) + throw FormatError("save/load: saved-game acknowledgement does not match the pending save"); + validate_confirmed_desk(confirmed_, confirmed_runtime_teams_, desktop_->state().managers, + desktop_->state().national_coach_takeover, desktop_->state().national_return_roster, + false, desk); + validate_desk_state(preparation.desktop); + if (preparation.desktop.manager_teams != desk.manager_teams || preparation.desktop.runtime_club != desk.runtime_club) + throw FormatError("save/load: save projection manager mapping mismatch"); + if (desk.managers.size() != desktop_->state().managers.size()) + throw FormatError("save/load: manager roster changed while saving"); + for (size_t i=0;istate().managers[i].name || + desk.managers[i].portrait != desktop_->state().managers[i].portrait) + throw FormatError("save/load: manager identity changed while saving"); + auto next_desktop = std::make_unique(data_, desk); + auto next_preparation = std::make_unique(std::move(preparation)); + save_load_->acknowledge(); save_load_.reset(); + desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); +} + +void StartupFlow::reject_file_action(std::string reason) { + if (!save_load_) throw FormatError("save/load: no file dialog"); + save_load_->reject(std::move(reason)); +} + +void StartupFlow::acknowledge_menu_layout(DeskState desk, PreparationState preparation) { + if (!save_load_ || !save_load_->pending() || + save_load_->pending()->file_kind != SaveLoadFileKind::menu_layout || + !desktop_ || !engine_attached_ || + desk.source != "engine_projection" || preparation.desktop.source != desk.source || + desk.manager_slot != save_load_->pending()->manager_slot || + desk.revision != save_load_->pending()->revision + 1 || + preparation.desktop.revision != desk.revision || + preparation.desktop.manager_slot != desk.manager_slot) + throw FormatError("save/load: menu-layout acknowledgement does not match the pending operation"); + const DeskState& before = desktop_->state(); + if (save_load_->pending()->origin_item_id < 0 || save_load_->pending()->origin_item_id >= 54 || + !before.menu_layout_shortcut || + before.menu_layout_shortcut->id != save_load_->pending()->origin_item_id) + throw FormatError("save/load: menu-layout origin no longer matches the active desktop record"); + validate_confirmed_desk(confirmed_, confirmed_runtime_teams_, before.managers, + before.national_coach_takeover, before.national_return_roster, false, desk); + validate_desk_state(desk); + validate_desk_state(preparation.desktop); + if (desk.options != before.options || desk.runtime_club != before.runtime_club || + desk.manager_teams != before.manager_teams || desk.managers != before.managers || + desk.manager_slot != before.manager_slot || desk.league != before.league || + desk.portrait != before.portrait || desk.badge != before.badge || + desk.day_counter != before.day_counter || desk.season_index != before.season_index || + desk.season_day != before.season_day || desk.date.year != before.date.year || + desk.date.month != before.date.month || desk.date.day != before.date.day || + desk.date.weekday != before.date.weekday || + desk.national_team != before.national_team || + desk.national_coach_takeover != before.national_coach_takeover || + desk.national_return_roster != before.national_return_roster || + preparation.desktop.manager_teams != desk.manager_teams || + preparation.desktop.runtime_club != desk.runtime_club || + preparation.desktop.managers != desk.managers || preparation.desktop.options != desk.options) + throw FormatError("save/load: menu-layout operation changed career ownership or calendar"); + auto expected = before; + expected.revision = desk.revision; + expected.source = desk.source; + expected.items = desk.items; + expected.mailbox_shortcut = desk.mailbox_shortcut; + expected.menu_layout_shortcut = desk.menu_layout_shortcut; + if (desk_json(expected) != desk_json(desk) || desk_json(desk) != desk_json(preparation.desktop)) + throw FormatError("save/load: menu-layout acknowledgement changed state outside the active menu design"); + validate_preparation_context(preparation); + auto next_desktop = std::make_unique(data_, std::move(desk)); + auto next_preparation = std::make_unique(std::move(preparation)); + save_load_->acknowledge(); save_load_.reset(); + desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); +} + +void StartupFlow::attach_loaded_game(DeskState desk, PreparationState preparation) { + if (!save_load_ || !save_load_->pending() || save_load_->pending()->action != SaveLoadAction::load || + save_load_->pending()->file_kind != SaveLoadFileKind::game || + desk.source != "engine_projection" || preparation.desktop.source != desk.source || + desk.revision <= save_load_->pending()->revision || preparation.desktop.manager_slot != desk.manager_slot || + preparation.desktop.revision != desk.revision) + throw FormatError("save/load: loaded-game projection does not match the pending load"); + validate_desk_state(desk); + validate_desk_state(preparation.desktop); + if (preparation.desktop.manager_teams != desk.manager_teams || preparation.desktop.runtime_club != desk.runtime_club) + throw FormatError("save/load: loaded-game manager mapping mismatch"); + auto next_desktop = std::make_unique(data_, desk); + auto next_preparation = std::make_unique(std::move(preparation)); + save_load_->acknowledge(); save_load_.reset(); + desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); + manager_.reset(); pending_.reset(); confirmed_.clear(); awaiting_context_ = false; + confirmed_runtime_teams_ = desk.manager_teams; + engine_attached_ = true; +} + +bool StartupFlow::resume_manager_selection(SelectionContext context) { + if (!awaiting_context_ || context.revision <= roster_revision_ || context.club_order.empty()) + throw FormatError("manager selection: expected a newer engine/reference club-order context"); + // Construct before mutation so a bad context leaves the pending request intact. + auto next = std::make_unique(data_, int(confirmed_.size()), confirmed_, context); + roster_revision_ = context.revision; roster_source_ = context.source; + manager_ = std::move(next); awaiting_context_ = false; + return true; +} + +std::string StartupFlow::screen_name() const { + if (indoor_standings_) return "indoor_standings"; + if(achievements_)return "achievements"; + if (settings_readme_) return "settings_readme"; + if(desk_records_)return desk_records_->kind()==DeskRecordKind::fair_play?"fair_play":"highscore"; + if(other_games_)return "other_games"; + if(balance_)return "balance_plan"; + if(top_scorers_)return "top_scorers"; + if(alltime_table_)return "alltime_table"; + if(world_cup_statistics_)return national_friendly_picker_?"national_friendly_picker":"world_cup_statistics"; + if(finance_totals_)return "finance_totals"; + if(series_records_)return "series_records"; + if(analytics_)return "analytics"; + if(statistics_rankings_)return "statistics_rankings"; + if(minute_statistics_)return "minute_statistics"; + if(transfer_history_)return "transfer_history"; + if(opportunities_)return "opportunities"; + if(statistics_menu_)return "statistics_menu"; + if(strengths_)return "strengths"; + if (calendar_) return calendar_->state().reschedule_manager >= 0 ? "reschedule_calendar" : "calendar"; + if(league_pairings_)return "league_pairings"; + if (joining_) return manager_ ? manager_->screen_name() : "joining_options"; + if (outgoing_transfer_) return "outgoing_transfer"; + if (friendly_table_active_) return "friendly_match"; + return player_card_ ? (player_card_->in_statistics() ? "player_statistics" : "player_card") : contracts_ ? "contracts" : friendly_match_ ? "friendly_match" : league_table_ ? "league_table" : mailbox_ ? "mailbox" : save_load_ ? "save_load" : settings_ ? "settings" : advertising_ ? "advertising" : environment_ ? "environment" : matchday_results_ ? "matchday_results" : player_card_ ? (player_card_->in_statistics() ? "player_statistics" : "player_card") : pitch_ ? "pitch" : lineup_ ? "lineup" : training_ ? "training" : training_camp_ ? "training_camp" : bank_ ? "bank" : stadium_ ? "stadium" : toto_ ? "toto" : transfer_market_ ? "transfer_market" : tactics_ ? "tactics" : desktop_ ? "desktop" : pending_ ? "career_pending" : awaiting_context_ ? "manager_pending" : manager_ ? manager_->screen_name() : "setup"; +} +std::string StartupFlow::state_json() const { + if (indoor_standings_) return indoor_standings_->state_json(); + if(achievements_)return "{\"screen\":\"achievements\",\"manager\":"+ + std::to_string(achievements_->state().manager_slot)+",\"season_count\":"+ + std::to_string(achievements_->state().season_count)+",\"selected_season\":"+ + std::to_string(achievements_->state().selected_season)+"}"; + if (settings_readme_) { + return "{\"screen\":\"settings_readme\",\"available\":" + + std::string(settings_readme_->file_available() ? "true" : "false") + + ",\"displayed_bytes\":" + std::to_string(settings_readme_->displayed_bytes()) + + ",\"close_input\":\"left_or_right_mouse_down\"}"; + } + if (joining_) { + std::ostringstream out; + out << "{\"screen\":" << json_quote(screen_name()) << ",\"joining_manager\":true,\"engine_attached\":true,\"revision\":" + << join_origin_.revision << ",\"options\":" << setup_json(join_setup_->options()) + << ",\"confirmed_count\":" << join_choices_.size(); + if (manager_) out << ",\"manager\":" << manager_json(manager_->choice()); + out << "}"; return out.str(); + } + const auto with_attachment = [&](std::string value) { + const std::string field = "\"engine_attached\":false"; + const auto at = value.find(field); + if (engine_attached_ && at != std::string::npos) value.replace(at, field.size(), "\"engine_attached\":true"); + return value; + }; + if (contracts_ && !player_card_) return contracts_->state_json(); + if (environment_) return environment_->state_json(); + if (outgoing_transfer_) return outgoing_transfer_->state_json(); + if(other_games_)return other_games_->state_json(); + if(desk_records_)return std::string("{\"screen\":\"")+ + (desk_records_->kind()==DeskRecordKind::fair_play?"fair_play":"highscore")+"\",\"close_input\":\"original_wait\"}"; + if(top_scorers_)return top_scorers_->state_json(); + if(world_cup_statistics_&&national_friendly_picker_) + return "{\"screen\":\"national_friendly_picker\",\"manager\":"+ + std::to_string(national_friendly_owner_.manager)+",\"runtime_team\":"+ + std::to_string(national_friendly_owner_.runtime_team)+",\"revision\":"+ + std::to_string(national_friendly_owner_.revision)+",\"request_id\":"+ + std::to_string(national_friendly_owner_.sequence)+"}"; + if(world_cup_statistics_)return "{\"screen\":\"world_cup_statistics\"}"; + if(analytics_)return "{\"screen\":\"analytics\",\"flags\":"+std::to_string(analytics_->state().source_flags)+"}"; + if(statistics_rankings_)return "{\"screen\":\"statistics_rankings\",\"category\":"+std::to_string(statistics_rankings_->state().category)+",\"first_season\":"+std::to_string(statistics_rankings_->state().first_season)+"}"; + if(minute_statistics_)return "{\"screen\":\"minute_statistics\",\"manager\":"+std::to_string(minute_statistics_->projection().manager_slot)+"}"; + if(transfer_history_)return "{\"screen\":\"transfer_history\",\"manager\":"+std::to_string(transfer_history_->projection().manager_slot)+",\"rows\":"+std::to_string(transfer_history_->projection().rows.size())+"}"; + if(opportunities_)return opportunities_->state_json(); + if(statistics_menu_)return statistics_menu_->state_json(); + if(strengths_)return strengths_->state_json(); + if(balance_)return balance_->state_json(); + if(league_pairings_)return league_pairings_->state_json(); + if (save_load_ && settings_) return save_load_->state_json(); + if (in_readonly_view()) { + auto result = calendar_ ? calendar_->state_json() : league_table_ ? league_table_->state_json() : mailbox_ ? mailbox_->state_json() : settings_ ? settings_->state_json() : advertising_->state_json(); + result.pop_back(); + return result + ",\"revision\":" + std::to_string(desktop_->state().revision) + + ",\"engine_attached\":" + (engine_attached_ ? "true" : "false") + + ",\"desktop_context\":" + with_attachment(desk_json(desktop_->state())) + "}"; + } + if (friendly_match_) { + auto result = friendly_match_->state_json(); + result.pop_back(); + return result + ",\"engine_attached\":" + (engine_attached_ ? "true" : "false") + + ",\"desktop_context\":" + desk_json(desktop_->state()) + "}"; + } + if (matchday_results_) return matchday_results_->state_json(); + if (save_load_) return save_load_->state_json(); + if (in_preparation_menu()) { + auto result = player_card_ ? player_card_->state_json() : pitch_ ? pitch_->state_json() : lineup_ ? lineup_->state_json() : training_ ? training_->state_json() : training_camp_ ? training_camp_->state_json() : bank_ ? bank_->state_json() : stadium_ ? stadium_->state_json() : toto_ ? toto_->state_json() : transfer_market_ ? transfer_market_->state_json() : tactics_->state_json(); + result.pop_back(); + result += ",\"pitch_context\":"; + result += !preparation_->pitch || !preparation_->pitch->indoor ? "null" : (*preparation_->pitch->indoor ? "\"indoor\"" : "\"outdoor\""); + if (lineup_ && !pitch_ && !player_card_ && lineup_->pending()) { + const auto& action = *lineup_->pending(); + std::string reason; + if (action.kind == LineupRequestKind::open_pitch) + reason = !preparation_->pitch || !preparation_->pitch->indoor ? "missing_transient_pitch_context" : "indoor_pitch_not_supported"; + if (action.kind == LineupRequestKind::open_player_info) { + reason = "missing_player_card_context"; + for (const auto& card : preparation_->player_cards) if (card.row == action.first_row) + reason = card.unsupported_record; + } + if (!reason.empty()) result += ",\"unavailable_navigation\":" + json_quote(reason); + } + return result + ",\"engine_attached\":" + (engine_attached_ ? "true" : "false") + + ",\"desktop_context\":" + with_attachment(desk_json(desktop_->state())) + "}"; + } + if (desktop_) { + return with_attachment(desktop_->state_json()); + } + std::ostringstream out; + out << "{\"screen\":" << json_quote(screen_name()) << ",\"options\":" << setup_json(setup_.options()) + << ",\"confirmed_managers\":["; + for (size_t i = 0; i < confirmed_.size(); ++i) { + if (i) out << ','; + out << manager_json(confirmed_[i]); + } + out << ']'; + if (manager_) out << ",\"manager\":" << manager_json(manager_->choice()); + out << ",\"roster_revision\":" << roster_revision_ << ",\"roster_source\":" << json_quote(roster_source_) + << ",\"engine_attached\":false}"; + return out.str(); +} + +} // namespace bmh::ui diff --git a/src/ui/flow.hpp b/src/ui/flow.hpp new file mode 100644 index 0000000..fe50c46 --- /dev/null +++ b/src/ui/flow.hpp @@ -0,0 +1,524 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +#include "ui/manager.hpp" +#include "ui/desktop.hpp" +#include "ui/preparation.hpp" +#include "ui/save_load.hpp" +#include "ui/stadium.hpp" +#include "ui/matchday_results_screen.hpp" +#include "ui/league_table.hpp" +#include "ui/league_table_range_dialog.hpp" +#include "ui/league_pairings.hpp" +#include "ui/mailbox_screen.hpp" +#include "ui/settings.hpp" +#include "ui/advertising.hpp" +#include "ui/friendly_match.hpp" +#include "ui/national_friendly_ui.hpp" +#include "ui/calendar.hpp" +#include "ui/strengths.hpp" +#include "ui/top_scorers.hpp" +#include "ui/desk_records.hpp" +#include "ui/opportunities.hpp" +#include "ui/statistics_rankings.hpp" +#include "ui/analytics.hpp" +#include "ui/minute_statistics.hpp" +#include "ui/transfer_history.hpp" +#include "ui/contracts.hpp" +#include "ui/outgoing_transfer.hpp" +#include "ui/balance_plan.hpp" +#include "ui/other_games.hpp" +#include "ui/alltime_table.hpp" +#include "ui/world_cup_statistics.hpp" +#include "ui/finance_totals.hpp" +#include "ui/series_records.hpp" +#include "ui/environment.hpp" +#include "ui/indoor_standings.hpp" +#include "ui/achievements.hpp" + +namespace bmh::ui { + +// Value boundary for the future engine adapter. No RNG, RAM or save writes. +struct NewCareerRequest { + SetupOptions options; + std::vector managers; +}; +struct InitializedManager { int slot = -1, master_club = -1, runtime_club = -1; }; +struct CareerInitializationResult { + DeskState desktop; + std::vector managers; + PreparationState preparation; +}; +enum class FlowRequest { none, load_game, manager_confirmed, new_career, kickoff, desk_action, end_session, submenu_opened, submenu_closed, contracts_closed, submenu_action, file_action, results_closed, mailbox_action, mailbox_closed, settings_action, settings_close, settings_file_action, friendly_action, national_friendly_selected, contract_action, advertising_action, environment_action, join_options, join_manager, join_cancel, league_pairings_action, strengths_action, top_scorers_action, balance_action, other_games_action, league_family_action, opportunities_action, statistics_menu_action, statistics_rankings_action, analytics_action, statistics_page_action, reschedule_action }; +enum class StatisticsPageActionKind : uint8_t { close, alltime, world_cup }; +struct StatisticsPageAction { DeskRequest owner{}; int page=-1; StatisticsPageActionKind kind=StatisticsPageActionKind::close; int nation=-1; bool relative=false; bool operator==(const StatisticsPageAction&) const = default; }; +struct FlowResult { + bool changed = false; + FlowRequest request = FlowRequest::none; + DeskRequest desk_action{}; + PreparationRequest submenu_action{}; + SaveLoadRequest file_action{}; + MailboxActionRequest mailbox_action{}; + MailboxCloseRequest mailbox_close{}; + SettingsWriteRequest settings_action{}; + uint64_t settings_owner_sequence = 0; + FriendlyMatchRequest friendly_action{}; + int national_friendly_opponent = -1; + ContractRequest contract_action{}; + AdvertisingRequest advertising_action{}; + EnvironmentRequest environment_action{}; + SetupOptions join_options{}; + ManagerChoice join_manager{}; + LeaguePairingsRequest league_pairings_action{}; + StrengthsRequest strengths_action{}; + TopScorersRequest top_scorers_action{}; + OpportunitiesRequest opportunities_action{}; + StatisticsMenuRequest statistics_menu_action{}; + StatisticsRankingsRequest statistics_rankings_action{}; + AnalyticsRequest analytics_action{}; + StatisticsPageAction statistics_page_action{}; + BalanceRequest balance_action{}; + OtherGamesRequest other_games_action{}; + LeagueFamilyRequest league_family_action{}; + RescheduleAction reschedule_action{}; +}; + +class StartupFlow { +public: + explicit StartupFlow(const std::filesystem::path& data, std::filesystem::path save_directory = {}) + : data_(data), save_directory_(save_directory.empty() ? data : std::move(save_directory)), setup_(data) {} + FlowResult click(int x, int y, bool right = false, bool double_click = false); + FlowResult pointer_down(int x,int y,bool right=false); + FlowResult process_timer_expired(int pointer_x = 0, int pointer_y = 0); + bool timed_notice_open() const; + FlowResult expire_timed_notice(); + // The synchronous SDL question presenter consumes the original nation-click UP. + // Call only after that modal has returned; right-DOWN close keeps its barrier. + void acknowledge_national_friendly_modal_release() { national_friendly_release_barrier_=false; } + FlowResult expire_stadium_tip(); + bool in_stadium() const { return bool(stadium_); } + bool in_pitch() const { return bool(pitch_); } + std::optional pitch_formation_save_feedback(bool restored) const; + FlowResult pitch_held_left(int x, int y, uint64_t source_ticks); + void consume_orphaned_pitch_release(){pitch_release_barrier_=false;} + const StadiumScreen* stadium() const { return stadium_.get(); } + const TotoScreen* toto() const { return toto_.get(); } + FlowResult hold(int x, int y, int milliseconds); + FlowResult move_action(int x, int y); + bool move(int x, int y) { return move_action(x, y).changed; } + bool text(std::string_view value); + bool key(std::string_view value) { return send_key(value).changed; } + FlowResult send_key(std::string_view value); + bool resume_manager_selection(SelectionContext context); + void show_manager_join(std::vector existing, SelectionContext context); + void resume_manager_join(SelectionContext context); + void acknowledge_manager_join(CareerInitializationResult result); + void reject_manager_join(std::string reason); + const DeskRequest* join_origin() const { return joining_ ? &join_origin_ : nullptr; } + const SetupOptions* pending_join_options() const { return join_options_pending_ ? &join_setup_->options() : nullptr; } + const ManagerChoice* pending_join_manager() const { return join_choice_pending_ ? &join_choices_.back() : nullptr; } + Image render() const; + void load_reference(const std::filesystem::path& save, std::optional indoor = std::nullopt); + void attach_initialized_career(CareerInitializationResult result); + void acknowledge_desk(DeskState state); + void reject_desk_action(std::string reason); + void acknowledge_desk_notice(const DeskRequest& owner); + void acknowledge_saved_game(DeskState desk, PreparationState preparation); + // Complete an authenticated menu-layout operation while preserving the active career. + void acknowledge_menu_layout(DeskState desk, PreparationState preparation); + void reject_file_action(std::string reason); + void attach_loaded_game(DeskState desk, PreparationState preparation); + const SaveLoadRequest* pending_file() const { + return save_load_ && save_load_->pending() ? &*save_load_->pending() : nullptr; + } + void attach_preparation_context(PreparationState state); + void show_matchday_results(MatchdayResults results); + bool in_results_view() const { return bool(matchday_results_); } + bool in_settings() const { return bool(settings_ && !save_load_); } + bool settings_readme_release_pending() const { return settings_readme_release_barrier_; } + void show_league_tables(std::array tables, int initial_league); + void show_family_league_tables(std::array tables, int initial_league, + StrengthsIdentity identity, std::optional preparation = {}); + void show_family_table_dispatch(std::array tables, int initial_league, + StrengthsIdentity identity, std::optional dialog = {}, + std::optional dialog_stage = {}, bool forecast_needs_present = false, + std::optional preparation = {}, bool friendly_entry = false); + // Accept a same-league internal selector operation without replacing its visible Table frame. + void acknowledge_family_selector(const LeagueFamilyRequest& old_request, + const StrengthsIdentity& accepted_identity); + void begin_league_family(StrengthsIdentity identity); + bool friendly_table_active() const { return friendly_table_active_; } + void acknowledge_friendly_own_club(const LeagueFamilyRequest&,StrengthsIdentity); + void complete_friendly_opponent_table(const LeagueFamilyRequest&,FriendlyMatchState,PreparationState); + void close_league_family(const LeagueFamilyRequest&, PreparationState); + void reject_league_family(std::string reason); + const std::optional& league_family_identity() const { return league_family_identity_; } + uint8_t league_family_child() const { return league_family_child_; } + void replace_family_child(); + const LeagueFamilyRequest* pending_league_family_action() const; + FlowResult after_family_table_present(uint64_t absolute_source_units); + FlowResult tick_family_table_source_units(uint64_t absolute_source_units); + FlowResult cancel_family_table_from_source_event(); + bool in_family_table_range_dialog() const { return bool(family_table_range_dialog_); } + bool family_table_range_input_ready() const { + return family_table_range_dialog_ && !family_table_dispatch_pending_ && + family_table_range_dialog_->source_input_ready(); + } + bool in_toto_calculator() const { return toto_ && toto_->calculator_open(); } + bool toto_calculator_input_ready() const { return toto_ && toto_->calculator_input_ready(); } + FlowResult after_toto_present(uint64_t source_units); + FlowResult tick_toto_source_units(uint64_t source_units); + void show_league_pairings(LeaguePairingsState); + void show_family_league_pairings(LeaguePairingsState, StrengthsIdentity); + void acknowledge_league_pairings(LeaguePairingsState, std::optional family = {}); + void close_league_pairings(PreparationState); + void reject_league_pairings(std::string reason); + bool in_league_pairings() const {return bool(league_pairings_);} + bool in_family_table() const { return league_table_ && league_family_identity_ && league_family_child_==1; } + FlowResult tick_league_pairings_source_seconds(uint64_t now); + void mark_league_pairings_presented_source_seconds(uint64_t now); + const LeaguePairingsScreen* league_pairings() const {return league_pairings_.get();} + const LeaguePairingsRequest* pending_league_pairings() const { + return league_pairings_&&league_pairings_->pending()?&*league_pairings_->pending():nullptr; + } + const LeagueFamilyRequest* pending_pairings_family_action() const { + return league_pairings_&&league_pairings_->pending_family_action()?&*league_pairings_->pending_family_action():nullptr; + } + void show_mailbox(MailboxState state); + // Source's MailboxRecipientMask popup is consumed after the native desk draw, without a + // synthetic DeskRequest. The app polls the Session latch only at an idle desk. + void show_notified_mailbox(MailboxState state); + bool in_mailbox() const { return bool(mailbox_); } + const MailboxActionRequest* pending_mailbox() const { return mailbox_ && mailbox_->pending() ? &*mailbox_->pending() : nullptr; } + const MailboxCloseRequest* pending_mailbox_close() const { return pending_mailbox_close_ ? &*pending_mailbox_close_ : nullptr; } + const BankRequest* pending_bank_action() const { + return bank_ && bank_->pending() ? &*bank_->pending() : nullptr; + } + const TransferMarketRequest* pending_transfer_market() const { + return transfer_market_ && transfer_market_->pending() ? &*transfer_market_->pending() : nullptr; + } + const OutgoingTransferRequest* pending_transfer_offer() const { + return outgoing_transfer_ && outgoing_transfer_->pending() ? &*outgoing_transfer_->pending() : nullptr; + } + void show_transfer_offer(PreparationState, OutgoingTransferEditorState); + void acknowledge_transfer_offer(PreparationState, OutgoingTransferEditorState); + void reject_transfer_offer(std::string reason); + void acknowledge_mailbox(MailboxState state, PreparationState preparation); + void acknowledge_mailbox_close(const MailboxCloseRequest&, DeskState, PreparationState); + void reject_mailbox_close(std::string reason); + void reject_mailbox(std::string reason); + const SettingsWriteRequest* pending_settings() const { return settings_ && settings_->pending() ? settings_->pending() : nullptr; } + void acknowledge_settings(SettingsState state, DeskState desk, PreparationState preparation); + void reject_settings(std::string reason); + void acknowledge_settings_notice_release(); + void acknowledge_settings_file(SettingsState state, DeskState desk, PreparationState preparation); + void reject_settings_file(std::string reason); + void cancel_settings_file(); + void acknowledge_settings_closed(SettingsState, DeskState, PreparationState); + void reject_settings_close(std::string reason); + void show_settings(SettingsState state, uint64_t owner_sequence = 0, DeskRequest owner = {}); + uint64_t settings_owner_sequence() const { return settings_owner_sequence_; } + const DeskRequest& settings_desk_owner() const { return settings_desk_owner_; } + uint64_t settings_owner_revision() const { return settings_ ? settings_->state().revision : settings_desk_owner_.revision; } + void show_advertising(AdvertisingState state); + const AdvertisingRequest* pending_advertising_action() const { + return advertising_ && advertising_->pending() ? &*advertising_->pending() : nullptr; + } + void acknowledge_advertising(AdvertisingState, DeskState, PreparationState); + void reject_advertising_action(std::string reason); + void show_environment(EnvironmentView, const DeskRequest& owner); + const EnvironmentScreen* environment() const { return environment_.get(); } + const EnvironmentRequest* pending_environment() const { + return environment_ && environment_->pending() ? &*environment_->pending() : nullptr; + } + void acknowledge_environment(EnvironmentView, std::optional preparation = {}); + void reject_environment_action(std::string reason); + bool in_environment() const { return bool(environment_); } + void show_achievements(AchievementsState, const DeskRequest& owner); + bool in_achievements() const { return bool(achievements_); } + const AchievementsScreen* achievements() const { return achievements_.get(); } + void show_strengths(StrengthsState, PreparationState, const DeskRequest& owner); + void show_family_strengths(StrengthsState, PreparationState); + void acknowledge_strengths(StrengthsState, PreparationState); + void close_strengths(StrengthsState, PreparationState); + void reject_strengths(std::string reason); + bool in_strengths() const { return bool(strengths_); } + const StrengthsScreen* strengths() const { return strengths_.get(); } + const StrengthsRequest* pending_strengths() const { + return strengths_&&strengths_->pending()?&*strengths_->pending():nullptr; + } + void show_top_scorers(TopScorersState, PreparationState, const DeskRequest& owner); + void acknowledge_top_scorers(TopScorersState, PreparationState); + void close_top_scorers(TopScorersState, PreparationState); + void reject_top_scorers(std::string reason); + bool in_top_scorers() const { return bool(top_scorers_); } + const TopScorersScreen* top_scorers() const { return top_scorers_.get(); } + const TopScorersRequest* pending_top_scorers() const { + return top_scorers_ && top_scorers_->pending() ? &*top_scorers_->pending() : nullptr; + } + void show_desk_records(DeskRecordsState, const DeskRequest& owner); + bool in_desk_records() const { return bool(desk_records_); } + const DeskRecordsScreen* desk_records() const { return desk_records_.get(); } + bool desk_records_points_active() const { return desk_records_&&desk_records_->points_active(); } + bool advance_desk_records_point() { return desk_records_&&desk_records_->advance_point(); } + bool finish_desk_records_points() { return desk_records_&&desk_records_->finish_points(); } + void show_opportunities(OpportunitiesState, PreparationState, const DeskRequest& owner); + void show_statistics_menu(const DeskRequest& owner, int transfer_history_count = 0); + void show_alltime_table(AllTimeTableState); + void show_world_cup_statistics(WorldCupStatisticsProjection); + void show_finance_totals(FinanceTotals); + void show_series_records(SeriesRecordsProjection); + FlowResult finish_statistics_page_input(bool changed); + const StatisticsPageAction* pending_statistics_page_action() const { return statistics_page_action_ ? &*statistics_page_action_ : nullptr; } + void close_statistics_page(); + bool in_statistics_page() const { return bool(alltime_table_||world_cup_statistics_||finance_totals_||series_records_); } + void show_statistics_rankings(StatisticsRankingState state); + void show_analytics(AnalyticsState state); + void acknowledge_analytics(AnalyticsState state, PreparationState preparation); + void close_analytics(); + void reject_analytics(); + bool in_analytics() const { return bool(analytics_); } + const AnalyticsScreen* analytics() const { return analytics_.get(); } + const AnalyticsRequest* pending_analytics() const { return analytics_ && analytics_->pending() ? &*analytics_->pending() : nullptr; } + void show_minute_statistics(MinuteStatisticsProjection projection); + void show_transfer_history(TransferHistoryProjection projection, const GameState& formatting_state, + int source_origin_y); + void acknowledge_statistics_rankings(StatisticsRankingState state); + void close_statistics_rankings(); + void reject_statistics_rankings(); + bool in_statistics_rankings() const { return bool(statistics_rankings_); } + bool in_minute_statistics() const { return bool(minute_statistics_); } + bool in_transfer_history() const { return bool(transfer_history_); } + const TransferHistoryScreen* transfer_history() const { return transfer_history_.get(); } + const StatisticsRankingsScreen* statistics_rankings() const { return statistics_rankings_.get(); } + const StatisticsRankingsRequest* pending_statistics_rankings() const { + return statistics_rankings_ && statistics_rankings_->pending() ? &*statistics_rankings_->pending() : nullptr; + } + void close_statistics_menu(); + void reject_statistics_menu(std::string reason); + bool in_statistics_menu() const { return bool(statistics_menu_); } + const StatisticsMenuScreen* statistics_menu() const { return statistics_menu_.get(); } + const StatisticsMenuRequest* pending_statistics_menu() const { + return statistics_menu_ && statistics_menu_->pending() ? &*statistics_menu_->pending() : nullptr; + } + void acknowledge_opportunities(OpportunitiesState, PreparationState); + void close_opportunities(OpportunitiesState, PreparationState); + void close_opportunities_for_statistics_parent(OpportunitiesState, PreparationState); + void reject_opportunities(std::string reason); + bool in_opportunities() const { return bool(opportunities_); } + const OpportunitiesScreen* opportunities() const { return opportunities_.get(); } + const OpportunitiesRequest* pending_opportunities() const { + return opportunities_ && opportunities_->pending() ? &*opportunities_->pending() : nullptr; + } + void show_balance(BalanceState, const DeskRequest& owner); + void acknowledge_balance(BalanceState); + void close_balance(BalanceState, PreparationState); + void reject_balance(std::string reason); + bool in_balance() const { return bool(balance_); } + const BalanceScreen* balance() const { return balance_.get(); } + const BalanceRequest* pending_balance() const { return balance_&&balance_->pending()?&*balance_->pending():nullptr; } + void show_other_games(OtherGamesState, PreparationState, const DeskRequest& owner); + void acknowledge_other_games(OtherGamesState, PreparationState); + void close_other_games(OtherGamesState, PreparationState); + void reject_other_games(std::string reason); + bool in_other_games() const { return bool(other_games_); } + const OtherGamesScreen* other_games() const { return other_games_.get(); } + const OtherGamesRequest* pending_other_games_action() const { + return other_games_ && other_games_->pending() ? &*other_games_->pending() : nullptr; + } + FlowResult tick_balance_source_milliseconds(uint64_t now); + void mark_balance_presented_source_milliseconds(uint64_t now); + FlowResult tick_stadium_calculator_source_ticks(unsigned ticks); + void mark_stadium_calculator_presented(); + void show_calendar(CalendarState state, const DeskRequest& owner); + const RescheduleAction* pending_reschedule_action() const { + return calendar_ && calendar_->pending_reschedule() ? &*calendar_->pending_reschedule() : nullptr; + } + void acknowledge_reschedule(CalendarState state, DeskRequest owner, DeskState desktop, + PreparationState preparation); + void reject_reschedule(); + bool source_mouse_wait_release_pending() const { + return indoor_standings_release_barrier_ || reschedule_release_barrier_ || achievements_release_barrier_ || desk_records_release_barrier_; + } + const CalendarScreen* calendar() const { return calendar_.get(); } + void show_indoor_standings(IndoorStandingsState state, const DeskRequest& owner); + const IndoorStandingsScreen* indoor_standings() const { return indoor_standings_.get(); } + bool in_indoor_standings() const { return bool(indoor_standings_); } + bool in_reschedule_calendar() const { return calendar_ && calendar_->state().reschedule_manager >= 0; } + void show_friendly_match(FriendlyMatchState state, int menu_kind = 6); + const LeagueTableScreen* friendly_opponent_picker() const { + return friendly_table_active_ ? league_table_.get() + : friendly_match_ ? friendly_match_->opponent_table() : nullptr; + } + const FriendlyMatchScreen* friendly_question_screen() const { + return friendly_match_ && friendly_match_->active_question() && !pending_friendly_action_ + ? friendly_match_.get() : nullptr; + } + FlowResult expire_friendly_question(bool release_consumed = false); + bool friendly_question_release_pending() const { return friendly_question_release_barrier_; } + const FriendlyQuoteProjection* friendly_calendar_quote() const { + return friendly_match_ && friendly_match_->stage() == FriendlyStage::calendar && friendly_match_->quote() + ? &*friendly_match_->quote() : nullptr; + } + void show_national_friendly_picker(WorldCupStatisticsProjection, const DeskRequest& owner, + int runtime_team); + const NationalFriendlyUiOwner* national_friendly_owner() const { + return national_friendly_picker_ ? &national_friendly_owner_ : nullptr; + } + const DeskRequest* national_friendly_desk_owner() const { + return national_friendly_picker_ ? &national_friendly_desk_owner_ : nullptr; + } + bool national_friendly_family_active() const { return national_friendly_picker_; } + void close_national_friendly_picker(); + void show_national_friendly_calendar(FriendlyMatchState, FriendlyQuoteProjection, + NationalFriendlyBookingRequest); + const FriendlyMatchRequest* pending_friendly_action() const { + return friendly_match_ && pending_friendly_action_ ? &*pending_friendly_action_ : nullptr; + } + bool acknowledge_friendly_quote(FriendlyQuoteProjection quote); + bool acknowledge_friendly_booking(FriendlyBookingAck ack); + bool acknowledge_friendly_booking(FriendlyBookingAck ack, DeskState desk, PreparationState preparation); + void reject_friendly_action(std::string reason); + void show_contracts(ContractsState state); + const ContractRequest* pending_contract_action() const { return contracts_ ? contracts_->pending() : nullptr; } + void acknowledge_contract_quote(ContractsState state, DeskState desk, PreparationState preparation); + void acknowledge_contract_offer(ContractsState state, DeskState desk, PreparationState preparation); + void acknowledge_contract_bonuses(ContractsState state, DeskState desk, PreparationState preparation); + void acknowledge_contract_insurance(ContractsState state, DeskState desk, PreparationState preparation); + void reject_contract_action(std::string reason); + bool in_readonly_view() const { return bool(desk_records_ || achievements_ || indoor_standings_ || other_games_ || strengths_ || top_scorers_ || opportunities_ || statistics_menu_ || statistics_rankings_ || analytics_ || minute_statistics_ || transfer_history_ || league_pairings_ || calendar_ || league_table_ || mailbox_ || settings_ || advertising_ || alltime_table_ || world_cup_statistics_ || finance_totals_ || series_records_); } + void acknowledge_preparation(PreparationState state, std::string transfer_notice = {}); + void reject_preparation_action(std::string reason); + void acknowledge_unchanged_transfer_market(); + void acknowledge_transfer_market_preview(PreparationState, TransferMarketPreview); + bool matches_pending_lineup(const LineupRequest&) const; + bool matches_pending_pitch(const PitchRequest&) const; + bool matches_pending_stadium(const StadiumRequest&) const; + bool in_preparation_menu() const { return bool(other_games_ || balance_ || player_card_ || pitch_ || lineup_ || training_ || training_camp_ || bank_ || stadium_ || environment_ || toto_ || transfer_market_ || tactics_ || save_load_ || friendly_match_ || contracts_); } + bool file_info_press(int x, int y) { return save_load_ && save_load_->info_press(x, y); } + const DesktopScreen* desktop() const { return desktop_.get(); } + std::string screen_name() const; + std::string state_json() const; + const SetupOptions& options() const { return setup_.options(); } + const NewCareerRequest* pending_career() const { return pending_.get(); } + const ManagerChoice* pending_manager() const { return awaiting_context_ ? &confirmed_.back() : nullptr; } +private: + FlowResult finish_statistics_rankings_input(bool changed); + FlowResult finish_analytics_input(bool changed); + bool joining_ = false, join_options_pending_ = false, join_choice_pending_ = false; + DeskRequest join_origin_; + std::unique_ptr join_setup_; + std::vector join_choices_; + uint64_t join_context_revision_ = 0; + void acknowledge_contract_mutation(ContractsState, DeskState, PreparationState, ContractActionKind); + std::filesystem::path data_; + std::filesystem::path save_directory_; + SetupScreen setup_; + std::unique_ptr manager_; + std::vector confirmed_; + std::unique_ptr pending_; + std::unique_ptr desktop_; + std::unique_ptr matchday_results_; + std::unique_ptr calendar_; + std::unique_ptr indoor_standings_; + bool indoor_standings_release_barrier_ = false; + std::unique_ptr strengths_; + std::unique_ptr top_scorers_; + std::unique_ptr desk_records_; + bool desk_records_release_barrier_ = false; + std::unique_ptr opportunities_; + std::unique_ptr statistics_menu_; + std::unique_ptr statistics_rankings_; + std::unique_ptr analytics_; + std::unique_ptr minute_statistics_; + std::unique_ptr transfer_history_; + std::unique_ptr alltime_table_; + std::unique_ptr world_cup_statistics_; + bool national_friendly_picker_ = false; + bool national_friendly_release_barrier_ = false; + NationalFriendlyUiOwner national_friendly_owner_{}; + DeskRequest national_friendly_desk_owner_{}; + std::unique_ptr finance_totals_; + std::unique_ptr series_records_; + std::optional statistics_page_action_; + int transfer_history_origin_y_ = 0; + std::unique_ptr league_table_; + std::unique_ptr family_table_range_dialog_; + std::optional family_table_range_profile_; + std::optional family_table_range_stage_; + std::optional family_table_last_outcome_; + std::optional family_table_dispatch_pending_; + bool family_table_forecast_needs_present_ = false; + bool family_table_source_clock_anchor_valid_ = false; + bool family_table_reset_clock_after_present_ = false; + uint64_t family_table_source_clock_anchor_ = 0; + std::optional league_family_identity_; + bool friendly_table_active_ = false; + uint8_t league_family_child_ = 0; + bool family_table_release_barrier_ = false; + std::unique_ptr league_pairings_; + std::unique_ptr balance_; + std::unique_ptr other_games_; + std::unique_ptr mailbox_; + std::optional pending_mailbox_close_; + std::unique_ptr settings_; + std::unique_ptr settings_readme_; + uint64_t settings_owner_sequence_ = 0; + DeskRequest settings_desk_owner_{}; + bool settings_release_barrier_ = false; + bool settings_readme_release_barrier_ = false; + std::unique_ptr advertising_; + uint64_t advertising_generation_ = 1; + std::unique_ptr friendly_match_; + bool friendly_question_release_barrier_ = false; + std::unique_ptr contracts_; + std::unique_ptr environment_; + std::unique_ptr achievements_; + DeskRequest environment_owner_{}; + uint64_t contracts_generation_ = 1; + std::optional pending_friendly_action_; + uint64_t next_friendly_request_id_ = 1; + std::unique_ptr preparation_; + std::unique_ptr lineup_; + std::unique_ptr training_; + std::unique_ptr training_camp_; + std::unique_ptr bank_; + std::unique_ptr stadium_; + std::unique_ptr toto_; + std::unique_ptr transfer_market_; + std::unique_ptr outgoing_transfer_; + std::unique_ptr save_load_; + std::unique_ptr tactics_; + std::unique_ptr pitch_; + bool pitch_entry_pending_ = false; + std::unique_ptr player_card_; + FlowResult route_desk(DeskRequest); + FlowResult finish_preparation_input(PreparationRequest, bool changed); + FlowResult finish_file_input(bool changed); + FlowResult finish_settings_input(bool changed); + FlowResult finish_readonly_input(bool changed); + FlowResult finish_league_pairings_input(bool changed); + FlowResult finish_strengths_input(bool changed); + FlowResult finish_top_scorers_input(bool changed); + FlowResult finish_opportunities_input(bool changed); + FlowResult finish_statistics_menu_input(bool changed); + FlowResult finish_balance_input(bool changed); + FlowResult finish_other_games_input(bool changed); + bool engine_attached_ = false; + bool balance_release_barrier_ = false; + bool achievements_release_barrier_ = false; + bool pitch_release_barrier_ = false; + bool pitch_hold_release_barrier_ = false; + bool reschedule_release_barrier_ = false; + bool awaiting_context_ = false; + std::vector confirmed_runtime_teams_; + uint64_t roster_revision_ = 0; + std::string roster_source_ = "master_database"; +}; + +} // namespace bmh::ui diff --git a/src/ui/friendly_match.cpp b/src/ui/friendly_match.cpp new file mode 100644 index 0000000..ca17164 --- /dev/null +++ b/src/ui/friendly_match.cpp @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "ui/friendly_match.hpp" + +#include +#include +#include +#include + +#include "game/state.hpp" +#include "ui/desk_state.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" + +namespace bmh::ui { +namespace { +bool left_modal_button(int x, int y) { return x >= 76 && x < 154 && y >= 139 && y < 158; } + +std::string stage_name(FriendlyStage stage) { + switch (stage) { + case FriendlyStage::opponents: return "opponents"; + case FriendlyStage::venue: return "venue"; + case FriendlyStage::quote_pending: return "quote_pending"; + case FriendlyStage::cost_confirmation: return "cost_confirmation"; + case FriendlyStage::calendar: return "calendar"; + case FriendlyStage::owner_approval: return "owner_approval"; + case FriendlyStage::booking_pending: return "booking_pending"; + case FriendlyStage::complete: return "complete"; + case FriendlyStage::unavailable: return "unavailable"; + } + return "unavailable"; +} + +int initial_league(const FriendlyMatchState& state) { + if (state.selected_league>=0 && state.selected_league<9) return state.selected_league; + for (size_t league = 0; league < state.leagues.size(); ++league) + if (std::any_of(state.leagues[league].rows.begin(), state.leagues[league].rows.end(), + [&](const LeagueTableRow& row) { return row.runtime_team_id == state.runtime_team; })) + return int(league); + return 0; +} +bool needs_other_manager(const FriendlyQuoteProjection& quote,int manager) { + return (quote.payer_manager>=0&"e.payer_manager!=manager)|| + (quote.opponent_manager>=0&"e.opponent_manager!=manager); +} +} + +std::string friendly_match_request_json(const FriendlyMatchRequest& request) { + std::ostringstream out; + out << "{\"kind\":" << json_quote(request.kind == FriendlyRequestKind::quote ? "quote" : "book") + << ",\"request_id\":" << request.request_id << ",\"quote_id\":" << request.quote_id + << ",\"revision\":" << request.revision << ",\"manager_slot\":" << request.manager_slot + << ",\"runtime_team\":" << request.runtime_team << ",\"opponent\":" << request.opponent + << ",\"opponent_manager\":" << request.opponent_manager << ",\"season_day\":" << request.season_day + << ",\"payer_manager\":" << request.payer_manager << ",\"home_team\":" << request.home_team + << ",\"away_team\":" << request.away_team << ",\"cost\":" << request.cost + << ",\"planner_count\":" << request.planner_count + << ",\"approving_manager\":" << request.approving_manager + << ",\"manager_home\":" << (request.manager_home ? "true" : "false") + << ",\"accept_cost\":" << (request.accept_cost ? "true" : "false") + << ",\"accept_opponent\":" << (request.accept_opponent ? "true" : "false") + << ",\"consenting_manager\":" << request.consenting_manager << '}'; + return out.str(); +} + +FriendlyCalendarCell friendly_calendar_cell(const LeImage& executable, uint32_t season_start_counter, int season_day) { + if (season_day < 0 || season_day > 365) throw FormatError("friendly calendar: invalid season day"); + const auto date = desk_date(season_start_counter + uint32_t(season_day), executable); + CalendarDayProjection day; + day.date = date; + const auto cell = calendar_cell(day); + return {cell.x, cell.y, cell.width, cell.height}; +} + +FriendlyMatchScreen::FriendlyMatchScreen(const std::filesystem::path& data, FriendlyMatchState state, + int desk_menu_kind) + : state_(std::move(state)), desk_menu_kind_(desk_menu_kind), + table_(data, state_.leagues, initial_league(state_), LeagueTableScreen::OpponentMode{}), + font_(load_font(asset_path(data / "F", "BMH2.FNT"))), + exe_(load_le(asset_path(data, "BMH.exe"))), + data_(data), next_request_id_(state_.first_request_id) { + const bool valid_national_slot = state_.national_team && state_.runtime_team == bmh::kNoTeam; + if (state_.manager_slot < 0 || state_.manager_slot > 3 || state_.runtime_team < 0 || + (state_.runtime_team >= 168 && !valid_national_slot) || + state_.revision == UINT64_MAX || !state_.first_request_id || state_.planner_count < 0 || + state_.planner_count > std::numeric_limits::max() - 2) + throw FormatError("friendly screen: invalid manager/request identity"); + if (!state_.mode_three) { + stage_ = FriendlyStage::unavailable; + feedback_ = "Freundschaftsspiele sind nur in Modus III verfuegbar."; + } else if (state_.national_team || state_.runtime_team == bmh::kNoTeam) { + stage_ = FriendlyStage::unavailable; + feedback_ = "Freundschaftsspiele fuer die Nationalmannschaft sind hier nicht verfuegbar."; + } else if (desk_menu_kind_ != 6) { + stage_ = FriendlyStage::unavailable; + feedback_ = "Diese Freundschaftsspiel-Ansicht ist nicht verfuegbar."; + } + if (state_.selected_opponent>=0) { + if (stage_!=FriendlyStage::opponents || state_.selected_opponent==state_.runtime_team || + std::none_of(table_.state().rows.begin(),table_.state().rows.end(), + [&](const auto& row){return row.runtime_team_id==state_.selected_opponent;})) + throw FormatError("friendly screen: invalid authoritative opponent return"); + selected_opponent_=state_.selected_opponent; + stage_=FriendlyStage::venue; + } +} + +FriendlyMatchScreen::FriendlyMatchScreen(const std::filesystem::path& data, FriendlyMatchState state, + FriendlyQuoteProjection national_quote, NationalFriendlyBookingRequest national_booking, + int desk_menu_kind) + : FriendlyMatchScreen(data, std::move(state), desk_menu_kind) { + const bool source_owner = desk_menu_kind == 6 && national_quote.runtime_team == bmh::kNoTeam && + national_booking.owner.menu_kind == 6 && national_booking.owner.manager == national_quote.manager_slot && + national_booking.owner.runtime_team == bmh::kNoTeam && + national_booking.owner.revision == national_quote.revision && + national_booking.quote.terms.opponent == national_quote.opponent && + national_booking.quote.terms.manager_home == national_quote.manager_home && + national_booking.quote.terms.planner_count == national_quote.planner_count; + if (!source_owner || !state_.national_team || state_.runtime_team != bmh::kNoTeam || + state_.manager_slot != national_quote.manager_slot || state_.revision != national_quote.revision || + national_quote.dates.size() != 366 || national_quote.cost < 0 || + national_booking.quote.terms.status != bmh::FriendlyQuoteStatus::quoted || + national_booking.quote.owner.request_id == 0) { + stage_ = FriendlyStage::unavailable; + feedback_ = "Diese Freundschaftsspielanfrage ist nicht mehr aktuell."; + return; + } + const int expected_home = national_quote.manager_home ? bmh::kNoTeam : national_quote.opponent; + const int expected_away = national_quote.manager_home ? national_quote.opponent : bmh::kNoTeam; + if (national_quote.home_team != expected_home || national_quote.away_team != expected_away || + national_quote.payer_manager != national_booking.quote.terms.payer_manager || + national_quote.opponent_manager != national_booking.quote.terms.opponent_manager || + national_quote.cost != national_booking.quote.terms.cost) { + stage_ = FriendlyStage::unavailable; + feedback_ = "Das Freundschaftsspielangebot ist veraltet."; + return; + } + quote_ = std::move(national_quote); + national_booking_ = std::move(national_booking); + selected_opponent_ = quote_->opponent; + manager_home_ = quote_->manager_home; + cost_confirmed_ = true; + owner_approved_ = true; + stage_ = FriendlyStage::calendar; + feedback_.clear(); + prepare_calendar(); +} + +void FriendlyMatchScreen::prepare_calendar() { + if (!quote_) throw FormatError("friendly calendar: missing owned quote"); + std::array seen{}; + for (const auto& option : quote_->dates) { + if (option.season_day < 0 || option.season_day > 365 || seen[size_t(option.season_day)]) + throw FormatError("friendly calendar: inconsistent owned date options"); + seen[size_t(option.season_day)] = true; + } + if (std::find(seen.begin(), seen.end(), false) != seen.end()) + throw FormatError("friendly calendar: incomplete owned date options"); + auto calendar = state_.calendar; + if (calendar.days.empty() || + calendar.season_start_counter + uint32_t(calendar.leading_days) != state_.season_start_counter || + calendar.current_day - calendar.leading_days != state_.current_day) + throw FormatError("friendly calendar: calendar and quote have different native anchors"); + calendar.friendly_selection = true; + for (auto& day : calendar.days) { + const auto option = std::find_if(quote_->dates.begin(), quote_->dates.end(), + [&](const FriendlyDateOption& value) { return value.season_day == day.season_day; }); + day.friendly_target = option != quote_->dates.end() && + (option->mark == FriendlyDateMark::available || option->mark == FriendlyDateMark::available_flagged); + } + calendar_.emplace(data_, std::move(calendar), state_.manager_name, true, state_.runtime_team); +} + +bool FriendlyMatchScreen::move(int x, int y) { + if (!close_requested_ && stage_==FriendlyStage::opponents) return table_.move(x,y); + if(pressed_question_&&*pressed_question_!=GameEndTaxDialog::Button::none&& + question_button(x,y)!=*pressed_question_) { + pressed_question_=GameEndTaxDialog::Button::none;return true; + } + return !close_requested_ && stage_ == FriendlyStage::calendar && calendar_ && calendar_->move(x, y); +} + +const TaxDialogProjection* FriendlyMatchScreen::question_projection() const { + if(stage_==FriendlyStage::venue)return state_.venue_question?&*state_.venue_question:nullptr; + if(stage_==FriendlyStage::cost_confirmation&"e_) + return quote_->cost_question?&*quote_->cost_question:nullptr; + if(stage_==FriendlyStage::owner_approval&"e_) + return quote_->owner_question?&*quote_->owner_question:nullptr; + return nullptr; +} + +GameEndTaxDialog::Button FriendlyMatchScreen::question_button(int x,int y) const { + const auto* p=question_projection(); + if(!p)return GameEndTaxDialog::Button::none; + return GameEndTaxDialog(data_,*p,{},table_.render()).hit_test(x,y); +} + +bool FriendlyMatchScreen::pointer_down(int x,int y,bool right) { + if (!close_requested_ && stage_==FriendlyStage::opponents) return table_.pointer_down(x,y,right); + if(close_requested_||right||!question_projection())return false; + pressed_question_=question_button(x,y);return true; +} + +void FriendlyMatchScreen::text(Image& image, int x, int y, std::string_view value, + uint8_t color, int max_width) const { + std::string bytes; + try { bytes = utf8_to_original(value); } + catch (const FormatError&) { + for (unsigned char c : value) bytes += c < 128 ? char(c) : '?'; + } + while (!bytes.empty() && font_.text_width(bytes) > max_width) bytes.pop_back(); + if (x >= 0 && y >= 0 && y + font_.height <= image.height) font_.draw(image, x, y, bytes, color); +} + +Image FriendlyMatchScreen::render_modal(Image image, std::string_view heading, std::string_view detail, + std::string_view left, std::string_view right) const { + constexpr int x0 = 48, y0 = 76, x1 = 272, y1 = 165; + for (int y = y0; y < y1; ++y) for (int x = x0; x < x1; ++x) image.at(x, y) = 0x42; + for (int x = x0; x < x1; ++x) { image.at(x, y0) = 0x5f; image.at(x, y1 - 1) = 0x5f; } + for (int y = y0; y < y1; ++y) { image.at(x0, y) = 0x5f; image.at(x1 - 1, y) = 0x5f; } + text(image, x0 + 12, y0 + 10, heading, 0x4f, x1 - x0 - 24); + text(image, x0 + 12, y0 + 31, detail, 0x6a, x1 - x0 - 24); + const int button_y = y0 + 67; + text(image, x0 + 34, button_y, left, 0x4f, 72); + text(image, x0 + 126, button_y, right, 0x4f, 72); + return image; +} + +Image FriendlyMatchScreen::render() const { + if (stage_ == FriendlyStage::opponents) { + return table_.render(); + } + if(stage_==FriendlyStage::venue||stage_==FriendlyStage::cost_confirmation|| + stage_==FriendlyStage::owner_approval) { + const auto* p=question_projection(); + if(!p||p->kind!=TaxDialogKind::question) + throw FormatError("friendly question: missing Source question projection"); + return GameEndTaxDialog(data_,*p,{},table_.render()).render(pressed_question_); + } + if (stage_ == FriendlyStage::quote_pending) + return render_modal(table_.render(), "Freundschaftsspiel", "Kosten und Termine werden geprueft.", "", ""); + if (stage_ == FriendlyStage::booking_pending) + return render_modal(table_.render(), "Freundschaftsspiel", "Termin wird verbindlich geprueft.", "", ""); + if (stage_ == FriendlyStage::complete) + return render_modal(table_.render(), "Freundschaftsspiel vereinbart", feedback_, "WEITER", ""); + if (stage_ == FriendlyStage::unavailable) + return render_modal(table_.render(), "Nicht verfuegbar", feedback_, "ZURUECK", ""); + if (stage_ != FriendlyStage::calendar || !quote_) return table_.render(); + + if (!calendar_) throw FormatError("friendly calendar: missing Source calendar view"); + return calendar_->render(); +} + +std::string FriendlyMatchScreen::state_json() const { + std::ostringstream out; + out << "{\"screen\":\"friendly_match\",\"stage\":" << json_quote(stage_name(stage_)) + << ",\"menu_kind\":" << desk_menu_kind_ << ",\"revision\":" << state_.revision + << ",\"manager_slot\":" << state_.manager_slot << ",\"runtime_team\":" << state_.runtime_team + << ",\"league\":" << table_.selected_league() << ",\"opponent\":" << selected_opponent_ + << ",\"close_requested\":" << (close_requested_ ? "true" : "false") + << ",\"feedback\":" << json_quote(feedback_) + << ",\"planner_count\":" << state_.planner_count; + if (stage_==FriendlyStage::opponents) out << ",\"picker\":" << table_.state_json(); + if (quote_) out << ",\"quote_id\":" << quote_->request_id << ",\"payer_manager\":" << quote_->payer_manager + << ",\"opponent_manager\":" << quote_->opponent_manager << ",\"quoted_planner_count\":" << quote_->planner_count + << ",\"cost\":" << quote_->cost << ",\"home_team\":" << quote_->home_team + << ",\"away_team\":" << quote_->away_team; + if (selected_day_) out << ",\"selected_day\":" << *selected_day_; + out << '}'; + return out.str(); +} + +std::optional FriendlyMatchScreen::answer_question(GameEndTaxDialog::Button answer) { + const bool yes=answer==GameEndTaxDialog::Button::yes; + const bool no=answer==GameEndTaxDialog::Button::no; + if (stage_ == FriendlyStage::venue && (yes || no)) { + if (next_request_id_ >= std::numeric_limits::max() - 1) { + feedback_ = "Keine weitere Anfrage moeglich."; + return std::nullopt; + } + manager_home_ = yes; + cost_confirmed_ = false; + owner_approved_ = false; + quote_.reset(); + selected_day_.reset(); + FriendlyMatchRequest request; + request.kind = FriendlyRequestKind::quote; + request.request_id = next_request_id_++; + request.revision = state_.revision; + request.manager_slot = state_.manager_slot; + request.runtime_team = state_.runtime_team; + request.opponent = selected_opponent_; + request.planner_count = state_.planner_count; + request.manager_home = manager_home_; + stage_ = FriendlyStage::quote_pending; + return request; + } + if (stage_ == FriendlyStage::cost_confirmation && (yes || no)) { + if (yes) { + cost_confirmed_ = true; + stage_ = needs_other_manager(*quote_,state_.manager_slot)? + FriendlyStage::owner_approval:FriendlyStage::calendar; + return std::nullopt; + } + close_requested_ = true; + return std::nullopt; + } + if (stage_ == FriendlyStage::owner_approval && (yes || no)) { + if (yes) { + owner_approved_ = true; + stage_ = FriendlyStage::calendar; + return std::nullopt; + } + close_requested_ = true; + return std::nullopt; + } + return std::nullopt; +} + +std::optional FriendlyMatchScreen::expire_question() { + if(close_requested_||!question_projection())return std::nullopt; + pressed_question_.reset(); + return answer_question(GameEndTaxDialog::Button::no); +} + +std::optional FriendlyMatchScreen::click(int x, int y, bool right_button) { + if (close_requested_) return std::nullopt; + if (right_button) { + // PresentManagerDialog calls4885b for event8 too; without an expired process + // timer that helper returns -1, leaving the question and hold intact. + if (!question_projection()) close_requested_ = true; + return std::nullopt; + } + auto answer=question_button(x,y); + if(pressed_question_&&answer!=*pressed_question_)answer=GameEndTaxDialog::Button::none; + pressed_question_.reset(); + if (stage_ == FriendlyStage::opponents) { + if (table_.click(x,y)) { + close_requested_=table_.close_requested(); + return std::nullopt; + } + const auto& rows = table_.state().rows; + // FriendlyMatchScreen checks only the row interval, not the name-column x. + if (y<=0x1c || y>=int(rows.size())*7+0x1c) return std::nullopt; + const int row = (y-0x1d)/7; + if (row < 0 || size_t(row) >= rows.size()) return std::nullopt; + selected_opponent_ = rows[size_t(row)].runtime_team_id; + if (selected_opponent_ == state_.runtime_team || selected_opponent_ < 0 || selected_opponent_ >= 168) { + selected_opponent_ = -1; + feedback_ = "Bitte einen anderen Ligaverein waehlen."; + return std::nullopt; + } + stage_ = FriendlyStage::venue; + feedback_.clear(); + return std::nullopt; + } + if (question_projection()) return answer_question(answer); + if (stage_ == FriendlyStage::calendar) { + if (!calendar_) return std::nullopt; + calendar_->move(x, y); + for (const auto& date : calendar_->state().days) { + const int day = date.season_day; + if (day < 0) continue; // July cells preceding Source word zero are display only. + const auto cell = calendar_cell(date); + if (x < cell.x || x >= cell.x + cell.width || y < cell.y || y >= cell.y + cell.height) continue; + const auto it = std::find_if(quote_->dates.begin(), quote_->dates.end(), [day](const FriendlyDateOption& option) { + return option.season_day == day; + }); + if (it == quote_->dates.end() || (it->mark != FriendlyDateMark::available && + it->mark != FriendlyDateMark::available_flagged)) return std::nullopt; + selected_day_ = day; + if (national_booking_) { + return book_request(day, national_booking_->approving_manager, + national_booking_->consenting_manager); + } + if(needs_other_manager(*quote_,state_.manager_slot)&&!owner_approved_)return std::nullopt; + return book_request(day, quote_->payer_manager >= 0 ? quote_->payer_manager : -1, + quote_->opponent_manager >= 0 ? quote_->opponent_manager : -1); + } + } + if ((stage_ == FriendlyStage::complete || stage_ == FriendlyStage::unavailable) && + left_modal_button(x, y)) close_requested_ = true; + return std::nullopt; +} + +std::optional FriendlyMatchScreen::key(std::string_view value) { + if (close_requested_) return std::nullopt; + // The Original question loop has no keyboard answer/cancel mapping. + if (question_projection()) return std::nullopt; + if (value == "ESC") { close_requested_ = true; return std::nullopt; } + if (stage_ == FriendlyStage::opponents && (value == "LEFT" || value == "RIGHT")) { + table_.key(value); + return std::nullopt; + } + return std::nullopt; +} + +bool FriendlyMatchScreen::acknowledge_quote(FriendlyQuoteProjection quote) { + if (stage_ != FriendlyStage::quote_pending || quote.request_id != uint64_t(next_request_id_ - 1) || + quote.revision != state_.revision || quote.manager_slot != state_.manager_slot || + quote.runtime_team != state_.runtime_team || quote.opponent != selected_opponent_ || + quote.manager_home != manager_home_ || quote.cost < 0 || + quote.planner_count != state_.planner_count || quote.dates.size() != 366) + return false; + const int expected_home = manager_home_ ? state_.runtime_team : selected_opponent_; + const int expected_away = manager_home_ ? selected_opponent_ : state_.runtime_team; + const int expected_payer = manager_home_ ? state_.manager_slot : quote.opponent_manager; + if (quote.home_team != expected_home || quote.away_team != expected_away || + quote.payer_manager != expected_payer || + quote.payer_manager < -1 || quote.payer_manager > 3 || + quote.opponent_manager < -1 || quote.opponent_manager > 3) + return false; + std::array seen{}; + for (const auto& day : quote.dates) { + if (day.season_day < 0 || day.season_day > 365 || seen[size_t(day.season_day)]) return false; + seen[size_t(day.season_day)] = true; + } + if (std::find(seen.begin(), seen.end(), false) != seen.end()) return false; + quote_ = std::move(quote); + prepare_calendar(); + stage_ = manager_home_ ? FriendlyStage::cost_confirmation : + needs_other_manager(*quote_,state_.manager_slot)?FriendlyStage::owner_approval:FriendlyStage::calendar; + cost_confirmed_ = !manager_home_; + selected_day_.reset(); + owner_approved_ = false; + feedback_.clear(); + return true; +} + +std::optional FriendlyMatchScreen::book_request(int season_day, int approving_manager, + int consenting_manager) { + if (!quote_ || !selected_day_ || *selected_day_ != season_day || !cost_confirmed_ || + next_request_id_ == std::numeric_limits::max()) return std::nullopt; + FriendlyMatchRequest request; + request.kind = FriendlyRequestKind::book; + request.request_id = next_request_id_++; + request.quote_id = quote_->request_id; + request.revision = state_.revision; + request.manager_slot = quote_->manager_slot; + request.runtime_team = quote_->runtime_team; + request.opponent = quote_->opponent; + request.opponent_manager = quote_->opponent_manager; + request.season_day = season_day; + request.payer_manager = quote_->payer_manager; + request.home_team = quote_->home_team; + request.away_team = quote_->away_team; + request.cost = quote_->cost; + request.planner_count = quote_->planner_count; + request.approving_manager = approving_manager; + request.consenting_manager = consenting_manager; + request.manager_home = quote_->manager_home; + request.accept_cost = quote_->payer_manager >= 0 && + (quote_->payer_manager == state_.manager_slot ? cost_confirmed_ : owner_approved_); + request.accept_opponent = quote_->opponent_manager >= 0 && + quote_->opponent_manager != state_.manager_slot && owner_approved_; + if (national_booking_) { + auto national = *national_booking_; + national.season_day = uint16_t(season_day); + request.national_booking = std::move(national); + request.accept_cost = request.national_booking->accept_cost; + request.accept_opponent = request.national_booking->accept_opponent; + request.approving_manager = request.national_booking->approving_manager; + request.consenting_manager = request.national_booking->consenting_manager; + } + pending_booking_request_id_ = request.request_id; + stage_ = FriendlyStage::booking_pending; + return request; +} + +bool FriendlyMatchScreen::acknowledge_booking(const FriendlyBookingAck& ack) { + if (stage_ != FriendlyStage::booking_pending || !quote_ || + ack.request_id != pending_booking_request_id_ || ack.quote_id != quote_->request_id || + ack.manager_slot != quote_->manager_slot || + ack.runtime_team != quote_->runtime_team || ack.opponent != quote_->opponent || + ack.opponent_manager != quote_->opponent_manager || + !selected_day_ || ack.season_day != *selected_day_ || ack.payer_manager != quote_->payer_manager || + ack.home_team != quote_->home_team || ack.away_team != quote_->away_team || ack.cost != quote_->cost) + return false; + if (!ack.accepted) { + if (ack.revision != state_.revision || ack.planner_count != state_.planner_count) return false; + stage_ = FriendlyStage::calendar; + feedback_ = "Termin konnte nicht gebucht werden."; + selected_day_.reset(); + pending_booking_request_id_ = 0; + return true; + } + if (ack.revision != state_.revision + 1 || ack.planner_count != quote_->planner_count + 2) return false; + stage_ = FriendlyStage::complete; + state_.revision = ack.revision; + state_.planner_count = ack.planner_count; + pending_booking_request_id_ = 0; + feedback_ = "Der Termin wurde eingetragen."; + return true; +} + +void FriendlyMatchScreen::reject(std::string message) { + if (stage_ == FriendlyStage::quote_pending) { + stage_ = FriendlyStage::venue; + } else if (stage_ == FriendlyStage::booking_pending) { + stage_ = FriendlyStage::calendar; + selected_day_.reset(); + } + feedback_ = std::move(message); +} + +} // namespace bmh::ui diff --git a/src/ui/friendly_match.hpp b/src/ui/friendly_match.hpp new file mode 100644 index 0000000..5e98daf --- /dev/null +++ b/src/ui/friendly_match.hpp @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "ui/league_table.hpp" +#include "ui/calendar.hpp" +#include "ui/game_end.hpp" +#include "game/desk_actions.hpp" + +namespace bmh::ui { + +enum class FriendlyStage { opponents, venue, quote_pending, cost_confirmation, calendar, owner_approval, booking_pending, complete, unavailable }; +enum class FriendlyDateMark { unavailable, available, available_flagged, current_day }; +enum class FriendlyRequestKind { quote, book }; + +struct FriendlyDateOption { + int season_day = -1; + FriendlyDateMark mark = FriendlyDateMark::unavailable; +}; + +struct FriendlyCalendarCell { int x = 0, y = 0, width = 11, height = 8; }; +FriendlyCalendarCell friendly_calendar_cell(const LeImage& executable, uint32_t season_start_counter, int season_day); + +// Controller-facing value request. The app adds/validates the active desk revision, +// manager and request ID before calling the revisionless engine helpers. +struct FriendlyMatchRequest { + FriendlyRequestKind kind = FriendlyRequestKind::quote; + uint64_t request_id = 0; + uint64_t quote_id = 0; + uint64_t revision = 0; + int manager_slot = -1; + int runtime_team = -1; + int opponent = -1; + int opponent_manager = -1; + int season_day = -1; + int payer_manager = -1; + int home_team = -1; + int away_team = -1; + int cost = 0; + int planner_count = -1; + int approving_manager = -1; + bool manager_home = false; + bool accept_cost = false; + bool accept_opponent = false; + int consenting_manager = -1; + std::optional national_booking; + bool operator==(const FriendlyMatchRequest&) const = default; +}; +std::string friendly_match_request_json(const FriendlyMatchRequest& request); + +struct FriendlyQuoteProjection { + uint64_t request_id = 0; + uint64_t revision = 0; + int manager_slot = -1; + int runtime_team = -1; + int opponent = -1; + int opponent_manager = -1; + int payer_manager = -1; + int home_team = -1; + int away_team = -1; + int cost = 0; + int planner_count = -1; + bool manager_home = false; + std::vector dates; + std::optional cost_question; + std::optional owner_question; +}; + +struct FriendlyBookingAck { + uint64_t request_id = 0; + uint64_t quote_id = 0; + uint64_t revision = 0; + bool accepted = false; + int manager_slot = -1; + int runtime_team = -1; + int opponent = -1; + int opponent_manager = -1; + int season_day = -1; + int payer_manager = -1; + int home_team = -1; + int away_team = -1; + int cost = 0; + int planner_count = -1; +}; + +struct FriendlyMatchState { + uint64_t revision = 0; + uint64_t first_request_id = 1; + int manager_slot = -1; + int runtime_team = -1; + int current_day = -1; + int planner_count = -1; + uint32_t season_start_counter = 0; + bool mode_three = false; + bool national_team = false; + std::string manager_name; + std::array leagues; + CalendarState calendar; + std::optional venue_question; + int selected_opponent = -1; // Accepted FriendlyMatchScreen(2,0) return; never a UI row guess. + int selected_league = -1; +}; + +class FriendlyMatchScreen { +public: + FriendlyMatchScreen(const std::filesystem::path& data, FriendlyMatchState state, + int desk_menu_kind = 6); + FriendlyMatchScreen(const std::filesystem::path& data, FriendlyMatchState state, + FriendlyQuoteProjection national_quote, + NationalFriendlyBookingRequest national_booking, + int desk_menu_kind = 6); + FriendlyStage stage() const { return stage_; } + int selected_league() const { return table_.selected_league(); } + int selected_opponent() const { return selected_opponent_; } + const LeagueTableScreen* opponent_table() const { + return stage_==FriendlyStage::opponents ? &table_ : nullptr; + } + const std::optional& quote() const { return quote_; } + bool close_requested() const { return close_requested_; } + const std::string& feedback() const { return feedback_; } + Image render() const; + std::string state_json() const; + bool move(int x, int y); + bool pointer_down(int x, int y, bool right = false); + std::optional click(int x, int y, bool right_button = false); + std::optional key(std::string_view key); + bool acknowledge_quote(FriendlyQuoteProjection quote); + bool acknowledge_booking(const FriendlyBookingAck& ack); + void reject(std::string message); + const TaxDialogProjection* active_question() const { return question_projection(); } + bool question_held() const { + return pressed_question_ && *pressed_question_!=GameEndTaxDialog::Button::none; + } + bool question_release_pending() const { return pressed_question_.has_value(); } + // ExpireQuestion forces button1 (No) for an expired active process timer. + std::optional expire_question(); + +private: + FriendlyMatchState state_; + int desk_menu_kind_ = 23; + LeagueTableScreen table_; + Font font_; + LeImage exe_; + std::filesystem::path data_; + std::optional calendar_; + FriendlyStage stage_ = FriendlyStage::opponents; + int selected_opponent_ = -1; + bool manager_home_ = false; + bool cost_confirmed_ = false; + bool owner_approved_ = false; + bool close_requested_ = false; + uint64_t next_request_id_ = 1; + uint64_t pending_booking_request_id_ = 0; + std::optional quote_; + std::optional national_booking_; + std::optional selected_day_; + std::string feedback_; + std::optional pressed_question_; + const TaxDialogProjection* question_projection() const; + GameEndTaxDialog::Button question_button(int x, int y) const; + std::optional answer_question(GameEndTaxDialog::Button); + void prepare_calendar(); + void text(Image&, int x, int y, std::string_view value, uint8_t color, int max_width) const; + Image render_modal(Image image, std::string_view heading, std::string_view detail, + std::string_view left, std::string_view right) const; + std::optional book_request(int season_day, int approving_manager, int consenting_manager); +}; + +} // namespace bmh::ui diff --git a/src/ui/friendly_match_tests.cpp b/src/ui/friendly_match_tests.cpp new file mode 100644 index 0000000..5199894 --- /dev/null +++ b/src/ui/friendly_match_tests.cpp @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/friendly_match.hpp" + +#include +#include +#include + +#include "ui/setup.hpp" +#include "ui/desk_state.hpp" +#include "game/schedule.hpp" +#include "game/state.hpp" +#include "game/messages.hpp" + +using namespace bmh::ui; + +namespace { +void check(bool ok, const char* message) { + if (!ok) throw std::runtime_error(message); +} + +FriendlyMatchState fixture(const std::filesystem::path& data) { + FriendlyMatchState state; + state.revision = 7; + state.manager_slot = 0; + state.runtime_team = 0; + state.current_day = 40; + state.planner_count = 4; + const auto exe = bmh::load_le(asset_path(data, "BMH.exe")); + // legacy routine: word zero is the first July Wednesday, not necessarily July 1. + uint32_t display_start = 1300; + while (desk_date(display_start, exe).month != 7 || desk_date(display_start, exe).day != 1) + ++display_start; + state.season_start_counter = display_start; + while (desk_date(state.season_start_counter, exe).weekday != 2) ++state.season_start_counter; + state.calendar.season_start_counter = display_start; + state.calendar.leading_days = int(state.season_start_counter - display_start); + state.calendar.current_day = state.current_day + state.calendar.leading_days; + for (int offset = 0; offset <= 366; ++offset) { + const auto date = desk_date(display_start + uint32_t(offset), exe); + if (offset && date.month == 7 && date.day == 1) break; + CalendarDayProjection day; + day.season_day = offset - state.calendar.leading_days; + day.day_counter = display_start + uint32_t(offset); + day.date = date; + day.current_day = offset == state.calendar.current_day; + state.calendar.days.push_back(day); + } + state.mode_three = true; + state.manager_name = "Tester"; + TaxDialogProjection venue; + venue.kind=TaxDialogKind::question;venue.source_flags=0x606; + venue.manager_name="Tester"; + venue.body=bmh::load_textd(asset_path(data,"TEXTD.BLK"))[bmh::text_id(::bmh::layout::Controller_ClubFriendlyState_TextPointer)]; + state.venue_question=venue; + int runtime = 0; + for (int league = 0; league < 9; ++league) { + auto& table = state.leagues[size_t(league)]; + table.manager_slot = 0; + table.league_id = league; + table.league_name = "Liga"; + table.header_text = "Tabelle"; + for (int team = 0; team < bmh::kLeagueSizes[league]; ++team) { + LeagueTableRow row; + row.rank = team + 1; + row.runtime_team_id = runtime++; + row.club_identity_key = row.runtime_team_id; + row.name = "Verein " + std::to_string(team); + row.name_color = 0x5f; + table.rows.push_back(std::move(row)); + } + } + return state; +} + +FriendlyQuoteProjection quote_for(const FriendlyMatchRequest& request, int planner_count, + const std::filesystem::path& data) { + FriendlyQuoteProjection quote; + quote.request_id = request.request_id; + quote.revision = request.revision; + quote.manager_slot = request.manager_slot; + quote.runtime_team = request.runtime_team; + quote.opponent = request.opponent; + quote.payer_manager = 0; + quote.home_team = request.runtime_team; + quote.away_team = request.opponent; + quote.cost = 32000; + quote.planner_count = planner_count; + quote.manager_home = request.manager_home; + const auto texts=bmh::load_textd(asset_path(data,"TEXTD.BLK")); + TaxDialogProjection cost; + cost.kind=TaxDialogKind::question;cost.source_flags=0x404;cost.manager_name="Tester"; + cost.body=texts[bmh::text_id(::bmh::layout::Controller_FormatError_TextPointer2)]+bmh::format_number(bmh::GameState{},quote.cost,0x101); + quote.cost_question=cost; + cost.source_flags=0x303;cost.source_manager_flags=1;cost.manager_name="Testgegner"; + cost.body=texts[bmh::text_id(::bmh::layout::Controller_FormatError_TextPointer3)];quote.owner_question=cost; + for (int day = 0; day <= 365; ++day) + quote.dates.push_back(FriendlyDateOption{day, + day <= 40 ? FriendlyDateMark::unavailable : FriendlyDateMark::available}); + return quote; +} +} + +int main(int argc, char** argv) { + try { + if (argc != 2) throw std::runtime_error("usage: ui_friendly_match_tests "); + const std::filesystem::path data(argv[1]); + auto original = fixture(data); + FriendlyMatchScreen screen(data, original); + check(screen.stage() == FriendlyStage::opponents, "club Mode III can enter the opponent view"); + const auto exe = bmh::load_le(asset_path(data, "BMH.exe")); + const auto date_font = bmh::load_font(asset_path(data / "F", "BMH3.FNT")); + for (int day = 1; day <= 31; ++day) + check(date_font.text_width(std::to_string(day)) <= 10, + "the Original small font renders every full calendar day in one cell"); + bool checked_week_rollover = false; + bool checked_saturday_month_start = false; + for (int day = 0; day <= 365; ++day) { + const auto date = desk_date(original.season_start_counter + uint32_t(day), exe); + const auto cell = friendly_calendar_cell(exe, original.season_start_counter, day); + const int month_slot = (date.month + 5) % 12; + const int month_x = 28 + (month_slot % 4) * 70; + const int month_y = 29 + (month_slot / 4) * 70; + if (date.day == 5 && date.weekday == 0) { + check(cell.x == month_x + 12 && cell.y == month_y, + "Source Monday on day five occupies the second week column"); + checked_week_rollover = true; + } + if (date.day == 1 && date.weekday == 5) { + check(cell.x == month_x && cell.y == month_y + 40, + "Source Saturday month start remains in the first week column"); + checked_saturday_month_start = true; + } + } + check(checked_week_rollover && checked_saturday_month_start, + "calendar geometry covers weekday offsets at two month starts"); + const auto initial_json = screen.state_json(); + const auto texts=bmh::load_textd(asset_path(data,"TEXTD.BLK")); + check(texts[bmh::text_id(::bmh::layout::LeagueTable_Glyph_TextPointer2)]==" " && texts[bmh::text_id(::bmh::layout::FixtureFriendlySecondBlankLabel)]==" ", + "German Original mode2 preserves the Source space-only closing footer labels"); + FriendlyMatchScreen full_row(data, original); + check(!full_row.click(300,28) && full_row.stage()==FriendlyStage::opponents && + !full_row.click(300,36) && full_row.stage()==FriendlyStage::venue && + full_row.selected_opponent()==1, + "Source row hit accepts the points/right side and exact row boundaries"); + FriendlyMatchScreen cancelled_footer(data, original); + check(cancelled_footer.pointer_down(162,207) && + cancelled_footer.render().pixels!=screen.render().pixels && + cancelled_footer.move(0,0) && !cancelled_footer.click(162,207) && + !cancelled_footer.close_requested(), + "leaving a held blank closing button cancels its later release"); + for (const int y : {207,220}) { + FriendlyMatchScreen footer(data, original); + check(footer.pointer_down(162,y) && !footer.close_requested() && + !footer.click(162,y) && footer.close_requested(), + "both Source mode2 footer buttons close on their matching left release"); + } + check(!screen.key("RIGHT") && screen.selected_league() == 1 && + !screen.key("LEFT") && screen.selected_league() == 0, + "local league-key navigation emits no engine action"); + check(!screen.click(40, 38), "opponent selection opens the venue prompt without an engine request"); + check(screen.selected_opponent() == 1 && screen.stage() == FriendlyStage::venue, + "the selected opponent is an owned runtime-team identity"); + check(!screen.click(80, 180) && screen.stage() == FriendlyStage::venue, + "clicks outside the visible venue buttons do not choose a venue"); + const auto unpressed_question=screen.render(); + check(!screen.click(99,171,true) && !screen.key("ESC") && + !screen.close_requested() && screen.stage()==FriendlyStage::venue && + screen.render().pixels==unpressed_question.pixels, + "ordinary right event and Escape cannot answer or close the Source venue question"); + check(screen.pointer_down(99,171) && screen.render().pixels!=unpressed_question.pixels, + "Source question button has its actual KB0 pressed frame before release"); + const auto pressed_question=screen.render(); + check(!screen.click(99,171,true) && !screen.key("ESC") && + screen.render().pixels==pressed_question.pixels && !screen.close_requested(), + "unrelated right/key events leave the held Source button owned by its left release"); + check(screen.move(0,0) && screen.render().pixels==unpressed_question.pixels && + !screen.click(99,171) && screen.stage()==FriendlyStage::venue, + "leaving a held Source button restores it and the later UP cannot choose a venue"); + check(!screen.click(80,150) && screen.stage()==FriendlyStage::venue, + "former synthetic question coordinates no longer answer the Original buttons"); + const auto quote_request = screen.click(99, 171); + check(quote_request && quote_request->kind == FriendlyRequestKind::quote && + quote_request->request_id == 1 && quote_request->revision == 7 && + quote_request->planner_count == 4 && quote_request->manager_home, + "venue selection sends an identity- and revision-bound read-only quote request"); + check(!screen.click(99, 171), "a repeated quote click while pending cannot emit another request"); + check(screen.acknowledge_quote(quote_for(*quote_request, 5, data)) == false, + "quote is rejected if the original planner counter changed"); + auto stale_revision_quote = quote_for(*quote_request, 4, data); + stale_revision_quote.revision++; + check(!screen.acknowledge_quote(stale_revision_quote), "quote from another desk revision is rejected"); + check(screen.acknowledge_quote(quote_for(*quote_request, 4, data)), "matching quote opens fee confirmation"); + check(screen.stage() == FriendlyStage::cost_confirmation, "home fee is shown before date choice"); + check(!screen.click(213,171,true) && !screen.key("ESC") && + screen.stage()==FriendlyStage::cost_confirmation && !screen.close_requested(), + "right event over No and Escape do not decline the Source fee question"); + check(!screen.click(10, 145) && screen.stage() == FriendlyStage::cost_confirmation, + "clicks outside the visible fee buttons do not accept or decline"); + check(!screen.click(99, 171), "accepting a quoted fee does not book or mutate state"); + check(screen.stage() == FriendlyStage::calendar, "accepted home fee opens the calendar"); + auto calendar_pixels = screen.render(); + check(calendar_pixels.width == 320 && calendar_pixels.height == 240, + "full calendar renders with the Original small font and one-/two-digit dates"); + auto original_calendar = bmh::load_vga(asset_path(data / "KB", "55.VGA")); + check(calendar_pixels.at(0, 18) == original_calendar.at(0, 0) && + calendar_pixels.at(319, 226) == original_calendar.at(319, 208), + "friendly calendar uses the Original opaque KB55 crop at y18, not a black custom view"); + for (const auto& date : original.calendar.days) if (date.season_day < 0) { + const auto cell = calendar_cell(date); + check(!screen.click(cell.x + 1, cell.y + 1) && screen.stage() == FriendlyStage::calendar, + "July dates before Source word zero cannot book native day zero"); + } + const auto future_cell = friendly_calendar_cell(exe, original.season_start_counter, 41); + check(screen.move(future_cell.x + 1, future_cell.y + 1), "Source day cell accepts pointer hover"); + auto hovered = screen.render(); + check(hovered.at(future_cell.x, future_cell.y + 1) == 0x75, + "available friendly day has Source inclusive light hover outline"); + check(screen.move(0, 0) && screen.render().pixels == calendar_pixels.pixels, + "leaving day cells restores the initial calendar and empty footer"); + const auto blocked_cell = friendly_calendar_cell(bmh::load_le(asset_path(data, "BMH.exe")), original.season_start_counter, 40); + check(!screen.click(blocked_cell.x + 1, blocked_cell.y + 1) && + screen.stage() == FriendlyStage::calendar, + "a date absent from the approved calendar projection cannot be requested"); + const auto last_date = desk_date(original.season_start_counter + 365, exe); + if ((last_date.month + 5) % 12 == 0 && last_date.day == 1) { + const auto year_boundary_cell = friendly_calendar_cell(exe, original.season_start_counter, 365); + check(!screen.click(year_boundary_cell.x + 1, year_boundary_cell.y + 1) && + screen.stage() == FriendlyStage::calendar, + "the next July 1 boundary is never offered as the last date of this season"); + } + auto day_cell = friendly_calendar_cell(bmh::load_le(asset_path(data, "BMH.exe")), original.season_start_counter, 41); + auto book_request = screen.click(day_cell.x + 1, day_cell.y + 1); + check(book_request && book_request->kind == FriendlyRequestKind::book && + book_request->season_day == 41 && book_request->planner_count == 4 && + book_request->quote_id == quote_request->request_id && + book_request->request_id != quote_request->request_id && book_request->cost == 32000, + "selecting a permitted date emits one booking request with the frozen quote"); + FriendlyBookingAck rejected; + rejected.request_id = book_request->request_id; + rejected.quote_id = book_request->quote_id; + rejected.revision = original.revision; + rejected.manager_slot = 0; + rejected.runtime_team = 0; + rejected.opponent = 1; + rejected.opponent_manager = -1; + rejected.season_day = 41; + rejected.payer_manager = 0; + rejected.home_team = 0; + rejected.away_team = 1; + rejected.cost = 32000; + rejected.planner_count = 4; + auto forged_reject = rejected; + forged_reject.request_id++; + check(!screen.acknowledge_booking(forged_reject), "a booking ACK with a different request ID is inert"); + check(screen.acknowledge_booking(rejected), "a rejected booking returns to the calendar without revision"); + check(screen.stage() == FriendlyStage::calendar && screen.state_json().find("\"revision\":7") != std::string::npos, + "rejection keeps the authoritative revision unchanged"); + day_cell = friendly_calendar_cell(bmh::load_le(asset_path(data, "BMH.exe")), original.season_start_counter, 41); + book_request = screen.click(day_cell.x + 1, day_cell.y + 1); + check(book_request.has_value(), "the user can retry after an inert rejection"); + FriendlyBookingAck accepted = rejected; + accepted.accepted = true; + accepted.revision = 8; + accepted.planner_count = 6; + accepted.request_id = book_request->request_id; + accepted.quote_id = book_request->quote_id; + accepted.accepted = true; + check(screen.acknowledge_booking(accepted), "successful booking ACK advances revision and planner counter"); + check(screen.stage() == FriendlyStage::complete && screen.close_requested() == false && + screen.state_json().find("\"revision\":8") != std::string::npos, + "only the authoritative success ACK completes the interaction"); + check(!screen.acknowledge_booking(accepted), "duplicate booking ACK is inert after completion"); + check(original.revision == 7 && original.planner_count == 4 && + original.leagues[0].rows.size() == size_t(bmh::kLeagueSizes[0]), + "screen interaction leaves its source projection unchanged"); + check(initial_json.find("friendly_match") != std::string::npos, + "screen exposes machine-readable state for app routing"); + + auto decline_state = fixture(data); + FriendlyMatchScreen decline_screen(data, decline_state); + decline_screen.click(40, 38); + const auto decline_quote_request = decline_screen.click(99, 171); + check(decline_screen.acknowledge_quote(quote_for(*decline_quote_request, 4, data)), + "decline fixture receives the same read-only quote"); + check(!decline_screen.click(213, 171) && decline_screen.close_requested() && + decline_state.revision == 7 && decline_state.planner_count == 4, + "Source declined cost ends the caller without booking or projection mutation"); + + auto shared_home = fixture(data); + FriendlyMatchScreen shared_screen(data, shared_home); + shared_screen.click(40, 38); + const auto shared_quote_request = shared_screen.click(99, 171); + auto shared_quote = quote_for(*shared_quote_request, 4, data); + shared_quote.opponent_manager = 1; + check(shared_screen.acknowledge_quote(shared_quote), "human opponent identity is bound to the quote"); + shared_screen.click(99, 171); + const auto consent_before=shared_screen.state_json(); + check(!shared_screen.click(213,171,true) && !shared_screen.key("ESC") && + !shared_screen.close_requested() && shared_screen.state_json()==consent_before, + "other-manager consent cannot be bypassed or declined by right event or Escape"); + check(shared_screen.stage()==FriendlyStage::owner_approval && + shared_screen.state_json().find("selected_day")==std::string::npos, + "Source asks other-manager consent before selecting any calendar date"); + const auto shared_day = friendly_calendar_cell(bmh::load_le(asset_path(data, "BMH.exe")), original.season_start_counter, 41); + check(!shared_screen.click(shared_day.x + 1, shared_day.y + 1) && + shared_screen.stage() == FriendlyStage::owner_approval, + "calendar coordinates cannot bypass pending Source consent"); + check(!shared_screen.click(99,171) && shared_screen.stage()==FriendlyStage::calendar, + "consenting manager opens calendar without booking a previously selected date"); + const auto consented = shared_screen.click(shared_day.x+1,shared_day.y+1); + check(consented && consented->accept_cost && consented->accept_opponent && + consented->approving_manager == 0 && consented->consenting_manager == 1, + "separate home payer and opponent consent are both carried explicitly"); + + FriendlyMatchScreen away_screen(data,fixture(data)); + away_screen.click(40,38); + const auto away_request=away_screen.click(213,171); + check(away_request&&!away_request->manager_home,"Source venue No means away"); + auto away_quote=quote_for(*away_request,4,data); + away_quote.opponent_manager=1;away_quote.payer_manager=1; + away_quote.home_team=1;away_quote.away_team=0; + check(away_screen.acknowledge_quote(away_quote)&&away_screen.stage()==FriendlyStage::owner_approval, + "away quote asks the paying manager before opening its calendar"); + check(!away_screen.click(99,171)&&away_screen.stage()==FriendlyStage::calendar, + "payer consent opens calendar without emitting a book command"); + const auto away_book=away_screen.click(shared_day.x+1,shared_day.y+1); + check(away_book&&away_book->accept_cost&&away_book->accept_opponent&& + away_book->approving_manager==1&&away_book->consenting_manager==1, + "later away-date request carries its prior bound payer and opponent consent"); + + FriendlyMatchScreen denied_screen(data,fixture(data)); + denied_screen.click(40,38);const auto denied_request=denied_screen.click(99,171); + auto denied_quote=quote_for(*denied_request,4,data);denied_quote.opponent_manager=1; + check(denied_screen.acknowledge_quote(denied_quote),"denial receives an owned human-opponent quote"); + denied_screen.click(99,171); + check(!denied_screen.click(213,171)&&denied_screen.close_requested(), + "other-manager No ends Source caller without date choice or booking"); + + FriendlyMatchScreen wrong_menu(data, fixture(data), 23); + check(wrong_menu.stage() == FriendlyStage::unavailable, + "separate Desk kind 23 view is not routed to the club booking workflow"); + auto national = fixture(data); + national.national_team = true; + national.runtime_team = bmh::kNoTeam; + FriendlyMatchScreen unavailable(data, national); + check(unavailable.stage() == FriendlyStage::unavailable && !unavailable.close_requested() && + !unavailable.click(80, 150) && unavailable.close_requested(), + "national-team booking is unavailable and its visible return button works"); + + auto cancelled = fixture(data); + FriendlyMatchScreen cancel_screen(data, cancelled); + check(!cancel_screen.key("ESC") && cancel_screen.close_requested(), + "ESC cancels the local view without issuing an engine request"); + + FriendlyMatchScreen timed_venue(data,original); + (void)timed_venue.click(40,38);(void)timed_venue.pointer_down(99,171); + check(timed_venue.question_held() && timed_venue.question_release_pending() && + !timed_venue.move(100,171) && timed_venue.question_held(), + "moving within a valid question widget retains Source release ownership"); + auto timed_away_request=timed_venue.expire_question(); + check(timed_away_request && !timed_away_request->manager_home && timed_away_request->kind==FriendlyRequestKind::quote && + timed_venue.stage()==FriendlyStage::quote_pending && !timed_venue.active_question() && + !timed_venue.expire_question(),"semantic expiry answers venue No once, preserving quote ownership"); + FriendlyMatchScreen timed_fee(data,original); + (void)timed_fee.click(40,38);const auto fee_request=timed_fee.click(99,171); + check(fee_request && timed_fee.acknowledge_quote(quote_for(*fee_request,original.planner_count,data)), + "fee expiry starts with an accepted real-shaped quote"); + (void)timed_fee.pointer_down(99,171);(void)timed_fee.move(0,0); + check(!timed_fee.question_held() && timed_fee.question_release_pending() && + !timed_fee.expire_question() && timed_fee.close_requested(), + "leaving the widget releases its answer but retains the old physical UP for the caller"); + std::cout << "friendly match UI state and ACK checks passed\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << "friendly match UI test failure: " << e.what() << '\n'; + return 1; + } +} diff --git a/src/ui/game_end.cpp b/src/ui/game_end.cpp new file mode 100644 index 0000000..e13ad5c --- /dev/null +++ b/src/ui/game_end.cpp @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "formats/executable_layout.hpp" +#include "ui/game_end.hpp" + +#include +#include +#include +#include + +#include "formats/font.hpp" +#include "formats/le.hpp" +#include "ui/manager.hpp" +#include "ui/setup.hpp" +#include "ui/sprite_font.hpp" + +namespace bmh::ui { +namespace { +void copy(Image& d,const Image& s,int sx,int sy,int x,int y,int w,int h,bool transparent=false) { + for(int yy=0;yy=0&&y+yy>=0&&x+xx=0&&top+f.height<=im.height) f.draw(im,x,top,bytes,c); +} +void source_text(Image& out,const Font& f,const LeImage& exe,int x,int baseline, + std::string_view bytes,uint8_t color,bool gradient) { + const int top=baseline-f.baseline; + if(top<0||top+f.height>out.height) return; + if(!gradient||exe.u8(::bmh::layout::TextGradientMode)!=2||color==0x40){f.draw(out,x,top,bytes,color);return;} + unsigned slot=0;while(slot<32&&exe.u8(::bmh::layout::Advertising_Text_RuntimeField2+slot)!=color)++slot; + if(slot==32){f.draw(out,x,top,bytes,color);return;} + Image mask(std::max(1,f.text_width(bytes)),f.height,0); + f.draw(mask,0,0,bytes,1); + for(int y=0;y=0&&x+xx out.width || baseline + 2 > out.height) return; + raw_text(out,f,x+2,baseline+2,bytes,0x40); + source_text(out,f,exe,x,baseline,bytes,color,gradient); +} +class SourceHyphenator { +public: + SourceHyphenator(const Font& font,const LeImage& exe):font_(font),exe_(exe),vowels_(exe.cstring(::bmh::layout::GameEnd_SourceHyphenator_ExecutableField)) { + for(int i=0;i<30;++i) clusters_.push_back(exe_.cstring(exe_.u32(::bmh::layout::GameEnd_SourceHyphenator_RuntimeField+uint32_t(i)*4))); + } + std::vector wrap(std::string_view text,int max_width,bool justify=false) const { + if(max_width<=4)throw FormatError("Source paragraph: invalid width"); + std::vector lines;std::string line;std::vector ends; + size_t at=0; + while(atmax_width) { + // FindBreak measures strlen(pending)+1, including glyph0. + const int cut=find_break(word,max_width-4, + font_.text_width(line)+font_.glyph(0).advance); + if(cut>=0) { + if(!line.empty()){line+=' ';ends.push_back(line.size()-1);} + std::string head=word.substr(0,size_t(cut+1)); + if(head.back()=='c'&&word[size_t(cut+1)]=='k')head.back()='k'; + line+=head;line+=exe_.cstring(::bmh::layout::Fltd_Layout_ExecutableField6); + word.erase(0,size_t(cut+1)); + } else if(line.empty()) { + // DOS cannot advance on an oversized indivisible word. + // Keep it intact for the caller's clipping, never hang or + // invent a syllable. Ordinary Source words take the path above. + line=word;word.clear(); + } + if(!ends.empty())ends.pop_back(); + size_t gap=0; + while(justify&&!ends.empty()&&font_.text_width(line)=ends.size())gap=0; + } + lines.push_back(line);line.clear();ends.clear();candidate=word; + } + if(!line.empty())line+=' '; + line+=word;ends.push_back(line.size()); + if(at clusters_; + bool vowel(char c) const { return vowels_.find(c)!=std::string::npos; } + static char fold(char c) { const unsigned char u=static_cast(c);return u>='A'&&u<='Z'?char(u+32):c; } + int find_break(const std::string& word,int max_prefix_width,int preceding) const { + int limit=int(word.size())-1; + for(int cut=limit;cut>=0;--cut) { + // Draw2 retains the previous over-width candidate as the + // right-section limit; this is not always the end of the word. + if(valid_break(word,cut,limit)) { + const auto prefix=std::string_view(word).substr(0,size_t(cut+1)); + if(preceding+font_.text_width(prefix)=0&&!vowel(word[size_t(start)]);--start) { + for(const auto& cluster:clusters_) { + if(cluster.empty()||start+int(cluster.size())<=cut+1)continue; + if(start+int(cluster.size())>int(word.size()))continue; + bool equal=true; + for(size_t j=0;j 0; at -= 3) digits.insert(size_t(at), "."); + const unsigned separators = (count - 1) / 3; + const unsigned reserved = minimum_digits > 3 ? (minimum_digits - 4) / 3 + 1 : 0; + std::string out = negative ? "-" : ""; + if (reserved > separators) out.append(reserved - separators, ' '); + if (minimum_digits > count + unsigned(negative)) out.append(minimum_digits - count - unsigned(negative), '%'); + return out + digits; +} +void button(Image& o,const Image& a,const SpriteFont& sf,const LeImage& exe,int x,int y,int w, + std::string_view label,bool selected=false){ + if(selected){const auto under=o.at(x,y+10);fill(o,x,y,w+1,2,under);fill(o,x,y,2,11,under);x+=2;y+=2;} + else {fill(o,x+2,y+10,w,2,0x40);fill(o,x+w,y+2,2,10,0x40);} + const int sy=selected?44:74; + copy(o,a,24,sy,x,y,31,10);int used=31; + while(w-used>20){int n=std::min(8,w-used-20);copy(o,a,24,sy+10,x+used,y,n,10);used+=n;} + copy(o,a,45-(w-used),sy+20,x+used,y,w-used,10); + sf.draw(o,x+w/2-sf.text_width(label)/2,y+7,label,exe.u8(::bmh::layout::Advertising_Button_RuntimeField + int(selected))); +} +std::string_view text_at(const TextDb& texts,uint32_t address) { + constexpr uint32_t base=::bmh::layout::TextPointerTable; + if(address wrap_source_text(const Font& font,const LeImage& exe, + std::string_view text,int max_width,bool justify) { + return SourceHyphenator(font,exe).wrap(text,max_width,justify); +} +std::vector wrap_source_text(const std::filesystem::path& data,std::string_view text,int max_width) { + const auto font=load_font(asset_path(data/"F","BMH3.FNT")); + const auto exe=load_le(asset_path(data,"BMH.exe")); + return wrap_source_text(font,exe,text,max_width); +} +struct GameEndHighscoreScreen::FontData { Font small; LeImage exe; SpriteFont sprite; explicit FontData(const std::filesystem::path& p):small(load_font(asset_path(p/"F","BMH3.FNT"))),exe(load_le(asset_path(p,"BMH.exe"))),sprite(p){} }; +GameEndHighscoreScreen::GameEndHighscoreScreen(const std::filesystem::path& data,HighscoreProjection p,GameEndRenderOptions options) + : projection_(std::move(p)),options_(options),background_(load_vga(asset_path(data/"KB","129.VGA"))), + logo_(load_vga(asset_path(data/"KB","51.VGA"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))),font_(std::make_shared(data)) {} +Image GameEndHighscoreScreen::render() const { + Image out=source_base(background_,options_.plain_background,true); + if(logo_.width>=112&&logo_.height>=74){fill(out,102,99,112,2,0x40);fill(out,212,27,2,74,0x40);copy(out,logo_,0,0,100,25,112,74);} + if(!projection_.ranked)return out; + const auto& heading=texts_[893]; + font_->sprite.draw(out,SpriteFont::centered_title_x(font_->sprite.text_width(original_to_utf8(heading))),13,original_to_utf8(heading),5); + for(size_t i=0;ismall,font_->exe,33,baseline,left,0x5f,options_.gradient_text); + source_text_shadow(out,font_->small,font_->exe,125,baseline,r.club_name,0x5f,options_.gradient_text); + source_text_shadow(out,font_->small,font_->exe,230,baseline,right,0x5f,options_.gradient_text); + } + return out; +} +struct GameEndFinalScreen::FontData { Font final_font; explicit FontData(const std::filesystem::path& p):final_font(load_font(asset_path(p/"F","BMH2.FNT"))){} }; +GameEndFinalScreen::GameEndFinalScreen(const std::filesystem::path& data,GameEndRenderOptions options) + : background_(load_vga(asset_path(data/"KB","129.VGA"))),options_(options),texts_(load_textd(asset_path(data,"TEXTD.BLK"))),font_(std::make_shared(data)) {} +Image GameEndFinalScreen::render() const { + Image out=source_base(background_,options_.plain_background,false); + for(const auto& [id,y]:{std::pair{1172,100},std::pair{1173,140}}){ + const auto& text=texts_[id];const int w=font_->final_font.text_width(text); + raw_text(out,font_->final_font,8+(311-w)/2,y,text,0x5f); + } + return out; +} +struct GameEndTaxDialog::FontData { Font small,large;LeImage exe;SpriteFont sprite;explicit FontData(const std::filesystem::path& p):small(load_font(asset_path(p/"F","BMH3.FNT"))),large(load_font(asset_path(p/"F","BMH2.FNT"))),exe(load_le(asset_path(p,"BMH.exe"))),sprite(p){} }; +struct ProgramErrorScreen::FontData { + Font font,header; LeImage exe; + explicit FontData(const std::filesystem::path& p) + : font(load_font(asset_path(p/"F","BMH3.FNT"))), + header(load_font(asset_path(p/"F","BMH2.FNT"))), exe(load_le(asset_path(p,"BMH.exe"))) {} +}; +ProgramErrorScreen::ProgramErrorScreen(const std::filesystem::path& data,uint16_t code,GameEndRenderOptions options) + : code_(code),options_(options),texts_(load_textd(asset_path(data,"TEXTD.BLK"))),font_(std::make_shared(data)) {} +Image ProgramErrorScreen::render() const { + Image out(320,240,0); + const uint8_t color=code_<150 && (code_<91 || code_>99)?0x75:0xf7; + const auto label=[&](std::string_view text,int baseline){ + source_text(out,font_->font,font_->exe,159-font_->font.text_width(text)/2, + baseline,text,color,options_.gradient_text); + }; + // TextAt selects font2 for the heading. DrawnFirstBy resets it to font3 + // after its first label; param7=-1 gives no shadow, header no gradient. + const auto heading=text_at(texts_,::bmh::layout::GameEnd_Out_TextPointer); + raw_text(out,font_->header,159-font_->header.text_width(heading)/2,21,heading,color); + for(int i=0;i<5;++i){ + std::string line(text_at(texts_,::bmh::layout::GameEnd_Line_TextPointer+uint32_t(i)*4)); + if(i==0) { + const auto number=std::to_string(code_); + // Replace(...,0x45) uses Source's '%' padding glyph, whose + // blank advance differs from an ordinary space in BMH3.FNT. + line.replace(14,5,std::string(5-number.size(),'%')+number); + } + label(std::move(line),60+i*10); + } + for(int n=0;n<3;++n){ + fill(out,n,n,320-2*n,1,color);fill(out,n,33-n,320-2*n,1,color); + fill(out,n,n,1,34-2*n,color);fill(out,319-n,n,1,34-2*n,color); + } + return out; +} +GameEndTaxDialog::GameEndTaxDialog(const std::filesystem::path& data,TaxDialogProjection p,GameEndRenderOptions options,std::optional restored_backdrop) + : projection_(std::move(p)),options_(options),restored_backdrop_(std::move(restored_backdrop)),background_(load_vga(asset_path(data/"KB","129.VGA"))),widgets_(load_vga(asset_path(data/"KB","0.VGA"))), + faces_(load_vga(asset_path(data/"KB","26.VGA"))),texts_(load_textd(asset_path(data,"TEXTD.BLK"))),font_(std::make_shared(data)) { + if(!projection_.badge_fallback) + badge_=load_vga(asset_path(data/"W",std::to_string(std::max(0,projection_.badge_sprite)>>3)+".VGA")); +} +Image GameEndTaxDialog::backdrop() const { + if(projection_.compact_dialog_frame)return Image(320,240,0); + if(restored_backdrop_&&restored_backdrop_->width==320&&restored_backdrop_->height==240)return *restored_backdrop_; + return source_base(background_,options_.plain_background,false); +} +Image GameEndTaxDialog::render(std::optional