Restore direct-installation Classic baseline for OpenBMH 1.0 (by Codex)

This commit is contained in:
Codex committed 2026-10-30 14:19:25 +01:00
1 parent c8f04d0099
commit c3704878d6
255 files changed
+311 -21131

No files matched your search

+31 -246
View File
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "app/career_session.hpp"
#include "content/save.hpp"
#include "import/save.hpp"
#include <stdexcept>
#include <system_error>
@@ -422,14 +420,16 @@ void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Datab
if (!unsupported_continuation.empty()) return;
std::vector<int> active_leagues;
// Expand the selected edition's groups. Only the German third divisions
// share bit 2; the English divisions each have their own calendar group.
// Stale descriptors beyond the active group count are ignored.
// 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 = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; ++league)
for (int league = first_league[k]; league < first_league[k] + league_count[k]; ++league)
active_leagues.push_back(league);
}
if (active_leagues.size() > 6)
@@ -539,7 +539,12 @@ static void install_league_sizes(const LeImage& exe) {
kNewcomerFirst = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField);
kNewcomerCount = exe.u16(::bmh::layout::CareerSession_InstallLeagueSizes_RuntimeField6);
// EXE strings the engine posts (messages.hpp)
install_message_texts(exe);
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)
@@ -555,11 +560,6 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
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"));
if (const auto resource = content::find(data)) {
g_.display_start_year = resource->content->start_year;
content::set_display_start_year(data, g_.display_start_year);
exe_.set_display_start_year(g_.display_start_year);
}
g_.texts = &texts_;
g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText
configure_training_camp_data(g_, exe_);
@@ -567,18 +567,14 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
g_.credit_rate_table_available = true;
install_default_hooks();
if (content::find(data))
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
write_desk_autosave(state, random);
};
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, bool importing_legacy)
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_);
@@ -588,62 +584,15 @@ CareerSession::CareerSession(const std::filesystem::path &data, uint32_t watcom_
? TransferAllocatorContext::zero : TransferAllocatorContext::blocked;
session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed);
initialize_club_modal_runtime();
bool original_english_save = false;
std::optional<content::SavedCareer> native;
if (const auto resource = content::find(data); resource && !importing_legacy) {
if (content::key(save_path.extension()) != ".obs")
throw FormatError("0.2 loads native OBS saves; use Add to migrate legacy games");
native = content::load_career(save_path, *resource->content);
g_ = std::move(native->state);
rand_ = native->random;
game_ = native->game;
} else {
const Savegame file = load_savegame(save_path);
original_english_save = file.version == "V2.20";
if (!file.checksum_ok ||
(file.version != "V2.24" && !(importing_legacy && kEnglishCompetitions && original_english_save)))
throw FormatError("savegame: unsupported or damaged FBM");
const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)};
const auto stream = original_english_save ? obw::normalize_english_save(file, counts) : file.stream;
const SaveState save(stream, counts);
const auto manager_count = save.data(::bmh::layout::ManagerCount)[0];
if (manager_count < 1 || manager_count > 4)
throw FormatError("Invalid legacy manager count");
if (importing_legacy) {
size_t english_blocks = 0;
for (const auto &[address, size] : kEnglishCompetitionBlocks)
for (const auto &block : save.extension())
if (block.address == address && block.bytes.size() == size)
++english_blocks;
if ((kEnglishCompetitions && english_blocks != std::size(kEnglishCompetitionBlocks)) ||
(!kEnglishCompetitions && english_blocks != 0))
throw FormatError(
"Spielstand und Mod-Ausgabe passen nicht zusammen oder englische Pokaldaten fehlen.");
}
g_ = GameState::from_save(save, counts);
if (importing_legacy && file.plain_header.size() >= 11) {
const std::string year(file.plain_header.begin() + 7, file.plain_header.begin() + 11);
if (std::all_of(year.begin(), year.end(), [](unsigned char c) { return std::isdigit(c); })) {
const int elapsed = ui::desk_date(g_.date, exe_).year - exe_.display_start_year();
const int origin = std::stoi(year) - elapsed;
if (origin >= 1900 && origin <= 9998)
g_.display_start_year = origin;
}
}
}
if (content::find(data)) {
content::set_display_start_year(data, g_.display_start_year);
exe_.set_display_start_year(g_.display_start_year);
}
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.
if (!native) {
g_.autosave_months = 0;
g_.autosave_month = month_code(g_.date);
}
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).
@@ -655,55 +604,10 @@ CareerSession::CareerSession(const std::filesystem::path &data, uint32_t watcom_
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
g_.credit_rate_table_available = true;
install_default_hooks();
if (content::find(data))
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
write_desk_autosave(state, random);
};
if (!native)
national_coach_after_load(
g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again)
if (!native && g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField))
game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)));
if (native) {
content::restore_driver(turn_driver_, native->driver);
restore_native_session_context(native->session);
turn_driver_.session_id = session_id_;
turn_driver_.revision = 1;
exe_.set_display_start_year(g_.display_start_year);
} else if (original_english_save &&
!g_.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) {
// V2.20 never stored transient match descriptors. Like its original loader,
// rebuild the current groups without replaying daily/financial progression
// or shuffling the saved manager order.
const int day = g_.season_day();
if (day < 0 || day >= 365)
throw FormatError("V2.20 calendar day is invalid");
const auto entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(day) * 2);
const auto competitions = g_.memory.u32(::bmh::layout::SavedCompetition);
std::vector<uint8_t> referees = db_.raw_referee_properties;
for (auto &referee : referees)
referee &= 0x7f;
MatchdayContext context;
context.month = month_code(g_.date);
context.season_day = day;
context.weekday = ui::desk_date(g_.date, exe_).weekday;
context.referees = &referees;
MinuteReport report;
auto groups = setup_matchday(g_, competitions, context, game_, rand_, report);
if (report.unsupported)
throw FormatError("V2.20 continuation: " + report.reason);
std::string error;
if (!begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties,
session_id_, 1, error))
throw FormatError(error);
turn_driver_.referees = std::move(referees);
turn_driver_.loaded_matchday_resume = true;
} else
restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_);
if (importing_legacy && !saved_turn_error_.empty())
throw FormatError(saved_turn_error_);
if (!native)
capture_source_desk_callargs();
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); }
@@ -4225,7 +4129,6 @@ bool CareerSession::finish(ui::CareerInitializationResult& result, std::string&
for (size_t m = 0; m < managers_.size(); ++m)
managers_[m].runtime_club = g_.manager_teams.at(m);
result.managers = managers_;
flush_native_autosave();
return true;
}
@@ -4432,7 +4335,6 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request
return id < names.size() ? names[id] : std::string();
}, exe_, g_);
}
flush_native_autosave();
return result;
}
@@ -4898,10 +4800,7 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
std::string extension=request.path.extension().string();
std::transform(extension.begin(),extension.end(),extension.begin(),
[](unsigned char c){return char(std::tolower(c));});
if (extension != (content::find(data_directory_) ? ".obsettings" : ".ein")) {
error = "invalid_settings_file_extension";
return false;
}
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;
@@ -4909,14 +4808,7 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
if(!ec&&std::filesystem::is_symlink(status)) {error="settings_file_target_is_symlink";return false;}
if(request.action==ui::SaveLoadAction::load) {
Bytes bytes;
try {
bytes = content::find(data_directory_)
? content::load_preferences(request.path, "settings", kBytes)
: read_file(request.path);
} catch (const std::exception &) {
error = "settings_file_read_failed";
return false;
}
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<kBytes;++i)staged.memory.set8(base+uint32_t(i),bytes[i]);
std::array<uint8_t,kBytes> raw{};
@@ -4939,11 +4831,6 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
Bytes bytes(kBytes);
for(size_t i=0;i<kBytes;++i)bytes[i]=staged.memory.u8(base+uint32_t(i));
try {
if (content::find(data_directory_)) {
content::save_preferences(request.path, "settings", bytes, request.overwrite);
error.clear();
return true;
}
std::ofstream file(request.path,std::ios::binary|std::ios::trunc);
if(!file) {error="settings_file_write_failed";return false;}
file.write(reinterpret_cast<const char*>(bytes.data()),std::streamsize(bytes.size()));file.flush();
@@ -7635,11 +7522,6 @@ std::string CareerSession::take_autosave_error() {
}
void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& random) {
// OpenBMH deviates from the original: native saves do not consume gameplay randomness for encryption.
if (content::find(data_directory_)) {
native_autosave_pending_ = bool(autosave_directory_);
return;
}
std::filesystem::path temporary;
try {
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
@@ -7674,83 +7556,6 @@ void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& ra
}
}
cli::Json CareerSession::native_session_context() const {
cli::Json::Array runtime, callargs, managers;
for (const auto &[address, value] : club_modal_runtime_)
runtime.emplace_back(cli::Json::Object{{"address", int64_t(address)}, {"value", int(value)}});
for (const auto &args : source_desk_callargs_)
callargs.emplace_back(cli::Json::Array{args.competition, args.opponent});
for (const auto &manager : managers_)
managers.emplace_back(cli::Json::Array{manager.slot, manager.master_club, manager.runtime_club});
return cli::Json::Object{{"schema", "classic-session@1.0"},
{"runtime", std::move(runtime)},
{"desk_callargs", std::move(callargs)},
{"managers", std::move(managers)}};
}
void CareerSession::restore_native_session_context(const cli::Json &root) {
const auto field = [&](const char *name) -> const cli::Json & {
if (!root.object() || !root.object()->contains(name))
throw FormatError("Native session field missing");
return root.object()->at(name);
};
if (!field("schema").string() || *field("schema").string() != "classic-session@1.0")
throw FormatError("Unsupported native session");
const auto array = [](const cli::Json &j, size_t maximum) -> const cli::Json::Array & {
if (!j.array() || j.array()->size() > maximum)
throw FormatError("Invalid native session array");
return *j.array();
};
const auto integer = [](const cli::Json &j, int64_t low, int64_t high) -> int64_t {
if (!j.integer() || *j.integer() < low || *j.integer() > high)
throw FormatError("Invalid native session integer");
return *j.integer();
};
std::map<uint32_t, uint8_t> runtime;
for (const auto &row : array(field("runtime"), 8192)) {
if (!row.object() || !row.object()->contains("address") || !row.object()->contains("value"))
throw FormatError("Invalid runtime byte");
const auto at = uint32_t(integer(row.object()->at("address"), 0, UINT32_MAX));
if (!club_modal_runtime_.contains(at) ||
!runtime.emplace(at, uint8_t(integer(row.object()->at("value"), 0, 255))).second)
throw FormatError("Unknown or duplicated runtime byte");
}
if (runtime.size() != club_modal_runtime_.size())
throw FormatError("Incomplete native runtime bytes");
std::vector<ui::DeskMatchCallargs> callargs;
for (const auto &row : array(field("desk_callargs"), 4)) {
const auto &fields = array(row, 2);
if (fields.size() != 2)
throw FormatError("Invalid desk arguments");
callargs.push_back({int(integer(fields[0], -1, 255)), int(integer(fields[1], -1, 4095))});
}
std::vector<ui::InitializedManager> managers;
for (const auto &row : array(field("managers"), 4)) {
const auto &fields = array(row, 3);
if (fields.size() != 3)
throw FormatError("Invalid manager mapping");
managers.push_back({int(integer(fields[0], 0, 3)), int(integer(fields[1], 0, 4095)),
int(integer(fields[2], 0, 4095))});
}
club_modal_runtime_ = std::move(runtime);
source_desk_callargs_ = std::move(callargs);
managers_ = std::move(managers);
}
void CareerSession::flush_native_autosave() {
if (!std::exchange(native_autosave_pending_, false))
return;
try {
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
throw FormatError("Autosave directory unavailable");
const auto resource = content::find(data_directory_);
if (!resource)
throw FormatError("Native content unavailable");
content::save_career(*autosave_directory_ / "AUTOSAVE.obs", *resource->content, g_, rand_, game_,
turn_driver_, true, native_session_context());
} catch (const std::exception &e) {
autosave_error_ = e.what();
}
}
bool 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_||
@@ -7764,7 +7569,7 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
std::string extension = path.extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (manager_slot != active || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() ||
extension != (content::find(data_directory_) ? ".obs" : ".fbm") || path.filename().empty()) {
extension != ".fbm" || path.filename().empty()) {
error = "invalid_save_request"; return false;
}
std::error_code ec;
@@ -7777,11 +7582,6 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
const bool exists = std::filesystem::exists(path, ec);
if (ec || (exists && !overwrite)) { error = exists ? "overwrite_confirmation_required" : "save_target_unavailable"; return false; }
try {
if (const auto resource = content::find(data_directory_)) {
content::save_career(path, *resource->content, g_, rand_, game_, turn_driver_, overwrite,
native_session_context());
return true;
}
WatcomRandom staged_rand = rand_;
const Savegame save = make_savegame(g_, staged_rand);
write_savegame(path, save);
@@ -7823,10 +7623,7 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
std::string extension = request.path.extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(),
[](unsigned char c) { return char(std::tolower(c)); });
if (extension != (content::find(data_directory_) ? ".oblayout" : ".men")) {
error = "invalid_menu_layout_extension";
return false;
}
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() ||
@@ -7871,14 +7668,8 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
if (request.action == ui::SaveLoadAction::load) {
Bytes payload;
try {
payload = content::find(data_directory_)
? content::load_preferences(request.path, "layout", kLayoutBytes)
: read_file(request.path);
} catch (const std::exception &) {
error = "menu_layout_read_failed";
return false;
}
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)
@@ -7913,12 +7704,6 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
for (size_t i = 0; i < kLayoutBytes; ++i) payload[i] = g_.memory.u8(base + uint32_t(i));
if (!validate_payload(payload)) return false;
try {
if (content::find(data_directory_)) {
content::save_preferences(request.path, "layout", payload, request.overwrite);
++revision;
error.clear();
return true;
}
std::ofstream file(request.path, std::ios::binary | std::ios::trunc);
if (!file) { error = "menu_layout_write_failed"; return false; }
file.write(reinterpret_cast<const char*>(payload.data()), std::streamsize(payload.size()));
+1 -6
View File
@@ -808,8 +808,7 @@ public:
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, bool importing_legacy = false);
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_; }
@@ -884,10 +883,6 @@ private:
std::optional<std::filesystem::path> autosave_directory_;
std::string autosave_error_;
void write_desk_autosave(const GameState&, WatcomRandom&);
bool native_autosave_pending_ = false;
void flush_native_autosave();
cli::Json native_session_context() const;
void restore_native_session_context(const cli::Json &);
bool live_source_identity(const ui::StrengthsIdentity&) const;
bool validate_desk_setting_owner(const DeskSettingIdentity&, uint64_t revision, std::string& error,
bool require_desk_phase = true) const;
+6 -11
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/executable_layout.hpp"
#include "app/controller.hpp"
#include "app/window_actions.hpp"
@@ -352,8 +351,8 @@ void start_original_desk_audio(openbmh::audio::Playback& playback, const GameSta
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) {
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)); });
@@ -980,8 +979,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
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), bool(content::find(data)));
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);
@@ -1878,8 +1876,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
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,
content::find(data) ? ".obsettings" : ".ein")) {
!save_path_in_directory(request.path, save_directory, ".ein")) {
flow.reject_settings_file("stale_request_or_invalid_settings_path");
return {};
}
@@ -1910,8 +1907,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
return {};
}
if (request.revision != revision ||
!save_path_in_directory(request.path, save_directory,
content::find(data) ? ".oblayout" : ".men")) {
!save_path_in_directory(request.path, save_directory, ".men")) {
flow.reject_file_action("stale_request_or_invalid_menu_layout_path");
return {};
}
@@ -1929,8 +1925,7 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
}
} 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, content::find(data) ? ".obs" : ".fbm")) {
if (request.revision != revision || !save_path_in_directory(request.path, save_directory)) {
flow.reject_file_action("stale_request_or_invalid_save_path");
return {};
}
+104 -155
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/executable_layout.hpp"
#include "ui/live_timing.hpp"
// openbmh_play - the UI of src/ui connected to the engine: options, manager dialogs, a new
@@ -11,7 +10,6 @@
#include <SDL.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
@@ -26,13 +24,9 @@
#include <vector>
#include "app/controller.hpp"
#include "app/quit_confirmation.hpp"
#include "launch/archive.hpp"
#include "launch/file_dialog.hpp"
#include "launch/game_data.hpp"
#include "launch/launcher.hpp"
#include "launch/startup_error.hpp"
#include "content/package.hpp"
#include "version.hpp"
#include "app/live_matchday_events.hpp"
#include "audio/playback.hpp"
@@ -76,23 +70,30 @@ 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) {
rml::report_start_error("OpenBMH", text);
std::fprintf(stderr, "%s\n", text.c_str());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "OpenBMH", text.c_str(), nullptr);
}
// Reattach the native editor when an in-game filename field takes focus. Cocoa
// owns a field-editor responder in addition to SDL's TEXTINPUT enable flag.
static void focus_filename_input(SDL_Renderer* renderer) {
int left, top, right, bottom;
SDL_RenderLogicalToWindow(renderer, 106, 209, &left, &top);
SDL_RenderLogicalToWindow(renderer, 262, 219, &right, &bottom);
const SDL_Rect field{left, top, std::max(1, right - left), std::max(1, bottom - top)};
SDL_StopTextInput();
SDL_SetTextInputRect(&field);
SDL_StartTextInput();
#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<unsigned long>(-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) {
rml::attach_parent_console();
attach_parent_console();
const std::vector<std::string> 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());
@@ -116,7 +117,7 @@ int main(int argc, char** argv) {
} 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("--run-mod") || is("--mod") || is("--data")) && value) {
} 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));
@@ -128,69 +129,51 @@ int main(int argc, char** argv) {
std::printf("OpenBMH %s\n", bmh::kOpenBmhVersion);
return 0;
} else if (is("--help") || is("-h")) {
std::printf("usage: OpenBMH [--mod <mods/name/content.obw>] [--seed <Watcom seed>] "
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] "
"[--live-frame-ms <0..1000>]\n");
std::printf("usage: openbmh_play [<game directory | BMH.EXE | game.zip | game.7z>] [--seed <Watcom seed>] "
"[--save-directory <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]);
} else {
show_start_error("Unknown option or missing argument: " + args[i]);
return 1;
}
}
std::filesystem::path executable;
if (char *base = SDL_GetBasePath()) {
executable = launch::path_from_utf8(base);
SDL_free(base);
#ifdef _WIN32
executable /= "OpenBMH.exe";
#else
executable /= "OpenBMH";
#endif
} else
executable = fs::absolute(launch::path_from_utf8(args.front()));
// 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 {
return launch::run_launcher(executable, [](const fs::path &package, const fs::path &source,
const fs::path &destination) {
const auto content = content::open(package);
content::Mount mount(package, content);
const auto source_bytes = read_file(source);
const auto digest = content::sha256(std::string(source_bytes.begin(), source_bytes.end()));
const auto seed = uint32_t(std::stoul(digest.substr(0, 8), nullptr, 16));
app::CareerSession migrated(mount.root(), seed, source, true);
std::string error;
if (!migrated.save_game(destination, migrated.state().memory.u8(::bmh::layout::ActiveManager),
false, error))
throw FormatError("Spielstand konnte nicht übernommen werden: " + error);
});
} catch (const std::exception &e) {
show_start_error(e.what());
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 <game directory | BMH.EXE | game.zip>");
return 1;
}
}
std::shared_ptr<const content::Classic> contents;
std::unique_ptr<content::Mount> mount;
bool english_game = false;
try {
if (fs::is_directory(data))
data /= "content.obw";
contents = content::open(data);
mount = std::make_unique<content::Mount>(data, contents);
data = mount->root();
english_game = contents->english;
if (save_directory.empty()) {
const auto root = executable.parent_path();
launch::ModLibrary library(root);
launch::ModEntry mod;
mod.content_id = contents->content_id;
save_directory = library.user_directory(mod);
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;
}
} catch (const std::exception &e) {
show_start_error(e.what());
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);
@@ -223,8 +206,6 @@ int main(int argc, char** argv) {
ui::SportschauTeamInfo sportschau_team_info(data);
ui::CompetitionWinnerScreen competition_winner(data);
const auto season_exe = load_le(ui::asset_path(data, "BMH.exe"));
english_game = english_game || season_exe.u8(layout::LeagueSizes) == 20;
app::QuitConfirmation quit_confirmation(window, english_game);
try {
if (!playback.initialize_original(app::original_audio_assets(data, season_exe), audio_error))
std::fprintf(stderr, "audio: %s\n", audio_error.c_str());
@@ -364,7 +345,7 @@ int main(int argc, char** argv) {
if (screen.close_requested()) return renewed_expired_player ? 1 : 0;
SDL_Event event;
bool changed = false;
while (quit_confirmation.poll(&event)) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
staged = before;
@@ -466,7 +447,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event event;
while (quit_confirmation.poll(&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;
@@ -480,7 +461,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event event;
while (quit_confirmation.poll(&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;
@@ -493,7 +474,7 @@ int main(int argc, char** argv) {
SDL_Delay(20); // Source timer unit used by the traced intro path.
SDL_PumpEvents();
SDL_Event close;
while (quit_confirmation.peep(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
while (SDL_PeepEvents(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
running = false; // platform close is the only intro-loop escape
}
};
@@ -507,7 +488,7 @@ int main(int argc, char** argv) {
while (running && SDL_GetPerformanceCounter() - started < ticks_per_wait) {
SDL_PumpEvents();
SDL_Event close;
while (quit_confirmation.peep(&close, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0)
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);
}
@@ -557,7 +538,7 @@ int main(int argc, char** argv) {
bool skipped = false;
while (running && !skipped && SDL_GetTicks() - start < duration) {
SDL_Event input;
while (quit_confirmation.poll(&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;
@@ -580,14 +561,14 @@ int main(int argc, char** argv) {
bool skip = false;
SDL_Event input;
if (step.minute_wait) {
while (quit_confirmation.poll(&input)) {
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 (quit_confirmation.peep(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
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) +
@@ -702,7 +683,7 @@ int main(int argc, char** argv) {
auto pressed = ui::GameEndTaxDialog::Button::none;
while (running) {
SDL_Event input;
while (quit_confirmation.poll(&input)) {
while (SDL_PollEvent(&input)) {
if (input.type == SDL_QUIT) { running = false; return false; }
if (input.type == SDL_MOUSEBUTTONDOWN) {
if (event.kind != SeasonTaxEventKind::question &&
@@ -741,7 +722,7 @@ int main(int argc, char** argv) {
const auto started = SDL_GetTicks();
while (running && Uint32(SDL_GetTicks() - started) < animation.wait_milliseconds()) {
SDL_Event input;
while (quit_confirmation.poll(&input)) if (input.type == SDL_QUIT) running = false;
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);
}
@@ -758,7 +739,7 @@ int main(int argc, char** argv) {
// events for the next Original input boundary; only handle SDL exit.
SDL_PumpEvents();
SDL_Event quit;
if (quit_confirmation.peep(&quit, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
if (SDL_PeepEvents(&quit, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) running = false;
if (running) SDL_Delay(10);
}
};
@@ -813,7 +794,7 @@ int main(int argc, char** argv) {
if (timed && Uint32(SDL_GetTicks() - started) >= 70 * 3 * 20)
return complete(PendingOfferAnswer::yes);
SDL_Event input;
while (quit_confirmation.poll(&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)
@@ -883,7 +864,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); // DecodeTaxAnimationScript/SDLFlushEvents redraw boundary
while (running) {
SDL_Event input;
while (quit_confirmation.poll(&input)) {
while (SDL_PollEvent(&input)) {
if (input.type == SDL_QUIT) { running = false; return PendingOfferTransferChoice{}; }
std::optional<int> bid;
if (input.type == SDL_MOUSEBUTTONDOWN &&
@@ -912,7 +893,7 @@ int main(int argc, char** argv) {
bool acknowledged=false;
while(running && !acknowledged) {
SDL_Event event;
while(quit_confirmation.poll(&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)) {
@@ -975,7 +956,7 @@ int main(int argc, char** argv) {
draw();
while (running) {
SDL_Event event;
while (quit_confirmation.poll(&event)) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) { running = false; return -1; }
ui::OutgoingTransferRequest action;
if (event.type == SDL_MOUSEMOTION) continue;
@@ -1092,7 +1073,7 @@ int main(int argc, char** argv) {
while (running) {
if (deadline_expired()) return true; //ClubInfoFromGame event8 returns to its owning caller.
SDL_Event input;
while (quit_confirmation.poll(&input)) {
while (SDL_PollEvent(&input)) {
if (input.type == SDL_QUIT) { running = false; return false; }
if (deadline_expired()) return true;
ui::ClubInfoRequest request;
@@ -1193,7 +1174,7 @@ int main(int argc, char** argv) {
SDL_PumpEvents();
while (running && (SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) {
SDL_Event input;
while (quit_confirmation.poll(&input))
while (SDL_PollEvent(&input))
if (input.type == SDL_QUIT) { running = false; return; }
SDL_PumpEvents();
if (running) SDL_Delay(10);
@@ -1261,7 +1242,7 @@ int main(int argc, char** argv) {
while (running) {
if (const auto complete = expire_card()) return *complete;
SDL_Event input;
while (quit_confirmation.poll(&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;
@@ -1323,7 +1304,7 @@ int main(int argc, char** argv) {
while (running) {
if (deadline_expired()) return; //LeagueCalculations frees its child before4f548 polls again.
SDL_Event input;
while (quit_confirmation.poll(&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)
@@ -1407,7 +1388,7 @@ int main(int argc, char** argv) {
while(running&&!outcome) {
if(expire_range())break;
SDL_Event input;
while(quit_confirmation.poll(&input)) {
while(SDL_PollEvent(&input)) {
if(input.type==SDL_QUIT){running=false;break;}
if(expire_range())break;
bool changed=false;
@@ -1463,7 +1444,7 @@ int main(int argc, char** argv) {
while(running) {
if(deadline_expired())return std::nullopt;
SDL_Event input;
while(quit_confirmation.poll(&input)) {
while(SDL_PollEvent(&input)) {
if(input.type==SDL_QUIT){running=false;break;}
if(deadline_expired())return std::nullopt;
bool changed=false;
@@ -1557,7 +1538,7 @@ int main(int argc, char** argv) {
// Source ignores the first OriginalMouseSound poll's gameplay result, then
// presents the starting scene before its ten option-delay polls.
SDL_Event initial;
if (quit_confirmation.poll(&initial) && initial.type == SDL_QUIT) { running = false; return; }
if (SDL_PollEvent(&initial) && initial.type == SDL_QUIT) { running = false; return; }
show_draw();
while (running && screen.advance_step()) {
if (screen.present_needed()) show_draw();
@@ -1565,7 +1546,7 @@ int main(int argc, char** argv) {
if (!running) return;
if (screen.input_poll_needed()) {
SDL_Event input;
while (quit_confirmation.poll(&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)) {
@@ -1600,7 +1581,7 @@ int main(int argc, char** argv) {
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
while (running) {
SDL_Event input;
while (quit_confirmation.poll(&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;
@@ -1637,7 +1618,7 @@ int main(int argc, char** argv) {
while (running && screen.phase() == ui::AlternateScorePhase::Calculator) {
SDL_Event event;
bool changed = false;
while (quit_confirmation.poll(&event)) {
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;
@@ -1679,8 +1660,7 @@ int main(int argc, char** argv) {
wait_season_ack();
}
} else {
const auto file =
highscore_file(save_directory, signature, season_texts[889], bool(content::find(data)));
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.
@@ -1703,11 +1683,6 @@ int main(int argc, char** argv) {
std::optional<Uint64> timed_notice_presented_at;
std::optional<Uint8> timed_notice_release;
auto handle = [&](const ui::FlowResult& r) {
if (r.request == ui::FlowRequest::end_session && !quit_confirmation.confirm()) {
flow.reject_desk_action(english_game ? "Quit cancelled." : "Beenden abgebrochen.");
dirty = true;
return;
}
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) {
@@ -1830,7 +1805,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_Event modal;
bool redrawn = false;
while (quit_confirmation.poll(&modal)) {
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;
@@ -2000,7 +1975,7 @@ int main(int argc, char** argv) {
show_dialog();
while (running && !outcome) {
SDL_Event input;
while (quit_confirmation.poll(&input)) {
while (SDL_PollEvent(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
bool changed = false;
if (input.type == SDL_TEXTINPUT) {
@@ -2100,7 +2075,7 @@ int main(int argc, char** argv) {
while (running && !closed) {
SDL_Event input;
bool redrawn = false;
while (quit_confirmation.poll(&input)) {
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)
@@ -2210,7 +2185,7 @@ int main(int argc, char** argv) {
offer_dirty = false;
}
SDL_Event event;
while (quit_confirmation.poll(&event)) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) { running = false; return -1; }
std::optional<int> answer;
if (event.type == SDL_MOUSEBUTTONUP &&
@@ -2279,7 +2254,7 @@ int main(int argc, char** argv) {
rendered_phase = phase;
}
SDL_Event event;
while (quit_confirmation.poll(&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))
@@ -2307,7 +2282,7 @@ int main(int argc, char** argv) {
bool dismissed = false;
while (running && !dismissed) {
SDL_Event event;
while (quit_confirmation.poll(&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)) {
@@ -2461,7 +2436,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_Event modal;
bool redrawn = false;
while (quit_confirmation.poll(&modal)) {
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))
@@ -2526,7 +2501,7 @@ int main(int argc, char** argv) {
bool resumed = false;
while (running && !resumed) {
SDL_Event paused_event;
while (quit_confirmation.poll(&paused_event)) {
while (SDL_PollEvent(&paused_event)) {
if (paused_event.type == SDL_QUIT) {
quit = true;
live_skipped = true;
@@ -2639,12 +2614,11 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
};
render_file();
focus_filename_input(renderer);
bool finished = false;
while (running && !finished) {
SDL_Event file_input;
bool file_changed = false;
while (quit_confirmation.poll(&file_input)) {
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 ||
@@ -2704,7 +2678,7 @@ int main(int argc, char** argv) {
while (running && !closed) {
SDL_Event input;
bool changed = false;
while (quit_confirmation.poll(&input)) {
while (SDL_PollEvent(&input)) {
if (input.type == SDL_QUIT) { running = false; break; }
if (readme) {
if (input.type == SDL_MOUSEBUTTONDOWN &&
@@ -2818,7 +2792,7 @@ int main(int argc, char** argv) {
const bool source_phase_start = minute == 1 ||
(state.indoor ? minute == 21 : (minute == 46 || minute == 91 || minute == 106));
SDL_Event event;
while (quit_confirmation.poll(&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;
@@ -2939,7 +2913,7 @@ int main(int argc, char** argv) {
present(live_screen.render_ball(frame, event.displacement, index, chance));
SDL_PumpEvents();
SDL_Event quit_event;
if (quit_confirmation.peep(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
break;
}
@@ -2976,7 +2950,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_PumpEvents();
SDL_Event quit_event;
if (quit_confirmation.peep(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (SDL_PeepEvents(&quit_event, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
live_chance_context.reset();
return;
@@ -3008,7 +2982,7 @@ int main(int argc, char** argv) {
SDL_RenderPresent(renderer);
SDL_PumpEvents();
SDL_Event input;
if (quit_confirmation.peep(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
if (SDL_PeepEvents(&input, 1, SDL_GETEVENT, SDL_QUIT, SDL_QUIT) > 0) {
running = false;
return;
}
@@ -3030,7 +3004,7 @@ int main(int argc, char** argv) {
SDL_Event input;
bool acknowledged = false;
while (running && !acknowledged) {
while (quit_confirmation.poll(&input)) {
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)) {
@@ -3065,7 +3039,7 @@ int main(int argc, char** argv) {
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 (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { 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);
@@ -3091,7 +3065,7 @@ int main(int argc, char** argv) {
if (event.kind != 2 && app::match_sound_enabled(state))
app::original_audio_command(playback, 17); // EventImpl/SDLPumpEvents, no injury whistle.
SDL_PumpEvents();SDL_Event input;
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { 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;
@@ -3115,7 +3089,7 @@ int main(int argc, char** argv) {
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 (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
if (SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { 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;
@@ -3179,16 +3153,16 @@ int main(int argc, char** argv) {
present(reality_surface,reality_colors,"OpenBMH - live_reality_report_"+round_identity);
}
SDL_PumpEvents();SDL_Event input;
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) {running=false;return true;}
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 (quit_confirmation.peep(&input,1,SDL_PEEKEVENT,SDL_KEYDOWN,SDL_KEYDOWN)>0 &&
if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_KEYDOWN,SDL_KEYDOWN)>0 &&
input.key.keysym.sym==SDLK_ESCAPE) {
quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_KEYDOWN,SDL_KEYDOWN);return true;
SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_KEYDOWN,SDL_KEYDOWN);return true;
}
if (quit_confirmation.peep(&input,1,SDL_PEEKEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN)>0 &&
if (SDL_PeepEvents(&input,1,SDL_PEEKEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN)>0 &&
input.button.button==SDL_BUTTON_RIGHT) {
quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true;
SDL_PeepEvents(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true;
}
return false;
}, [&](const PhaseResultRequest& request, const std::vector<MatchGroup>& groups,
@@ -3601,42 +3575,18 @@ int main(int argc, char** argv) {
}
};
SDL_StartTextInput();
bool filename_input_active = false;
std::array<bool, 2> setup_button_down{};
while (running) {
const bool filename_open = flow.screen_name() == "save_load";
if (filename_open && !filename_input_active) focus_filename_input(renderer);
filename_input_active = filename_open;
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 (quit_confirmation.poll(&e)) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
running = false;
break;
}
if (e.type == SDL_WINDOWEVENT) {
if (e.window.event == SDL_WINDOWEVENT_FOCUS_LOST) setup_button_down.fill(false);
if (e.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) {
if (flow.screen_name() == "save_load") focus_filename_input(renderer);
else SDL_StartTextInput();
}
}
// A native picker/window activation can leave an unmatched UP.
// Only a press which began on setup may toggle its options.
if ((e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) &&
(e.button.button == SDL_BUTTON_LEFT || e.button.button == SDL_BUTTON_RIGHT)) {
const size_t button = e.button.button == SDL_BUTTON_LEFT ? 0 : 1;
if (e.type == SDL_MOUSEBUTTONDOWN) setup_button_down[button] = flow.screen_name() == "setup";
else {
const bool owned = setup_button_down[button];
setup_button_down[button] = false;
if (flow.screen_name() == "setup" && !owned) continue;
}
}
if(e.type==SDL_MOUSEBUTTONUP&&timed_notice_release&&e.button.button==*timed_notice_release) {
timed_notice_release.reset();continue;
}
@@ -3692,8 +3642,7 @@ int main(int argc, char** argv) {
continue;
}
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE &&
!flow.in_preparation_menu() && !flow.in_results_view() && !flow.in_readonly_view() &&
quit_confirmation.confirm())
!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(),
-63
View File
@@ -1,63 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <SDL.h>
#include <functional>
#include <utility>
namespace bmh::app {
// OpenBMH deviates from the original: confirms application exit with a localized native dialog, with cancellation selected by default.
// All event retrieval remains on the UI thread. An event filter/watch could run
// on SDL's event thread and must not own a native modal dialog.
class QuitConfirmation {
public:
using Presenter = std::function<int(const SDL_MessageBoxData*, int*)>;
QuitConfirmation(SDL_Window* window, bool english, Presenter presenter = SDL_ShowMessageBox)
: window_(window), english_(english), presenter_(std::move(presenter)) {}
bool confirm() {
if (confirmed_) return true;
const SDL_MessageBoxButtonData buttons[] = {
{SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT | SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT,
0, english_ ? "Cancel" : "Abbrechen"},
{0, 1, english_ ? "Quit" : "Beenden"}
};
const SDL_MessageBoxData dialog{SDL_MESSAGEBOX_WARNING, window_,
english_ ? "Quit OpenBMH?" : "OpenBMH beenden?",
english_ ? "Do you really want to quit OpenBMH?\nUnsaved changes will be lost." :
"OpenBMH wirklich beenden?\nNicht gespeicherte Änderungen gehen verloren.",
2, buttons, nullptr};
int selected = 0;
if (presenter_(&dialog, &selected) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Cannot show quit confirmation: %s", SDL_GetError());
return false; // A failed dialog must not silently discard the session.
}
confirmed_ = selected == 1;
return confirmed_;
}
int poll(SDL_Event* event) {
if (!event) return SDL_PollEvent(nullptr);
while (SDL_PollEvent(event)) {
if (event->type != SDL_QUIT || confirm()) return 1;
}
return 0;
}
int peep(SDL_Event* events, int count, SDL_eventaction action, Uint32 first, Uint32 last) {
const int received = SDL_PeepEvents(events, count, action, first, last);
if (received <= 0 || !events || action != SDL_GETEVENT) return received;
int kept = 0;
for (int i = 0; i < received; ++i)
if (events[i].type != SDL_QUIT || confirm()) events[kept++] = events[i];
return kept;
}
private:
SDL_Window* window_;
bool english_, confirmed_ = false;
Presenter presenter_;
};
} // namespace bmh::app