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
+2 -24
View File
@@ -70,14 +70,7 @@ struct OriginalSynth::State {
unsigned tempo_tick{};
std::function<void(std::uint8_t, std::uint8_t)> register_observer;
std::function<void(std::uint8_t)> sample_observer;
std::function<void(const OriginalNoteEvent&)> note_observer;
void observe_note(unsigned track, std::uint8_t channel, std::uint8_t instrument, std::uint8_t pitch,
std::uint8_t duration, std::uint8_t volume, bool sample) {
if (dry || !note_observer) return;
note_observer(OriginalNoteEvent{stats.bar, stats.step, std::uint8_t(track), channel, instrument, pitch,
duration, volume, sample});
}
void write(std::uint8_t reg, std::uint8_t value) noexcept {
if (dry) return;
++stats.register_writes;
@@ -320,19 +313,13 @@ struct OriginalSynth::State {
const auto pitch = code < 128 ? code : song.parts[cursor++];
const auto duration = song.parts[cursor++];
if (index == 9 && code < 128) {
if (!dma_effect) {
observe_note(index, 0, 0, pitch, 0, 0, true);
start_sample(pitch, false);
}
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;
const auto played = std::uint8_t(pitch + t.transpose);
const auto volume = song_level(t.volume);
observe_note(index, t.channel, t.instrument, played, duration, volume, false);
note(t.channel, played, volume);
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; }
@@ -477,14 +464,5 @@ void OriginalSynth::set_register_observer(std::function<void(std::uint8_t, std::
void OriginalSynth::set_sample_observer(std::function<void(std::uint8_t)> f) {
if (state_) state_->sample_observer = std::move(f);
}
void OriginalSynth::set_note_observer(std::function<void(const OriginalNoteEvent&)> f) {
if (state_) state_->note_observer = std::move(f);
}
bool OriginalSynth::song_timing(unsigned song, OriginalSongTiming& timing) const noexcept {
if (!state_ || song >= state_->songs.size()) return false;
const auto& s = state_->songs[song];
timing = {s.tempo, s.end, s.repeat};
return true;
}
} // namespace openbmh::audio
-18
View File
@@ -31,21 +31,6 @@ struct OriginalAudioStats {
std::uint32_t bar{}, step{}, song = 255;
bool playing{}, ambient{}, failed{};
};
// Timing of one song: one sequencer step every `tempo` IRQ0 ticks, 16 steps per
// bar; after bar `end` playback continues at bar `repeat` (end == repeat: stop).
struct OriginalSongTiming {
std::uint16_t tempo{}, end{}, repeat{};
};
// One note the music sequencer actually started (offline tools such as the MIDI
// export). `pitch` is the index into the OPL note table with the track transpose
// applied; `duration` counts sequencer steps until key-off (255 = held until the
// channel's next note); `level` is the OPL output level 0..63. Sample notes
// (track 9) carry the sample slot in `pitch` and no channel, duration or level.
struct OriginalNoteEvent {
std::uint32_t bar{}, step{};
std::uint8_t track{}, channel{}, instrument{}, pitch{}, duration{}, level{};
bool sample{};
};
// The Original MIDILINK sequencer and one Sound Blaster PCM channel. IRQ0 uses
// PIT divisor0x199a. SONG/TRCK/PART, OPL instruments, SFX priorities/lifetimes,
@@ -73,9 +58,6 @@ public:
void tick() noexcept;
void set_register_observer(std::function<void(std::uint8_t, std::uint8_t)> observer);
void set_sample_observer(std::function<void(std::uint8_t)> observer);
void set_note_observer(std::function<void(const OriginalNoteEvent&)> observer);
// Timing of song 0..2; false before load() or for another index.
bool song_timing(unsigned song, OriginalSongTiming& timing) const noexcept;
private:
struct State;
std::unique_ptr<State> state_;
-290
View File
@@ -2,7 +2,6 @@
#include "formats/executable_layout.hpp"
#include "container.hpp"
#include "music_fallback.hpp"
#include "original.hpp"
#include "playback.hpp"
#include "formats/le.hpp"
@@ -20,7 +19,6 @@
#include <charconv>
#include <filesystem>
#include <span>
#include <sstream>
#include <string_view>
namespace {
@@ -79,279 +77,10 @@ openbmh::audio::OriginalAssets load_original_assets(const std::filesystem::path&
return assets;
}
// ---------------------------------------------------------------------------
// MIDI export of the Original music (for remastering with other instruments).
//
// The sequencer runs offline exactly as in the game; the note observer records
// every note it starts. Each of the 16 song tracks becomes one MIDI track on the
// MIDI channel of the same number, so track 9, the sample (drum) track, lands on
// General MIDI channel 10. One sequencer step is a sixteenth note (16 steps per
// bar, 96 ticks per quarter); the tempo follows from the song's IRQ0 divisor.
// OPL pitches are converted through the note table of the user's executable.
// An optional map file assigns General MIDI programs and drum notes:
// inst <instrument> <program 0..127>
// sample <slot> <drum note 0..127>
// A template listing the instruments and samples a song uses is written next to
// the MIDI file (OUTPUT.map.txt) so the assignment can be edited and re-run.
struct MidiNote {
std::uint32_t start{}, end{};
std::uint8_t note{}, velocity{}, instrument{};
bool sample{};
};
// Program per instrument and drum note per sample slot; -1 = not assigned.
struct MidiMap {
std::array<int, 256> program;
std::array<int, 256> drum;
MidiMap() { program.fill(-1); drum.fill(-1); }
};
// Default General MIDI program from how an instrument is played: low lines become
// a bass, instruments that often sound in chords strings, high lines a trumpet and
// the remaining lines a brass section. Only a starting point for the editable map.
int guess_program(double mean_note, double chord_share) {
if (mean_note < 50.0) return 33; // Electric Bass (finger)
if (chord_share > 0.25) return 48; // String Ensemble 1
return mean_note >= 70.0 ? 56 : 61; // Trumpet for high lines, else Brass Section
}
// Default drum note from the sample itself: zero crossings per second separate
// dark (kick), middle (snare, tom) and bright (hi-hat, cymbal) sounds; the
// length separates closed from open or crash sounds.
int guess_drum(const openbmh::audio::PcmSample& pcm) {
if (pcm.mono.empty() || !pcm.sample_rate) return 38;
std::size_t crossings = 0;
for (std::size_t i = 1; i < pcm.mono.size(); ++i)
crossings += (pcm.mono[i - 1] < 0) != (pcm.mono[i] < 0);
const double seconds = double(pcm.mono.size()) / pcm.sample_rate;
const double rate = crossings / seconds;
if (rate < 1200.0) return seconds < 0.6 ? 36 : 41; // Bass Drum 1 / Low Floor Tom
if (rate < 4000.0) return seconds < 0.4 ? 38 : 45; // Acoustic Snare / Low Tom
if (seconds < 0.15) return 42; // Closed Hi-Hat
return seconds < 0.5 ? 46 : 49; // Open Hi-Hat / Crash Cymbal 1
}
bool read_midi_map(const std::filesystem::path& path, MidiMap& map, std::string& error) {
std::ifstream in(path);
if (!in) { error = "cannot read MIDI map"; return false; }
std::string kind;
unsigned line = 0;
for (std::string text; std::getline(in, text);) {
++line;
if (const auto hash = text.find('#'); hash != std::string::npos) text.resize(hash);
std::istringstream fields(text);
int index = -1, value = -1;
if (!(fields >> kind)) continue;
if (!(fields >> index >> value) || index < 0 || index > 255 || value < 0 || value > 127 ||
(kind != "inst" && kind != "sample")) {
error = "invalid MIDI map line " + std::to_string(line); return false;
}
(kind == "inst" ? map.program : map.drum)[std::size_t(index)] = value;
}
return true;
}
bool write_midi(const std::filesystem::path& path, const std::array<std::vector<MidiNote>, 16>& tracks,
const MidiMap& map, std::uint32_t usec_per_quarter, std::uint32_t loop_start,
std::uint32_t loop_end, std::string& error) {
using Track = std::vector<std::uint8_t>;
const auto vlq = [](Track& t, std::uint32_t value) {
std::uint8_t bytes[5]; int n = 0;
do { bytes[n++] = std::uint8_t(value & 0x7f); value >>= 7; } while (value);
while (n--) t.push_back(std::uint8_t(bytes[n] | (n ? 0x80 : 0)));
};
const auto meta_text = [&vlq](Track& t, std::uint32_t delta, std::uint8_t type, const std::string& text) {
vlq(t, delta); t.push_back(0xff); t.push_back(type); vlq(t, std::uint32_t(text.size()));
t.insert(t.end(), text.begin(), text.end());
};
std::vector<Track> chunks;
{ // Conductor track: tempo, 4/4, loop markers.
Track t;
t.insert(t.end(), {0x00, 0xff, 0x51, 0x03, std::uint8_t(usec_per_quarter >> 16),
std::uint8_t(usec_per_quarter >> 8), std::uint8_t(usec_per_quarter)});
t.insert(t.end(), {0x00, 0xff, 0x58, 0x04, 0x04, 0x02, 0x18, 0x08});
std::uint32_t now = 0;
if (loop_start != loop_end) {
meta_text(t, loop_start, 0x06, "loop start"); now = loop_start;
meta_text(t, loop_end - now, 0x06, "loop end"); now = loop_end;
}
t.insert(t.end(), {0x00, 0xff, 0x2f, 0x00});
chunks.push_back(std::move(t));
}
for (unsigned index = 0; index < tracks.size(); ++index) {
const auto& notes = tracks[index];
if (notes.empty()) continue;
const std::uint8_t channel = std::uint8_t(index);
struct Event { std::uint32_t time; int order; std::uint8_t status, a, b; bool two; };
std::vector<Event> events;
int last_program = -1;
for (const auto& n : notes) {
if (!n.sample) {
const int program = map.program[n.instrument];
if (program != last_program) {
events.push_back({n.start, 1, std::uint8_t(0xc0 | channel), std::uint8_t(program), 0, false});
last_program = program;
}
}
// Sample notes carry their slot in `instrument`; the map names the drum.
const auto key = n.sample ? std::uint8_t(map.drum[n.instrument]) : n.note;
events.push_back({n.start, 2, std::uint8_t(0x90 | channel), key, n.velocity, true});
events.push_back({n.end, 0, std::uint8_t(0x80 | channel), key, 0, true});
}
// Note-offs before program changes before note-ons at the same time.
std::stable_sort(events.begin(), events.end(), [](const Event& l, const Event& r) {
return l.time != r.time ? l.time < r.time : l.order < r.order;
});
Track t;
meta_text(t, 0, 0x03, index == 9 ? "track 9 (samples)" : "track " + std::to_string(index));
std::uint32_t now = 0;
for (const auto& e : events) {
vlq(t, e.time - now); now = e.time;
t.push_back(e.status); t.push_back(e.a);
if (e.two) t.push_back(e.b);
}
t.insert(t.end(), {0x00, 0xff, 0x2f, 0x00});
chunks.push_back(std::move(t));
}
std::ofstream out(path, std::ios::binary);
if (!out) { error = "cannot create MIDI output"; return false; }
const auto put16 = [&out](unsigned v) { const char b[] = {char(v >> 8), char(v)}; out.write(b, 2); };
const auto put32 = [&out](std::uint32_t v) {
const char b[] = {char(v >> 24), char(v >> 16), char(v >> 8), char(v)}; out.write(b, 4);
};
out.write("MThd", 4); put32(6); put16(1); put16(unsigned(chunks.size())); put16(96);
for (const auto& t : chunks) {
out.write("MTrk", 4); put32(std::uint32_t(t.size()));
out.write(reinterpret_cast<const char*>(t.data()), std::streamsize(t.size()));
}
if (!out) { error = "failed while writing MIDI output"; return false; }
return true;
}
int export_midi(openbmh::audio::OriginalAssets assets, unsigned song, const std::filesystem::path& output,
unsigned loops, const std::filesystem::path& map_path) {
using namespace openbmh::audio;
MidiMap map;
std::string error;
if (!map_path.empty() && !read_midi_map(map_path, map, error)) { std::cerr << error << '\n'; return 1; }
// MIDI note of every entry of the OPL note table: F-number and block give the
// frequency (49716 Hz OPL clock), rounded to the nearest equal-tempered note.
std::array<std::uint8_t, 96> midi_note{};
for (unsigned i = 0; i < midi_note.size(); ++i) {
const auto f = assets.tables.frequencies[i];
const double hz = double(f & 0x3ff) * 49716.0 / std::pow(2.0, 20 - ((f >> 10) & 7));
midi_note[i] = std::uint8_t(std::clamp(std::lround(69.0 + 12.0 * std::log2(hz / 440.0)), 0L, 127L));
}
// The song's own bank, kept for analysing its drum samples after the run.
const std::vector<std::uint8_t> bank = assets.containers.at(song);
OriginalSynth synth;
if (!synth.load(std::move(assets), 22050, error)) {
std::cerr << "Original audio rejected: " << error << '\n'; return 1;
}
OriginalSongTiming timing;
if (!synth.song_timing(song, timing)) { std::cerr << "unknown song\n"; return 1; }
constexpr std::uint32_t kTicksPerStep = 24; // 96 per quarter, a step is a sixteenth
std::array<std::vector<MidiNote>, 16> tracks;
// Last note per OPL channel: a new note on the channel ends the previous one.
std::array<std::pair<int, std::size_t>, 9> sounding;
sounding.fill({-1, 0});
std::array<bool, 256> used_instrument{}, used_sample{};
// The export ends after the first pass plus (loops - 1) passes of the loop
// section; a song without a loop (end == repeat) ends after its last bar.
const bool looping = timing.end != timing.repeat;
const std::uint64_t last_step = std::uint64_t(timing.end) * 16 +
(looping ? std::uint64_t(loops - 1) * (timing.end - timing.repeat) * 16 : 0);
std::uint64_t tick = 0;
synth.set_note_observer([&](const OriginalNoteEvent& e) {
if (tick / timing.tempo >= last_step) return;
const auto start = std::uint32_t(tick / timing.tempo) * kTicksPerStep;
if (e.sample) {
used_sample[e.pitch] = true;
tracks[e.track].push_back({start, start + kTicksPerStep / 2, 0, 100, e.pitch, true});
return;
}
used_instrument[e.instrument] = true;
if (auto [track, index] = sounding[e.channel]; track >= 0) {
auto& previous = tracks[std::size_t(track)][index];
previous.end = std::min(previous.end, start);
if (previous.end <= previous.start) previous.end = previous.start + 1;
}
// duration 0 releases in the step it starts; 255 holds until the next note.
const std::uint32_t length = e.duration == 255 ? std::numeric_limits<std::uint32_t>::max() / 2
: std::max<std::uint32_t>(e.duration * kTicksPerStep, kTicksPerStep / 4);
tracks[e.track].push_back({start, start + length, midi_note[e.pitch],
std::uint8_t(std::min(127, 1 + e.level * 2)), e.instrument, false});
sounding[e.channel] = {int(e.track), tracks[e.track].size() - 1};
});
if (!synth.command(std::uint8_t(song))) { std::cerr << "Original command rejected\n"; return 1; }
std::uint64_t steps = 0;
for (; tick / timing.tempo < last_step; ++tick) {
synth.tick();
const auto stats = synth.stats();
if (stats.failed) { std::cerr << "Original decoder failed during export\n"; return 1; }
steps = tick / timing.tempo + 1;
if (!stats.playing) break;
}
const auto song_end = std::uint32_t(std::min(steps, last_step)) * kTicksPerStep;
const unsigned completed_loops = looping ? loops : 1;
for (auto& notes : tracks)
for (auto& n : notes) n.end = std::min(n.end, song_end);
// One step lasts tempo * 6554 / 1193180 s; a quarter is four steps.
const auto usec = std::uint32_t(std::lround(4.0 * timing.tempo * 6554.0 / 1193180.0 * 1e6));
const std::uint32_t loop_start = timing.repeat * 16u * kTicksPerStep;
const std::uint32_t loop_end = timing.end == timing.repeat ? loop_start : timing.end * 16u * kTicksPerStep;
// Defaults for everything the map file leaves open (§ guess_program/guess_drum):
// per instrument the mean note and the share of notes that start together with
// another note of the same instrument (chords); per sample its sound.
struct Usage { std::size_t notes{}, chord{}; double sum{}; int low{127}, high{0}; };
std::array<Usage, 256> usage{};
for (const auto& notes : tracks)
for (std::size_t i = 0; i < notes.size(); ++i) {
const auto& n = notes[i];
if (n.sample) continue;
auto& u = usage[n.instrument];
++u.notes; u.sum += n.note; u.low = std::min<int>(u.low, n.note); u.high = std::max<int>(u.high, n.note);
}
for (const auto& a : tracks) for (const auto& n : a) {
if (n.sample) continue;
bool together = false;
for (const auto& b : tracks) for (const auto& m : b)
if (&m != &n && !m.sample && m.instrument == n.instrument && m.start == n.start) { together = true; break; }
if (together) ++usage[n.instrument].chord;
}
Container container;
std::span<const std::uint8_t> samp;
if (parse_container(bank, container, error))
for (const auto& c : container.chunks)
if (c.id == "SAMP") samp = std::span<const std::uint8_t>(bank).subspan(c.payload_offset, c.payload_size);
for (unsigned i = 0; i < 256; ++i) {
if (used_instrument[i] && map.program[i] < 0) {
const auto& u = usage[i];
map.program[i] = guess_program(u.notes ? u.sum / u.notes : 60.0, u.notes ? double(u.chord) / u.notes : 0.0);
}
if (used_sample[i] && map.drum[i] < 0) {
PcmSample pcm;
map.drum[i] = !samp.empty() && decode_sample(samp, i, pcm, error) ? guess_drum(pcm) : 38;
}
}
if (!write_midi(output, tracks, map, usec, loop_start, loop_end, error)) { std::cerr << error << '\n'; return 1; }
auto template_path = output;
template_path += ".map.txt";
std::ofstream list(template_path);
list << "# OpenBMH MIDI map for song " << song << ": edit and pass with --map FILE\n"
<< "# inst <instrument> <General MIDI program 0..127>, sample <slot> <drum note>\n";
for (unsigned i = 0; i < 256; ++i) if (used_instrument[i]) {
const auto& u = usage[i];
list << "inst " << i << ' ' << map.program[i] << " # " << u.notes << " notes, range " << u.low << '-'
<< u.high << ", chords " << (u.notes ? 100 * u.chord / u.notes : 0) << "%\n";
}
for (unsigned i = 0; i < 256; ++i) if (used_sample[i]) list << "sample " << i << ' ' << map.drum[i] << '\n';
std::size_t notes = 0;
for (const auto& t : tracks) notes += t.size();
std::cout << "exported Original song=" << song << " midi notes=" << notes << " tempo_us=" << usec
<< " loops=" << completed_loops << " map=" << template_path.string() << '\n';
return 0;
}
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-midi 0..2 OUTPUT.mid [--loops 1..16] [--map FILE]\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";
@@ -359,24 +88,6 @@ int original_driver(int argc, char** argv) {
};
if (argc < 4) return usage();
const std::string action = argv[3];
if (action == "--export-midi") {
unsigned song = 0, loops = 1;
std::filesystem::path map;
if (argc < 6 || !bounded_number(argv[4], 0, 2, song)) return usage();
for (int at = 6; at < argc; at += 2) {
if (at + 1 >= argc) return usage();
const std::string option = argv[at];
if (option == "--loops") {
if (!bounded_number(argv[at + 1], 1, 16, loops)) return usage();
} else if (option == "--map") map = argv[at + 1];
else return usage();
}
try {
return export_midi(load_original_assets(argv[2]), song, argv[5], loops, map);
} catch (const std::exception& error) {
std::cerr << "Original audio input: " << error.what() << '\n'; return 1;
}
}
const bool song = action == "--export-song";
const bool export_id = action == "--export-id";
const bool play = action == "--play-id";
@@ -469,7 +180,6 @@ int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << "usage: openbmh_sound <container-file> [--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-midi 0..2 OUTPUT.mid [--loops N] [--map FILE]\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"
+1 -3
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#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
@@ -187,8 +186,7 @@ void Console::register_info_commands() {
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),
bool(content::find(options_.data)));
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);
+3 -7
View File
@@ -5,7 +5,6 @@
#include <algorithm>
#include "formats/content.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "ui/cup_draw.hpp"
@@ -397,8 +396,7 @@ 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 += content::find(options_.data) ? ".obs" : ".FBM";
if (!path.has_extension()) path += ".FBM";
return path;
}
@@ -412,8 +410,7 @@ void Console::register_file_commands() {
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()) ==
(content::find(options_.data) ? ".obs" : ".fbm"))
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());
@@ -466,8 +463,7 @@ void Console::register_file_commands() {
void Console::load_game(const std::filesystem::path& requested) {
std::filesystem::path path = requested;
if (!path.has_extension())
path += content::find(options_.data) ? ".obs" : ".FBM";
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<app::CareerSession> loaded;
+23 -64
View File
@@ -32,9 +32,6 @@
#include "launch/archive.hpp"
#include "launch/game_data.hpp"
#include "content/package.hpp"
#include "launch/process.hpp"
#include "launch/mods.hpp"
#include "version.hpp"
namespace {
@@ -86,8 +83,7 @@ Arguments parse_args(int argc, char** argv) {
std::exit(0);
}
if (arg == "--help" || arg == "-h") args.help = true;
else if (arg == "--data" || arg == "--mod")
args.data = bmh::launch::path_from_utf8(next(arg));
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;
@@ -120,26 +116,21 @@ Arguments parse_args(int argc, char** argv) {
}
void print_usage() {
std::cout
<< "openbmh_cli --mod <content.obw> [--seed <n>] [--text|--json] [--log <jsonl>]\n"
"openbmh_cli --replay <jsonl> [--mod <content.obw>] [--text|--json]\n"
"openbmh_cli --console --mod <content.obw> [--saves <dir>] [--seed <n>] [--text|--json] [--echo]\n"
" [--log|--replay <jsonl> [--keep-going]] [--serve <dir> | --listen <port>] [--seats "
"N]\n"
" --listen: the console on 127.0.0.1:<port>, 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 <dir>/seat<k> per manager; a request \"WaitTurn\" waits for k's turn.\n"
" --resume <jsonl>: with --seats, first play an earlier session log again, then go on.\n"
"openbmh_cli --send <dir> [--timeout <seconds>] (the block on stdin)\n"
" --serve: the session answers blocks dropped into <dir> (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 <master_club> <manager_name> [strength], load/save <path>, kickoff, status, desk, "
"quit\n";
std::cout << "openbmh_cli --data <BMH directory> [--seed <n>] [--text|--json] [--log <jsonl>]\n"
"openbmh_cli --replay <jsonl> [--data <BMH directory>] [--text|--json]\n"
"openbmh_cli --console --data <BMH directory> [--saves <dir>] [--seed <n>] [--text|--json] [--echo]\n"
" [--log|--replay <jsonl> [--keep-going]] [--serve <dir> | --listen <port>] [--seats N]\n"
" --listen: the console on 127.0.0.1:<port>, 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 <dir>/seat<k> per manager; a request \"WaitTurn\" waits for k's turn.\n"
" --resume <jsonl>: with --seats, first play an earlier session log again, then go on.\n"
"openbmh_cli --send <dir> [--timeout <seconds>] (the block on stdin)\n"
" --serve: the session answers blocks dropped into <dir> (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 <master_club> <manager_name> [strength], load/save <path>, kickoff, status, desk, quit\n";
}
std::string command_line_response(const Json& response) {
@@ -719,46 +710,14 @@ int main(int argc, char** argv) {
Arguments args = parse_args(argc, argv);
if (args.help) { print_usage(); return 0; }
if (!args.send.empty()) return run_send(args);
// Replay and resumed sessions can supply their content/save paths in
// the log header. Resolve them before mounting or selecting defaults.
const auto &source_log = !args.replay.empty() ? args.replay : args.resume;
if (!source_log.empty()) {
std::ifstream input(source_log, std::ios::binary);
std::string line;
if (!input || !std::getline(input, line))
throw std::runtime_error("cannot_read_session_log_header");
const auto header = parse_json(line);
const auto *fields = header.object();
if (!fields || !fields->contains("type") || !fields->at("type").string() ||
*fields->at("type").string() != (args.console ? "openbmh_console_log" : "openbmh_cli_log"))
throw std::runtime_error("invalid_session_log_header");
if (args.data.empty()) {
if (!fields->contains("data") || !fields->at("data").string())
throw std::runtime_error("missing_session_content_path");
args.data = bmh::launch::path_from_utf8(*fields->at("data").string());
}
if (args.console && args.saves.empty() && fields->contains("saves") &&
fields->at("saves").string())
args.saves = bmh::launch::path_from_utf8(*fields->at("saves").string());
}
std::shared_ptr<const bmh::content::Classic> contents;
std::unique_ptr<bmh::content::Mount> mount;
// --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()) {
if (std::filesystem::is_directory(args.data))
args.data /= "content.obw";
contents = bmh::content::open(args.data);
mount = std::make_unique<bmh::content::Mount>(args.data, contents);
args.data = mount->root();
if (args.saves.empty()) {
bmh::launch::ModLibrary library(
bmh::launch::executable_path(bmh::launch::path_from_utf8(argv[0])).parent_path());
bmh::launch::ModEntry mod;
mod.content_id = contents->content_id;
args.saves = library.user_directory(mod);
}
} else
throw std::runtime_error(
"0.2 requires --mod <content.obw>; import installations in OpenBMH first");
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);
-63
View File
@@ -1,63 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/digest.hpp"
#include <array>
#include <bit>
#include <cstdint>
#include <vector>
namespace bmh::content {
std::string sha256(std::string_view input) {
constexpr std::array<uint32_t, 64> k{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
std::array<uint32_t, 8> h{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
std::vector<uint8_t> data(input.begin(), input.end());
const uint64_t bits = uint64_t(data.size()) * 8;
data.push_back(0x80);
while (data.size() % 64 != 56)
data.push_back(0);
for (int i = 7; i >= 0; --i)
data.push_back(uint8_t(bits >> (8 * i)));
for (size_t offset = 0; offset < data.size(); offset += 64) {
std::array<uint32_t, 64> w{};
for (size_t i = 0; i < 16; ++i)
for (size_t j = 0; j < 4; ++j)
w[i] = (w[i] << 8) | data[offset + 4 * i + j];
for (size_t i = 16; i < 64; ++i) {
const auto a = w[i - 15], b = w[i - 2];
w[i] = w[i - 16] + (std::rotr(a, 7) ^ std::rotr(a, 18) ^ (a >> 3)) + w[i - 7] +
(std::rotr(b, 17) ^ std::rotr(b, 19) ^ (b >> 10));
}
auto [a, b, c, d, e, f, g, v] = h;
for (size_t i = 0; i < 64; ++i) {
const auto t = v + (std::rotr(e, 6) ^ std::rotr(e, 11) ^ std::rotr(e, 25)) +
((e & f) ^ (~e & g)) + k[i] + w[i];
const auto u =
(std::rotr(a, 2) ^ std::rotr(a, 13) ^ std::rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
v = g;
g = f;
f = e;
e = d + t;
d = c;
c = b;
b = a;
a = t + u;
}
const std::array<uint32_t, 8> work{a, b, c, d, e, f, g, v};
for (size_t i = 0; i < 8; ++i)
h[i] += work[i];
}
constexpr char digits[] = "0123456789abcdef";
std::string result;
for (auto word : h)
for (int i = 7; i >= 0; --i)
result += digits[(word >> (4 * i)) & 15];
return result;
}
} // namespace bmh::content
-7
View File
@@ -1,7 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <string>
#include <string_view>
namespace bmh::content {
std::string sha256(std::string_view data);
}
-134
View File
@@ -1,134 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/package.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include <chrono>
#include <fstream>
namespace bmh::content {
namespace fs = std::filesystem;
using namespace obw::detail;
namespace {
constexpr const char *inventory = "x-classic/seal.json";
O hashes(const Documents &docs) {
O result;
for (const auto &[name, value] : docs)
if (name != inventory) {
if (!safe_path(name))
fail("invalid content entry");
result[name] = sha256(value);
}
return result;
}
std::string identity(const Documents &docs) {
auto entries = hashes(docs);
entries.erase("x-classic/inventory.json");
auto manifest = parse(docs, "manifest.json");
manifest.object()->erase("generator");
manifest.object()->erase("title");
entries["manifest.json"] = sha256(cli::dump_json(manifest));
return sha256(cli::dump_json(entries));
}
} // namespace
Documents read_archive(const fs::path &file) {
if (fs::is_symlink(fs::symlink_status(file)) || !fs::is_regular_file(file) ||
fs::file_size(file) > 128ull * 1024 * 1024)
fail("invalid native archive");
// The archive itself remains a real file when its path is a mounted asset root.
std::ifstream stream(file, std::ios::binary);
std::string input(size_t(fs::file_size(file)), '\0');
if (!stream.read(input.data(), std::streamsize(input.size())))
fail("cannot read native archive");
mz_zip_archive zip{};
if (!mz_zip_reader_init_mem(&zip, input.data(), input.size(), 0))
fail("invalid ZIP archive");
struct End {
mz_zip_archive *zip;
~End() { mz_zip_reader_end(zip); }
} end{&zip};
Documents out;
uint64_t total = 0;
const auto count = mz_zip_reader_get_num_files(&zip);
if (count > 8192)
fail("too many archive entries");
for (mz_uint i = 0; i < count; ++i) {
mz_zip_archive_file_stat stat{};
if (!mz_zip_reader_file_stat(&zip, i, &stat))
fail("cannot read entry metadata");
if (stat.m_is_directory)
continue;
const std::string name = stat.m_filename;
if (!safe_path(name) || stat.m_uncomp_size > 32ull * 1024 * 1024 ||
(total += stat.m_uncomp_size) > 128ull * 1024 * 1024)
fail("unsafe or oversized archive entry");
std::string value(size_t(stat.m_uncomp_size), '\0');
if (!mz_zip_reader_extract_to_mem(&zip, i, value.data(), value.size(), 0))
fail("damaged ZIP entry");
if (!out.emplace(name, std::move(value)).second)
fail("duplicate archive entry");
}
return out;
}
void write_archive(const Documents &out, const fs::path &file, bool overwrite) {
mz_zip_archive zip{};
if (!mz_zip_writer_init_heap(&zip, 0, 0))
fail("cannot initialize ZIP writer");
struct End {
mz_zip_archive *zip;
~End() { mz_zip_writer_end(zip); }
} end{&zip};
uint64_t total = 0;
if (out.size() > 8192)
fail("too many archive entries");
for (const auto &[name, data] : out) {
if (!safe_path(name) || data.size() > 32ull * 1024 * 1024 ||
(total += data.size()) > 128ull * 1024 * 1024)
fail("invalid archive size or path");
if (!mz_zip_writer_add_mem(&zip, name.c_str(), data.data(), data.size(), MZ_BEST_SPEED))
fail("cannot add ZIP entry");
}
void *buffer = nullptr;
size_t size = 0;
if (!mz_zip_writer_finalize_heap_archive(&zip, &buffer, &size))
fail("cannot finalize ZIP archive");
struct Free {
void *data;
~Free() { mz_free(data); }
} free{buffer};
write_atomic(file, std::string_view(static_cast<const char *>(buffer), size), overwrite);
}
std::string seal(Documents &docs) {
obw::validate(docs);
auto entries = hashes(docs);
const auto id = identity(docs);
put(docs, inventory,
O{{"schema", "classic-seal@1.0"}, {"content_id", id}, {"entries", std::move(entries)}});
return id;
}
std::string verify(const Documents &docs) {
const auto stored = parse(docs, inventory);
if (str(get(stored, "schema")) != "classic-seal@1.0")
fail("unsupported Classic seal");
const auto actual = hashes(docs);
const auto encoded = cli::dump_json(actual);
if (cli::dump_json(get(stored, "entries")) != encoded || str(get(stored, "content_id")) != identity(docs))
fail("Classic contents were changed; import the installation again");
return identity(docs);
}
std::shared_ptr<const Classic> open(const fs::path &path) {
auto docs = read_archive(path);
const auto id = verify(docs);
auto value = std::make_shared<Classic>(obw::load_classic(docs));
constexpr std::array<uint8_t, 9> german{18, 18, 18, 18, 18, 12, 12, 12, 12};
constexpr std::array<uint8_t, 9> english{20, 20, 20, 20, 10, 12, 12, 12, 12};
const auto &leagues = value->english ? english : german;
for (size_t i = 0; i < leagues.size(); ++i)
if (value->executable.u8(layout::LeagueSizes + uint32_t(i)) != leagues[i])
fail("Classic supports only the original BMH and Football Limited league structures");
value->content_id = id;
const auto manifest = parse(docs, "manifest.json");
value->start_year = std::stoi(str(get(manifest, "start_date")).substr(0, 4));
value->executable.set_display_start_year(value->start_year);
value->documents = std::move(docs);
return value;
}
} // namespace bmh::content
-15
View File
@@ -1,15 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/classic.hpp"
#include "content/digest.hpp"
#include "formats/native_file.hpp"
namespace bmh::content {
using Documents = obw::Documents;
// Generic bounded ZIP documents; format-specific validation belongs to its reader.
Documents read_archive(const std::filesystem::path &file);
void write_archive(const Documents &, const std::filesystem::path &, bool overwrite = false);
// Sealed Classic contents: hashes cover every entry, including the original importer inventory.
std::string seal(Documents &);
std::string verify(const Documents &);
std::shared_ptr<const Classic> open(const std::filesystem::path &);
} // namespace bmh::content
-263
View File
@@ -1,263 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/save.hpp"
#include "import/detail.hpp"
#include "game/save.hpp"
#include <limits>
#include <algorithm>
#include <bit>
namespace bmh::content {
using namespace obw::detail;
namespace {
J rng(uint32_t seed, uint64_t calls) { return O{{"seed", int64_t(seed)}, {"calls", std::to_string(calls)}}; }
uint64_t calls(const J &value) {
const auto s = str(get(value, "calls"));
size_t end = 0;
uint64_t n;
try {
n = std::stoull(s, &end);
} catch (...) {
fail("invalid random draw counter");
}
if (end != s.size() || s.empty() ||
!std::all_of(s.begin(), s.end(), [](unsigned char c) { return c >= '0' && c <= '9'; }))
fail("invalid random draw counter");
return n;
}
uint32_t seed(const J &value) {
const auto n = num(get(value, "seed"));
if (n < 0 || n > UINT32_MAX)
fail("invalid random seed");
return uint32_t(n);
}
Documents world_of(const Documents &docs) {
Documents world;
for (const auto &[name, value] : docs)
if (!name.starts_with("state/"))
world[name] = value;
world["manifest.json"] = docs.at("state/world-manifest.json");
return world;
}
} // namespace
namespace {
template <class T> J vector_json(const std::vector<T> &values) {
A rows;
for (auto value : values)
rows.emplace_back(int64_t(value));
return rows;
}
template <class T> void vector_json(const J &j, std::vector<T> &out) {
if (!j.array() || j.array()->size() > 1000000)
fail("invalid checkpoint array");
for (const auto &row : *j.array()) {
const auto n = num(row);
if (n < int64_t(std::numeric_limits<T>::min()) || n > int64_t(std::numeric_limits<T>::max()))
fail("checkpoint array value out of range");
out.push_back(T(n));
}
}
J group_json(const MatchGroup &g) {
O out;
#define FIELD(name) out[#name] = vector_json(g.name);
FIELD(desc)
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
FIELD(spectators) FIELD(log)
#undef FIELD
out["cup_addresses"] = A{int64_t(g.cup_result_address[0]), int64_t(g.cup_result_address[1])};
out["phase"] = g.phase;
out["ended"] = int64_t(g.ended);
out["kickoff_void_mask"] = int64_t(g.kickoff_void_mask);
return out;
}
MatchGroup group_json(const J &in) {
MatchGroup g;
#define FIELD(name) vector_json(get(in, #name), g.name);
FIELD(desc)
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
FIELD(spectators) FIELD(log)
#undef FIELD
const auto &at = arr(get(in, "cup_addresses"));
if (at.size() != 2)
fail("invalid cup addresses");
for (size_t i = 0; i < 2; ++i) {
const auto n = num(at[i]);
if (n < 0 || n > UINT32_MAX)
fail("invalid cup address");
g.cup_result_address[i] = uint32_t(n);
}
const auto phase = num(get(in, "phase")), ended = num(get(in, "ended")),
mask = num(get(in, "kickoff_void_mask"));
if (phase < 0 || phase > 1 || ended < 0 || ended > UINT32_MAX || mask < 0 || mask > UINT32_MAX)
fail("invalid match checkpoint");
g.phase = int(phase);
g.ended = uint32_t(ended);
g.kickoff_void_mask = uint32_t(mask);
if ((g.desc.size() != 0xc0 && g.desc.size() != 0xd0) || g.fixtures.size() % 2 || g.matches() > 32 ||
(!g.records.empty() && g.records.size() != size_t(g.matches()) * 18) ||
(!g.end_minute.empty() && g.end_minute.size() != size_t(g.matches())) ||
(!g.spectators.empty() && g.spectators.size() != size_t(g.matches())))
fail("invalid match dimensions");
return g;
}
J groups_json(const std::vector<MatchGroup> &groups) {
A rows;
for (const auto &group : groups)
rows.push_back(group_json(group));
return rows;
}
std::vector<MatchGroup> groups_json(const J &j) {
std::vector<MatchGroup> groups;
const auto &rows = arr(j);
if (rows.size() > 6)
fail("too many match groups");
for (const auto &row : rows)
groups.push_back(group_json(row));
return groups;
}
} // namespace
J driver_checkpoint(const TurnDriver &d) {
return O{{"schema", "classic-driver@1.0"},
{"stage", int(d.stage)},
{"calendar_entry", d.calendar_entry},
{"manager_position", d.manager_position},
{"next_event_id", std::to_string(d.next_event_id)},
{"loaded_matchday_resume", d.loaded_matchday_resume},
{"suppress_remaining_pre_match_offers", d.suppress_remaining_pre_match_offers},
{"national_nomination_desk", d.national_nomination_desk},
{"enable_national_nomination_desks", d.enable_national_nomination_desks},
{"groups", groups_json(d.groups)},
{"referee_source", vector_json(d.referee_source)},
{"referees", vector_json(d.referees)},
{"last_results", O{{"valid", d.last_results.valid},
{"date", int64_t(d.last_results.date)},
{"calendar_entry", d.last_results.calendar_entry},
{"matchday", d.last_results.matchday},
{"groups", groups_json(d.last_results.groups)},
{"tournament_name", vector_json(d.last_results.tournament_name)}}}};
}
void restore_driver(TurnDriver &d, const J &j) {
if (str(get(j, "schema")) != "classic-driver@1.0")
fail("unsupported driver checkpoint");
const auto stage = num(get(j, "stage"));
const auto position = num(get(j, "manager_position"));
const auto entry = num(get(j, "calendar_entry"));
if (stage < 0 || stage > 2 || position < 0 || position > 4 || entry < 0 || entry > UINT16_MAX)
fail("invalid saved desk cursor");
d.stage = TurnDriver::Stage(stage);
d.manager_position = int(position);
d.calendar_entry = uint16_t(entry);
const auto flag = [](const J &value, const char *name) {
const auto &b = get(value, name);
if (!b.boolean())
fail("invalid driver flag");
return *b.boolean();
};
d.loaded_matchday_resume = flag(j, "loaded_matchday_resume");
d.suppress_remaining_pre_match_offers = flag(j, "suppress_remaining_pre_match_offers");
d.national_nomination_desk = flag(j, "national_nomination_desk");
d.enable_national_nomination_desks = flag(j, "enable_national_nomination_desks");
J counter = O{{"calls", get(j, "next_event_id")}};
d.next_event_id = calls(counter);
d.groups = groups_json(get(j, "groups"));
d.referee_source.clear();
d.referees.clear();
vector_json(get(j, "referee_source"), d.referee_source);
vector_json(get(j, "referees"), d.referees);
const auto &last = get(j, "last_results");
d.last_results.valid = flag(last, "valid");
const auto date = num(get(last, "date")), calendar = num(get(last, "calendar_entry")),
matchday = num(get(last, "matchday"));
if (date < 0 || date > UINT32_MAX || calendar < 0 || calendar > UINT16_MAX || matchday < 0 ||
matchday > UINT16_MAX)
fail("invalid result snapshot");
d.last_results.date = uint32_t(date);
d.last_results.calendar_entry = uint16_t(calendar);
d.last_results.matchday = uint16_t(matchday);
d.last_results.groups = groups_json(get(last, "groups"));
d.last_results.tournament_name.clear();
vector_json(get(last, "tournament_name"), d.last_results.tournament_name);
}
void save_career(const std::filesystem::path &path, const Classic &content, const GameState &state,
const WatcomRandom &random, const GameRandom &game, const TurnDriver &driver, bool overwrite,
const J &session) {
if (driver.stage != TurnDriver::Stage::Empty && driver.stage != TurnDriver::Stage::MatchdayDesks &&
driver.stage != TurnDriver::Stage::SeasonEndDesk)
fail("save unavailable outside a manager desk");
Documents docs = content.documents;
if (verify(docs) != content.content_id)
fail("invalid content identity");
docs["state/world-manifest.json"] = docs.at("manifest.json");
auto manifest = parse(docs, "manifest.json");
(*manifest.object())["kind"] = "save";
(*manifest.object())["save_profile"] = "classic-career-v1";
(*manifest.object())["content_id"] = content.content_id;
put(docs, "manifest.json", std::move(manifest));
put(docs, "state/career.json", encode_native_state(state));
put(docs, "state/rng.json",
O{{"schema", "classic-rng@1.0"},
{"watcom", rng(random.seed(), random.calls())},
{"game", rng(uint32_t(game.seed()), game.calls())}});
put(docs, "state/session.json", session);
put(docs, "state/driver.json", driver_checkpoint(driver));
put(docs, "state/information.json", encode_native_bytes(save_header(state)));
O checks;
for (const auto &[name, value] : docs)
if (name.starts_with("state/"))
checks[name] = sha256(value);
put(docs, "state/integrity.json", O{{"schema", "save-integrity@1.0"}, {"entries", std::move(checks)}});
write_archive(docs, path, overwrite);
}
SavedCareer load_career(const std::filesystem::path &path, const Classic &content) {
const auto docs = read_archive(path);
const auto manifest = parse(docs, "manifest.json");
if (str(get(manifest, "kind")) != "save" || str(get(manifest, "save_profile")) != "classic-career-v1" ||
str(get(manifest, "content_id")) != content.content_id)
fail("save belongs to another mod or format");
const auto integrity = parse(docs, "state/integrity.json");
if (str(get(integrity, "schema")) != "save-integrity@1.0")
fail("unsupported save integrity");
O checks;
for (const auto &[name, value] : docs)
if (name.starts_with("state/") && name != "state/integrity.json")
checks[name] = sha256(value);
if (cli::dump_json(get(integrity, "entries")) != cli::dump_json(checks))
fail("damaged native save");
const auto world = world_of(docs);
if (verify(world) != content.content_id)
fail("save world contents changed");
SavedCareer out;
out.state = decode_native_state(parse(docs, "state/career.json"));
if (out.state.players.size() != content.database.players.size() ||
out.state.club_ids.size() != content.database.club_names.size() ||
out.state.manager_records.size() != 5 * 0xb0c)
fail("native state does not match Classic dimensions");
const auto generators = parse(docs, "state/rng.json");
if (str(get(generators, "schema")) != "classic-rng@1.0")
fail("unsupported RNG checkpoint");
const auto &w = get(generators, "watcom");
const auto &g = get(generators, "game");
out.random.restore(seed(w), calls(w));
out.game.restore(std::bit_cast<int32_t>(seed(g)), calls(g));
out.session = parse(docs, "state/session.json");
out.driver = parse(docs, "state/driver.json");
out.header = decode_native_bytes(parse(docs, "state/information.json"), 172);
return out;
}
Bytes save_information(const std::filesystem::path &path) {
const auto docs = read_archive(path);
return decode_native_bytes(parse(docs, "state/information.json"), 172);
}
Bytes load_preferences(const std::filesystem::path &path, const char *kind, size_t size) {
const auto b = read_file(path);
const auto root = cli::parse_json(std::string(b.begin(), b.end()));
if (str(get(root, "schema")) != std::string("classic-") + kind + "@1.0")
fail("unsupported preferences");
return decode_native_bytes(get(root, "payload"), size);
}
void save_preferences(const std::filesystem::path &path, const char *kind, const Bytes &b, bool overwrite) {
write_atomic(path,
cli::dump_json(O{{"schema", std::string("classic-") + kind + "@1.0"},
{"payload", encode_native_bytes(b)}}) +
"\n",
overwrite);
}
} // namespace bmh::content
-23
View File
@@ -1,23 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "content/package.hpp"
#include "formats/native_state.hpp"
#include "game/turn_driver.hpp"
namespace bmh::content {
struct SavedCareer {
GameState state;
WatcomRandom random;
GameRandom game;
cli::Json driver, session;
Bytes header;
};
void save_career(const std::filesystem::path &, const Classic &, const GameState &, const WatcomRandom &,
const GameRandom &, const TurnDriver &, bool overwrite, const cli::Json &session = {});
SavedCareer load_career(const std::filesystem::path &, const Classic &);
Bytes save_information(const std::filesystem::path &);
cli::Json driver_checkpoint(const TurnDriver &);
void restore_driver(TurnDriver &, const cli::Json &);
// Native settings/layout files retain the validated Classic bytes with a typed envelope.
Bytes load_preferences(const std::filesystem::path &, const char *kind, size_t size);
void save_preferences(const std::filesystem::path &, const char *kind, const Bytes &, bool overwrite);
} // namespace bmh::content
-118
View File
@@ -1,118 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-only
include(FetchContent)
set(OPENBMH_EDITOR_VERSION "0.5.5")
file(WRITE "${CMAKE_BINARY_DIR}/editor-version.json" "{\"version\": \"${OPENBMH_EDITOR_VERSION}\"}\n")
set(JSON_BuildTests OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_json GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.12.0 GIT_SHALLOW TRUE)
FetchContent_Declare(editor_http GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
GIT_TAG v0.63.0 GIT_SHALLOW TRUE SOURCE_SUBDIR no-cmake)
set(SDL2IMAGE_INSTALL OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_SAMPLES OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_TESTS OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_VENDORED ON CACHE BOOL "" FORCE)
set(SDL2IMAGE_DEPS_SHARED OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_BACKEND_STB ON CACHE BOOL "" FORCE)
set(SDL2IMAGE_BACKEND_IMAGEIO OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_BACKEND_WIC OFF CACHE BOOL "" FORCE)
foreach(codec AVIF BMP GIF JXL LBM PCX PNM QOI SVG TIF XCF XPM XV)
set(SDL2IMAGE_${codec} OFF CACHE BOOL "" FORCE)
endforeach()
set(SDL2IMAGE_PNG ON CACHE BOOL "" FORCE)
set(SDL2IMAGE_JPG ON CACHE BOOL "" FORCE)
set(SDL2IMAGE_WEBP ON CACHE BOOL "" FORCE)
if(MSVC)
set(WEBP_ENABLE_SIMD ON CACHE BOOL "Use WebP's runtime CPU selection" FORCE)
endif()
set(SDL2IMAGE_PNG_SAVE OFF CACHE BOOL "" FORCE)
set(SDL2IMAGE_JPG_SAVE OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_images GIT_REPOSITORY https://github.com/libsdl-org/SDL_image.git
GIT_TAG release-2.8.8 GIT_SHALLOW TRUE GIT_SUBMODULES external/libwebp)
set(LUNASVG_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_svg GIT_REPOSITORY https://github.com/sammycage/lunasvg.git
GIT_TAG v3.5.0 GIT_SHALLOW TRUE)
set(PUGIXML_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(PUGIXML_BUILD_SHARED_AND_STATIC_LIBS OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_xml GIT_REPOSITORY https://github.com/zeux/pugixml.git
GIT_TAG v1.15 GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(editor_json editor_http editor_images editor_svg editor_xml)
if(MSVC)
# The pinned WebP CMake propagates /arch:AVX into SSE2 source files, even
# though their runtime gate only checks SSE2. Compile its explicit SSE
# intrinsics at the default x64 baseline, preserving CPU dispatch and all
# upstream sources. Disabling SIMD is broken in this pinned MSVC build.
get_target_property(webp_source_directory webpdsp SOURCE_DIR)
get_target_property(webp_dsp_sources webpdsp SOURCES)
foreach(source IN LISTS webp_dsp_sources)
if(source MATCHES "_sse(2|41)\\.c$")
set_source_files_properties("${source}" DIRECTORY "${webp_source_directory}"
PROPERTIES COMPILE_FLAGS "")
endif()
endforeach()
endif()
file(WRITE "${CMAKE_BINARY_DIR}/editor-dependencies.json" "{\n")
foreach(component editor_json editor_http editor_images editor_svg editor_xml)
file(TO_CMAKE_PATH "${${component}_SOURCE_DIR}" component_path)
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "\"${component}\": \"${component_path}\"")
if(NOT component STREQUAL "editor_xml")
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" ",")
endif()
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "\n")
endforeach()
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n")
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp comparison.cpp regulations.cpp images.cpp options.cpp mcp.cpp)
target_compile_definitions(bmh_editor_core PUBLIC OPENBMH_EDITOR_VERSION="${OPENBMH_EDITOR_VERSION}")
target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR})
target_link_libraries(bmh_editor_core PUBLIC nlohmann_json::nlohmann_json bmh_content
PRIVATE bmh_miniz ${BMH_SDL_TARGET} SDL2_image::SDL2_image-static lunasvg::lunasvg pugixml::pugixml)
find_package(Threads REQUIRED)
target_link_libraries(bmh_editor_core PUBLIC Threads::Threads)
if(WIN32)
target_link_libraries(bmh_editor_core PRIVATE ws2_32 crypt32)
endif()
add_executable(openbmh_editor main.cpp ui.cpp)
set_target_properties(openbmh_editor PROPERTIES OUTPUT_NAME OpenBMHEditor
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
target_link_libraries(openbmh_editor PRIVATE bmh_editor_core bmh_rmlui nfd::nfd ${BMH_SDL_TARGET})
if(MSVC)
target_compile_options(bmh_editor_core PRIVATE /W4 /utf-8)
target_compile_options(openbmh_editor PRIVATE /utf-8)
else()
target_compile_options(bmh_editor_core PRIVATE -Wall -Wextra -Wpedantic)
endif()
if(WIN32)
set_target_properties(openbmh_editor PROPERTIES WIN32_EXECUTABLE TRUE)
endif()
set(editor_assets "${CMAKE_BINARY_DIR}/assets/editor")
FetchContent_GetProperties(rmlui)
file(MAKE_DIRECTORY "${editor_assets}")
foreach(asset editor.rml theme.rcss)
configure_file("${CMAKE_SOURCE_DIR}/assets/editor/${asset}" "${editor_assets}/${asset}" COPYONLY)
endforeach()
foreach(weight Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${editor_assets}/LatoLatin-${weight}.ttf" COPYONLY)
endforeach()
install(TARGETS openbmh_editor RUNTIME DESTINATION . COMPONENT Editor)
install(DIRECTORY "${editor_assets}/" DESTINATION assets/editor COMPONENT Editor)
add_executable(editor_core_tests ../../tests/editor_core_tests.cpp)
target_link_libraries(editor_core_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_core_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_core_tests COMMAND editor_core_tests)
add_executable(editor_comparison_tests ../../tests/editor_comparison_tests.cpp)
target_link_libraries(editor_comparison_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_comparison_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_comparison_tests COMMAND editor_comparison_tests)
add_executable(editor_regulations_tests ../../tests/editor_regulations_tests.cpp)
target_link_libraries(editor_regulations_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_regulations_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_regulations_tests COMMAND editor_regulations_tests)
add_test(NAME editor_version COMMAND openbmh_editor --version)
set_tests_properties(editor_version PROPERTIES PASS_REGULAR_EXPRESSION "OpenBMH Editor ${OPENBMH_EDITOR_VERSION}")
-326
View File
@@ -1,326 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/archive.hpp"
#include "content/digest.hpp"
#include <algorithm>
#include <chrono>
#include <cwctype>
#include <fstream>
#include <miniz.h>
#include <mutex>
#include <random>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
namespace bmh::editor {
namespace {
constexpr uint64_t max_entry = 64ull * 1024 * 1024;
constexpr uint64_t max_total = 2ull * 1024 * 1024 * 1024;
constexpr size_t max_entries = 100000;
void publish(const fs::path &temporary, const fs::path &destination) {
#ifdef _WIN32
if (!MoveFileExW(temporary.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
throw Error("save_failed", {{"path", utf8(destination)}, {"system", GetLastError()}});
#else
std::error_code ec;
fs::rename(temporary, destination, ec);
if (ec)
throw Error("save_failed", {{"path", utf8(destination)}, {"system", ec.message()}});
#endif
}
struct Remove {
fs::path target;
~Remove() {
if (!target.empty()) {
std::error_code ec;
fs::remove_all(target, ec);
}
}
};
} // namespace
std::string utf8(const fs::path &value) {
const auto data = value.generic_u8string();
return {data.begin(), data.end()};
}
fs::path path(std::string_view value) { return fs::path(std::u8string(value.begin(), value.end())); }
bool safe_name(std::string_view value) {
if (value.empty() || value.front() == '/' || value.find('\\') != value.npos || value.find(':') != value.npos ||
value.find('\0') != value.npos || value.back() == '/')
return false;
const auto relative = path(value);
for (const auto &part : relative)
if (part == "." || part == ".." || part.empty())
return false;
return !relative.is_absolute();
}
std::string new_id(const std::string &prefix) {
static std::mutex lock;
static std::mt19937_64 random(std::random_device{}());
std::lock_guard guard(lock);
static const char *digits = "0123456789abcdef";
std::string result = prefix;
for (int n = 0; n < 2; ++n) {
auto number = random();
for (int i = 0; i < 16; ++i) {
result += digits[number & 15];
number >>= 4;
}
}
return result;
}
std::string folded(std::string value) {
// UTF-8 byte equality is retained; the small UI search additionally handles
// ASCII case without changing authored spelling or source identity.
for (char &c : value)
if (c >= 'A' && c <= 'Z')
c = char(c + ('a' - 'A'));
return value;
}
std::string read_file(const fs::path &file, uint64_t maximum) {
std::ifstream source(file, std::ios::binary);
if (!source)
throw Error("open_failed", {{"path", utf8(file)}});
source.seekg(0, std::ios::end);
auto size = source.tellg();
if (size < 0 || uint64_t(size) > maximum)
throw Error("size_limit", {{"path", utf8(file)}});
source.seekg(0);
std::string bytes(size_t(size), '\0');
source.read(bytes.data(), std::streamsize(bytes.size()));
if (!source && !bytes.empty())
throw Error("open_failed", {{"path", utf8(file)}});
return bytes;
}
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
if (!overwrite && fs::exists(file))
throw Error("destination_exists");
if (fs::is_symlink(fs::symlink_status(file)))
throw Error("unsafe_path");
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
throw Error("output_parent_missing");
auto temporary = parent / new_id(".openbmh-editor-");
Remove cleanup{temporary};
{
std::ofstream output(temporary, std::ios::binary);
output.write(data.data(), std::streamsize(data.size()));
output.close();
if (!output)
throw Error("save_failed");
}
publish(temporary, file);
}
struct ArchiveStore::Impl {
fs::path cache;
fs::path root;
mutable std::ifstream input;
mutable mz_zip_archive zip{};
struct Item {
uint64_t size;
mz_uint index;
fs::path file;
};
std::map<std::string, Item> entries;
std::map<std::string, std::shared_ptr<const std::string>> changed;
mutable std::mutex mutex;
bool zip_open = false;
static size_t read_at(void *opaque, mz_uint64 offset, void *data, size_t count) {
auto &in = static_cast<Impl *>(opaque)->input;
in.clear();
in.seekg(std::streamoff(offset));
in.read(static_cast<char *>(data), std::streamsize(count));
return size_t(in.gcount());
}
~Impl() {
if (zip_open)
mz_zip_reader_end(&zip);
input.close();
if (!cache.empty()) {
std::error_code ec;
fs::remove_all(cache, ec);
}
}
};
ArchiveStore::ArchiveStore() : impl_(std::make_unique<Impl>()) {}
ArchiveStore::~ArchiveStore() = default;
std::shared_ptr<ArchiveStore> ArchiveStore::open(const fs::path &source) {
auto result = std::make_shared<ArchiveStore>();
auto &s = *result->impl_;
uint64_t total = 0;
auto add = [&](std::string name, Impl::Item item) {
if (!safe_name(name) || item.size > max_entry || total + item.size > max_total ||
s.entries.size() >= max_entries)
throw Error("archive_limit", {{"entry", name}});
if (!s.entries.emplace(name, std::move(item)).second)
throw Error("duplicate_entry", {{"entry", name}});
total += item.size;
};
if (fs::is_symlink(fs::symlink_status(source)))
throw Error("unsafe_path");
if (fs::is_directory(source)) {
const auto original = fs::canonical(source);
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
s.root = s.cache / "world";
fs::create_directories(s.root);
for (const auto &entry : fs::recursive_directory_iterator(original)) {
if (entry.is_symlink())
throw Error("unsafe_path");
if (entry.is_regular_file()) {
const auto relative = entry.path().lexically_relative(original);
const auto snapshot = s.root / relative;
add(utf8(relative), {entry.file_size(), 0, snapshot});
fs::create_directories(snapshot.parent_path());
fs::copy_file(entry.path(), snapshot);
}
}
} else {
if (!fs::is_regular_file(source) || fs::file_size(source) > max_total)
throw Error("archive_limit");
s.cache = fs::temp_directory_path() / new_id("openbmh-editor-");
fs::create_directory(s.cache);
const auto snapshot = s.cache / "source.obw";
fs::copy_file(source, snapshot);
s.input.open(snapshot, std::ios::binary);
s.zip.m_pRead = Impl::read_at;
s.zip.m_pIO_opaque = &s;
if (!mz_zip_reader_init(&s.zip, fs::file_size(snapshot), 0))
throw Error("invalid_archive");
s.zip_open = true;
auto count = mz_zip_reader_get_num_files(&s.zip);
if (count > max_entries)
throw Error("archive_limit");
for (mz_uint index = 0; index < count; ++index) {
mz_zip_archive_file_stat stat{};
if (!mz_zip_reader_file_stat(&s.zip, index, &stat))
throw Error("invalid_archive");
if (stat.m_is_directory)
continue;
if (((stat.m_external_attr >> 16) & 0170000) == 0120000)
throw Error("unsafe_path");
if (stat.m_is_encrypted || !stat.m_is_supported)
throw Error("unsupported_archive");
add(stat.m_filename, {stat.m_uncomp_size, index, {}});
}
}
if (!s.entries.contains("manifest.json"))
throw Error("missing_manifest");
return result;
}
bool ArchiveStore::contains(const std::string &name) const {
return impl_->changed.contains(name) || impl_->entries.contains(name);
}
std::vector<std::string> ArchiveStore::names() const {
std::set<std::string> all;
for (const auto &[key, _] : impl_->entries)
all.insert(key);
for (const auto &[key, _] : impl_->changed)
all.insert(key);
return {all.begin(), all.end()};
}
uint64_t ArchiveStore::size(const std::string &name) const {
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
return i->second->size();
if (auto i = impl_->entries.find(name); i != impl_->entries.end())
return i->second.size;
throw Error("missing_asset", {{"path", name}});
}
std::string ArchiveStore::read(const std::string &name) const {
if (auto i = impl_->changed.find(name); i != impl_->changed.end())
return *i->second;
const auto entry = impl_->entries.find(name);
if (entry == impl_->entries.end())
throw Error("missing_asset", {{"path", name}});
if (!entry->second.file.empty()) {
if (fs::is_symlink(fs::symlink_status(entry->second.file)))
throw Error("unsafe_path");
return read_file(entry->second.file, max_entry);
}
std::lock_guard guard(impl_->mutex);
std::string bytes(size_t(entry->second.size), '\0');
if (!mz_zip_reader_extract_to_mem(&impl_->zip, entry->second.index, bytes.data(), bytes.size(), 0))
throw Error("invalid_archive", {{"entry", name}});
return bytes;
}
void ArchiveStore::set(const std::string &name, std::shared_ptr<const std::string> bytes) {
if (!safe_name(name) || !bytes || bytes->size() > max_entry)
throw Error("unsafe_asset");
impl_->changed[name] = std::move(bytes);
}
std::shared_ptr<const std::string> ArchiveStore::overlay(const std::string &name) const {
auto i = impl_->changed.find(name);
return i == impl_->changed.end() ? nullptr : i->second;
}
void ArchiveStore::restore(const std::string &name, std::shared_ptr<const std::string> value) {
if (value)
set(name, std::move(value));
else
impl_->changed.erase(name);
}
void ArchiveStore::save(const fs::path &target, const std::map<std::string, std::string> &docs,
const std::set<std::string> &excluded) const {
if (target.extension() != ".obw")
throw Error("obw_only");
if (fs::is_symlink(fs::symlink_status(target)))
throw Error("unsafe_path");
auto parent = target.has_parent_path() ? target.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
throw Error("output_parent_missing");
auto temporary = parent / new_id(".openbmh-editor-");
Remove cleanup{temporary};
std::ofstream output(temporary, std::ios::binary);
if (!output)
throw Error("save_failed");
mz_zip_archive writer{};
writer.m_pIO_opaque = &output;
writer.m_pWrite = [](void *opaque, mz_uint64 position, const void *data, size_t count) -> size_t {
auto &stream = *static_cast<std::ofstream *>(opaque);
stream.seekp(std::streamoff(position));
stream.write(static_cast<const char *>(data), std::streamsize(count));
return stream ? count : 0;
};
if (!mz_zip_writer_init_v2(&writer, 0, MZ_ZIP_FLAG_WRITE_ZIP64))
throw Error("save_failed");
struct Close {
mz_zip_archive *p;
~Close() { mz_zip_writer_end(p); }
} closer{&writer};
std::set<std::string> all;
for (auto &name : names())
all.insert(name);
for (auto &[name, _] : docs)
all.insert(name);
if (all.size() > max_entries)
throw Error("archive_limit");
uint64_t total = 0;
for (const auto &name : all) {
if (excluded.contains(name))
continue;
if (!safe_name(name))
throw Error("unsafe_path");
auto replacement = docs.find(name);
const auto bytes_size = replacement != docs.end() ? replacement->second.size() : size(name);
if (bytes_size > max_entry || (total += bytes_size) > max_total)
throw Error("archive_limit");
auto existing = impl_->entries.find(name);
if (replacement == docs.end() && !impl_->changed.contains(name) && impl_->zip_open &&
existing != impl_->entries.end()) {
std::lock_guard guard(impl_->mutex);
if (!mz_zip_writer_add_from_zip_reader(&writer, &impl_->zip, existing->second.index))
throw Error("save_failed");
} else {
auto bytes = replacement != docs.end() ? replacement->second : read(name);
const auto level = name.ends_with(".json") ? MZ_BEST_SPEED : MZ_NO_COMPRESSION;
if (!mz_zip_writer_add_mem(&writer, name.c_str(), bytes.data(), bytes.size(), level))
throw Error("save_failed");
}
}
if (!mz_zip_writer_finalize_archive(&writer))
throw Error("save_failed");
output.close();
if (!output)
throw Error("save_failed");
publish(temporary, target);
}
} // namespace bmh::editor
-28
View File
@@ -1,28 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
#include <functional>
namespace bmh::editor {
// Asset bytes are read on demand. A private source snapshot permits replacing
// the user's own editor file atomically on Windows as well as POSIX systems.
class ArchiveStore {
public:
ArchiveStore();
static std::shared_ptr<ArchiveStore> open(const fs::path &);
~ArchiveStore();
bool contains(const std::string &) const;
std::vector<std::string> names() const;
uint64_t size(const std::string &) const;
std::string read(const std::string &) const;
void set(const std::string &, std::shared_ptr<const std::string>);
std::shared_ptr<const std::string> overlay(const std::string &) const;
void restore(const std::string &, std::shared_ptr<const std::string>);
void save(const fs::path &, const std::map<std::string, std::string> &documents,
const std::set<std::string> &excluded = {}) const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace bmh::editor
-307
View File
@@ -1,307 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/world.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
namespace bmh::editor {
namespace {
bool date_valid(const std::string &date) {
if (date.size() != 10 || date[4] != '-' || date[7] != '-')
return false;
for (size_t i = 0; i < date.size(); ++i)
if (i != 4 && i != 7 && (date[i] < '0' || date[i] > '9'))
return false;
if (std::stoi(date.substr(0, 4)) < 1583)
return false;
return std::chrono::year_month_day{std::chrono::year(std::stoi(date.substr(0, 4))),
std::chrono::month(unsigned(std::stoi(date.substr(5, 2)))),
std::chrono::day(unsigned(std::stoi(date.substr(8, 2))))}
.ok();
}
bool source_duplicate(const Json &player) {
const auto simulation = player.value("x-simulation", Json::object());
return str(simulation, "squad_role") == "source-only-duplicate";
}
std::optional<int64_t> money(const Json &value) {
if (!value.is_number_integer() ||
(value.is_number_unsigned() && value.get<uint64_t>() > uint64_t(std::numeric_limits<int64_t>::max())))
return {};
const auto number = value.get<int64_t>();
return number >= 0 ? std::optional<int64_t>(number) : std::nullopt;
}
struct Mean {
long double sum = 0;
size_t count = 0;
void add(const Json &value) {
if (value.is_number() && std::isfinite(value.get<double>())) {
sum += value.get<double>();
++count;
}
}
Json value() const { return count ? Json(double(sum / count)) : Json(); }
};
struct Group {
size_t players = 0, known = 0, ambiguous = 0;
int64_t salary = 0;
bool overflow = false;
std::map<std::string, Mean> attributes;
void add(const Json &player) {
++players;
for (auto it = player["attributes"].begin(); it != player["attributes"].end(); ++it)
attributes[it.key()].add(it.value());
ambiguous += player.value("salary_ambiguous", size_t(0));
if (const auto amount = money(player["salary"])) {
++known;
if (salary > std::numeric_limits<int64_t>::max() - *amount)
overflow = true;
else
salary += *amount;
}
}
void write(Json &row, const Json &fields) const {
row["player_count"] = players;
row["salary_known"] = known;
row["salary_unknown"] = players - known;
row["salary_ambiguous"] = ambiguous;
row["salary_overflow"] = overflow;
row["salary_complete"] = players > 0 && known == players && !overflow;
row["salary_total"] = known && !overflow ? Json(salary) : Json();
// Salaries remain integer minor units. Round the mean to the nearest
// minor unit without overflowing the sum or inventing unknown wages.
row["salary_average"] =
known && !overflow
? Json(salary / int64_t(known) + (salary % int64_t(known) >= int64_t((known + 1) / 2)))
: Json();
row["attributes"] = Json::object();
row["attribute_counts"] = Json::object();
for (const auto &field : fields) {
const auto key = str(field, "key");
const auto found = attributes.find(key);
row["attributes"][key] = found == attributes.end() ? Json() : found->second.value();
row["attribute_counts"][key] = found == attributes.end() ? 0 : found->second.count;
}
}
};
} // namespace
Json comparison_data(const World &world, const Json &args) {
const auto table = str(args, "table", "players"), language = str(args, "language", "de");
if (table != "players" && table != "clubs" && table != "leagues")
throw Error("unknown_table");
if (language != "de" && language != "en")
throw Error("invalid_change");
std::map<std::string, const Json *> clubs, leagues;
std::map<std::string, std::set<std::string>> memberships;
for (const auto &league : world.rows("competitions"))
if (str(league, "type") == "league") {
const auto id = str(league, "id");
leagues[id] = &league;
for (const auto &member : league.value("members", Json::array()))
if (member.is_string())
memberships[member.get<std::string>()].insert(id);
}
for (const auto &club : world.rows("clubs"))
clubs[str(club, "id")] = &club;
auto league_for = [&](const std::string &id) {
const auto comp = clubs.contains(id) ? str(*clubs.at(id), "competition") : "";
if (leagues.contains(comp))
return comp;
const auto found = memberships.find(id);
return found != memberships.end() && found->second.size() == 1 ? *found->second.begin()
: std::string();
};
std::map<std::string, size_t> sets;
size_t excluded = 0;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player)) {
++excluded;
continue;
}
++sets[str(player, "attribute_set")];
}
auto selected_set = str(args, "attribute_set");
if (!selected_set.empty() && !sets.contains(selected_set))
throw Error("invalid_attribute_set");
if (selected_set.empty() && sets.size() == 1)
selected_set = sets.begin()->first;
// Equal-looking numbers can have different meanings (FC physical strength
// versus Classic playing strength). Never average or sort mixed systems.
const bool mixed = selected_set.empty() && sets.size() > 1;
std::map<std::string, Json> fields;
if (!mixed) {
for (const auto &rule : world.rows("rules")) {
auto id = str(rule, "attribute_set", str(rule, "id"));
if (str(rule, "type") == "attribute_set" &&
(id == selected_set || id == "rule:" + selected_set)) {
const auto definitions = rule.value("fields", Json::object());
for (auto it = definitions.begin(); it != definitions.end(); ++it)
fields[it.key()] = {{"key", it.key()},
{"min", it.value().value("min", Json())},
{"max", it.value().value("max", Json())}};
}
}
for (const auto &player : world.rows("players"))
if (!source_duplicate(player) && str(player, "attribute_set") == selected_set) {
const auto attributes = player.value("attributes", Json::object());
for (auto it = attributes.begin(); it != attributes.end(); ++it)
if (it.value().is_number() && !fields.contains(it.key()))
fields[it.key()] = {{"key", it.key()}, {"min", nullptr}, {"max", nullptr}};
}
}
Json definitions = Json::array();
for (const auto &[_, field] : fields)
definitions.push_back(field);
Json available_sets = Json::array();
for (const auto &[id, count] : sets)
available_sets.push_back({{"id", id}, {"players", count}});
const auto date = str(world.manifest, "start_date");
std::map<std::pair<std::string, std::string>, std::vector<const Json *>> contracts;
if (date_valid(date))
for (const auto &contract : world.rows("contracts")) {
const auto start = str(contract, "start"), end = str(contract, "end");
// An absent date is an open bound. A malformed bound cannot be
// treated as evidence of an active employment contract.
const auto start_value = contract.value("start", Json()),
end_value = contract.value("end", Json());
if ((!start_value.is_null() && !start_value.is_string()) ||
(!end_value.is_null() && !end_value.is_string()) ||
(!start.empty() && (!date_valid(start) || start > date)) ||
(!end.empty() && (!date_valid(end) || end < date)))
continue;
contracts[{str(contract, "person"), str(contract, "team")}].push_back(&contract);
}
Json players = Json::array();
std::map<std::string, Group> club_groups, league_groups;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player) ||
(!selected_set.empty() && str(player, "attribute_set") != selected_set))
continue;
const auto id = str(player, "id"), team = str(player, "team"), league = league_for(team);
const auto *club = clubs.contains(team) ? clubs.at(team) : nullptr;
Json row{{"id", id},
{"name", world.title(player, language)},
{"team", team},
{"nation", club ? str(*club, "nation") : ""},
{"competition", league},
{"positions", player.value("positions", Json::array())},
{"attribute_set", str(player, "attribute_set")},
{"player_count", 1},
{"attributes", Json::object()},
{"salary", nullptr},
{"salary_ambiguous", 0}};
const auto attributes = player.value("attributes", Json::object());
for (const auto &[key, _] : fields) {
const auto value = attributes.value(key, Json());
row["attributes"][key] = value.is_number() && std::isfinite(value.get<double>()) ? value : Json();
}
if (!team.empty()) {
const auto found = contracts.find({id, team});
if (found != contracts.end()) {
if (found->second.size() == 1) {
const auto salary = money(found->second.front()->value("salary", Json()));
if (salary)
row["salary"] = *salary;
} else
row["salary_ambiguous"] = 1;
}
}
if (club)
club_groups[team].add(row);
if (!league.empty())
league_groups[league].add(row);
players.push_back(std::move(row));
}
Json rows = Json::array();
if (table == "players")
rows = std::move(players);
else if (table == "clubs") {
for (const auto &[id, club] : clubs) {
Json row{{"id", id},
{"name", world.title(*club, language)},
{"nation", str(*club, "nation")},
{"competition", league_for(id)}};
club_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
} else
for (const auto &[id, league] : leagues) {
Json row{{"id", id},
{"name", world.title(*league, language)},
{"nation", str(*league, "nation")},
{"competition", id},
{"club_count", 0}};
for (const auto &[club_id, _] : clubs)
if (league_for(club_id) == id)
row["club_count"] = row["club_count"].get<size_t>() + 1;
league_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
const auto simulation = world.manifest.value("x-simulation", Json());
return {{"table", table},
{"items", std::move(rows)},
{"attributes", definitions},
{"attribute_sets", available_sets},
{"attribute_set", selected_set},
{"mixed_attribute_sets", mixed},
{"currency", world.manifest.value("currency", Json())},
{"date", date},
{"excluded_players", excluded},
{"fictional_completion",
simulation.is_object() && simulation.value("fictional_completion", Json()) == true}};
}
Json query_comparison(const Json &data, const Json &args) {
const auto search = folded(str(args, "search")), nation = str(args, "nation"),
league = str(args, "competition"), team = str(args, "team"), sort = str(args, "sort", "name");
const bool descending = args.value("descending", false);
bool valid_sort = sort == "name" || sort == "salary" || sort == "salary_total" ||
sort == "salary_average" || sort == "player_count" || sort == "club_count" ||
sort == "salary_known";
for (const auto &field : data["attributes"])
valid_sort |= sort == "attributes." + str(field, "key");
if (!valid_sort)
throw Error("invalid_comparison_sort");
auto value = [&](const Json &row) {
if (sort == "name")
return Json(folded(str(row, "name")));
if (sort.starts_with("attributes."))
return row["attributes"].value(sort.substr(11), Json());
return row.value(sort, Json());
};
std::vector<const Json *> matches;
for (const auto &row : data["items"]) {
if ((!nation.empty() && str(row, "nation") != nation) ||
(!league.empty() && str(row, "competition") != league) ||
(!team.empty() && str(row, "team", str(row, "id")) != team) ||
(!search.empty() && folded(str(row, "name")).find(search) == std::string::npos &&
folded(str(row, "id")).find(search) == std::string::npos))
continue;
matches.push_back(&row);
}
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
const auto av = value(*a), bv = value(*b);
if (av.is_null() != bv.is_null())
return !av.is_null(); // Unknown values are last in both directions.
if (av == bv)
return str(*a, "id") < str(*b, "id");
return descending ? av > bv : av < bv;
});
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
Json result = Json::object();
for (auto it = data.begin(); it != data.end(); ++it)
if (it.key() != "items")
result[it.key()] = it.value();
result["items"] = Json::array();
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
i < matches.size() && int64_t(result["items"].size()) < limit; ++i)
result["items"].push_back(*matches[i]);
result["total"] = matches.size();
result["offset"] = offset;
result["limit"] = limit;
return result;
}
} // namespace bmh::editor
-11
View File
@@ -1,11 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
class World;
// Read-only projections. Session caches the unfiltered data at its revision;
// searching, sorting and paging always operate on the complete projection.
Json comparison_data(const World &, const Json &args);
Json query_comparison(const Json &data, const Json &args);
} // namespace bmh::editor
-316
View File
@@ -1,316 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/images.hpp"
#include <SDL.h>
#include <SDL_image.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <functional>
#include <limits>
#include <lunasvg.h>
#include <miniz.h>
#include <pugixml.hpp>
#include <sstream>
namespace bmh::editor::images {
namespace {
constexpr uint64_t maximum_pixels = 32ull * 1024 * 1024;
void bounds(int w, int h) {
if (w <= 0 || h <= 0 || w > 8192 || h > 8192 || uint64_t(w) * uint64_t(h) > maximum_pixels)
throw Error("image_dimensions");
}
struct Geometry {
double angle = 0, x = 0, y = 0, width = 1, height = 1;
bool flip_x = false, flip_y = false;
explicit Geometry(const Json &input) {
const Json value = input.is_null() ? Json::object() : input;
if (!value.is_object())
throw Error("invalid_transform");
angle = value.value("angle", 0.0);
flip_x = value.value("flip_x", false);
flip_y = value.value("flip_y", false);
if (value.contains("crop")) {
const auto &crop = value["crop"];
x = crop.value("x", 0.0);
y = crop.value("y", 0.0);
width = crop.value("width", 1.0);
height = crop.value("height", 1.0);
}
if (!std::isfinite(angle) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(width) ||
!std::isfinite(height) || std::abs(angle) > 360 || x < 0 || y < 0 || width <= 0 || height <= 0 ||
x + width > 1.000001 || y + height > 1.000001)
throw Error("invalid_transform");
}
Json json() const {
return {{"angle", angle},
{"flip_x", flip_x},
{"flip_y", flip_y},
{"crop", {{"x", x}, {"y", y}, {"width", width}, {"height", height}}}};
}
};
std::pair<double, double> canvas(double w, double h, double angle) {
const auto rad = angle * std::acos(-1.0) / 180.0;
auto c = std::abs(std::cos(rad)), s = std::abs(std::sin(rad));
return {std::ceil(w * c + h * s - 1e-9), std::ceil(w * s + h * c - 1e-9)};
}
void validate_svg(pugi::xml_node node) {
for (auto attr : node.attributes()) {
const std::string key = attr.name(), value = attr.value();
const auto lower = folded(value);
if ((key == "href" || key == "xlink:href") && std::string(node.name()) != "a" && !value.empty() &&
value.front() != '#' && !value.starts_with("data:image/"))
throw Error("external_svg_resource");
if (lower.find("url(") != lower.npos && lower.find("url(#") == lower.npos &&
lower.find("url('#") == lower.npos && lower.find("url(\"#") == lower.npos)
throw Error("external_svg_resource");
}
if (std::string(node.name()) == "style") {
const std::string css = folded(node.text().as_string());
if (css.find("@import") != css.npos || css.find("http:") != css.npos || css.find("https:") != css.npos ||
css.find("file:") != css.npos)
throw Error("external_svg_resource");
}
for (auto child : node.children())
validate_svg(child);
}
std::unique_ptr<lunasvg::Document> svg_document(std::string_view bytes) {
pugi::xml_document xml;
if (!xml.load_buffer(bytes.data(), bytes.size()))
throw Error("invalid_image");
validate_svg(xml.document_element());
auto doc = lunasvg::Document::loadFromData(bytes.data(), bytes.size());
if (!doc || doc->width() <= 0 || doc->height() <= 0 || !std::isfinite(doc->width()) ||
!std::isfinite(doc->height()))
throw Error("invalid_image");
return doc;
}
std::string transform_svg(std::string_view bytes, const Geometry &g, int &width, int &height) {
auto source = svg_document(bytes);
const double w = source->width(), h = source->height();
const auto [cw, ch] = canvas(w, h, g.angle);
const auto ow = std::max(1.0, cw * g.width), oh = std::max(1.0, ch * g.height);
if (ow > 1000000 || oh > 1000000)
throw Error("image_dimensions");
width = int(std::round(ow));
height = int(std::round(oh));
pugi::xml_document original, output;
if (!original.load_buffer(bytes.data(), bytes.size()))
throw Error("invalid_image");
auto root = output.append_child("svg");
root.append_attribute("xmlns") = "http://www.w3.org/2000/svg";
root.append_attribute("xmlns:xlink") = "http://www.w3.org/1999/xlink";
root.append_attribute("width") = ow;
root.append_attribute("height") = oh;
const auto view = "0 0 " + std::to_string(ow) + ' ' + std::to_string(oh);
root.append_attribute("viewBox") = view.c_str();
auto group = root.append_child("g");
std::ostringstream matrix;
matrix.imbue(std::locale::classic());
matrix << "translate(" << -g.x * cw << ' ' << -g.y * ch << ") translate(" << cw / 2 << ' ' << ch / 2 << ") rotate("
<< g.angle << ") scale(" << (g.flip_x ? -1 : 1) << ' ' << (g.flip_y ? -1 : 1) << ") translate(" << -w / 2
<< ' ' << -h / 2 << ')';
group.append_attribute("transform") = matrix.str().c_str();
auto child = group.append_copy(original.document_element());
if (!child.attribute("width"))
child.append_attribute("width");
if (!child.attribute("height"))
child.append_attribute("height");
child.attribute("width") = w;
child.attribute("height") = h;
std::ostringstream serialized;
output.save(serialized, "", pugi::format_raw, pugi::encoding_utf8);
return serialized.str();
}
double kernel(double x) {
x = std::abs(x);
if (x <= 1)
return (1.5 * x - 2.5) * x * x + 1;
if (x < 2)
return ((-0.5 * x + 2.5) * x - 4) * x + 2;
return 0;
}
void sample(const Raster &source, double x, double y, uint8_t *destination) {
const int ix = int(std::floor(x)), iy = int(std::floor(y));
double alpha = 0;
std::array<double, 3> color{};
for (int j = iy - 1; j <= iy + 2; ++j)
for (int i = ix - 1; i <= ix + 2; ++i) {
if (i < 0 || j < 0 || i >= source.width || j >= source.height)
continue;
const auto *pixel = source.pixels.data() + (size_t(j) * source.width + i) * 4;
const double weight = kernel(x - i) * kernel(y - j);
const double a = pixel[3] / 255.0;
alpha += weight * a;
for (int c = 0; c < 3; ++c)
color[c] += pixel[c] * a * weight;
}
for (int c = 0; c < 3; ++c)
destination[c] = alpha > 1e-8 ? uint8_t(std::clamp(std::round(color[c] / alpha), 0.0, 255.0)) : 0;
destination[3] = uint8_t(std::clamp(std::round(alpha * 255), 0.0, 255.0));
}
Raster rotate_crop(const Raster &source, const Geometry &g, int maximum = 8192) {
const auto [cw, ch] = canvas(source.width, source.height, g.angle);
double ow = std::max(1.0, std::round(cw * g.width)), oh = std::max(1.0, std::round(ch * g.height));
const double factor = std::min(1.0, maximum / std::max(ow, oh));
Raster result{std::max(1, int(std::round(ow * factor))), std::max(1, int(std::round(oh * factor))), {}};
bounds(result.width, result.height);
result.pixels.resize(size_t(result.width) * result.height * 4);
const auto rad = g.angle * std::acos(-1.0) / 180.0;
const auto cosine = std::cos(rad), sine = std::sin(rad);
for (int y = 0; y < result.height; ++y)
for (int x = 0; x < result.width; ++x) {
double dx = (x + .5) * ow / result.width + g.x * cw - cw / 2;
double dy = (y + .5) * oh / result.height + g.y * ch - ch / 2;
double sx = cosine * dx + sine * dy, sy = -sine * dx + cosine * dy;
if (g.flip_x)
sx = -sx;
if (g.flip_y)
sy = -sy;
sample(source, sx + source.width / 2.0 - .5, sy + source.height / 2.0 - .5,
result.pixels.data() + (size_t(y) * result.width + x) * 4);
}
return result;
}
void be32(std::string &data, uint32_t n) {
for (int shift = 24; shift >= 0; shift -= 8)
data += char(n >> shift);
}
void chunk(std::string &out, const char *type, const std::string &data) {
be32(out, uint32_t(data.size()));
const auto start = out.size();
out.append(type, 4);
out += data;
be32(out, uint32_t(mz_crc32(0, reinterpret_cast<const unsigned char *>(out.data() + start), data.size() + 4)));
}
} // namespace
Raster decode(std::string_view bytes, const std::string &extension, int vector_size) {
if (bytes.size() > 64ull * 1024 * 1024)
throw Error("size_limit");
if (folded(extension) == ".svg" || extension == "svg") {
auto doc = svg_document(bytes);
const double scale = vector_size / std::max(doc->width(), doc->height());
auto bitmap = doc->renderToBitmap(std::max(1, int(std::round(doc->width() * scale))),
std::max(1, int(std::round(doc->height() * scale))));
if (bitmap.isNull())
throw Error("invalid_image");
bitmap.convertToRGBA();
Raster result{bitmap.width(), bitmap.height(), {}};
bounds(result.width, result.height);
result.pixels.resize(size_t(result.width) * result.height * 4);
for (int y = 0; y < result.height; ++y)
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
bitmap.data() + size_t(y) * bitmap.stride(), size_t(result.width) * 4);
return result;
}
auto *stream = SDL_RWFromConstMem(bytes.data(), int(bytes.size()));
if (!stream)
throw Error("invalid_image");
SDL_Surface *loaded = IMG_Load_RW(stream, 1);
if (!loaded)
throw Error("invalid_image", {{"detail", IMG_GetError()}});
struct Free {
SDL_Surface *p;
~Free() { SDL_FreeSurface(p); }
} source{loaded};
bounds(loaded->w, loaded->h);
SDL_Surface *converted = SDL_ConvertSurfaceFormat(loaded, SDL_PIXELFORMAT_RGBA32, 0);
if (!converted)
throw Error("invalid_image");
Free rgba{converted};
Raster result{converted->w, converted->h, {}};
result.pixels.resize(size_t(result.width) * result.height * 4);
for (int y = 0; y < result.height; ++y)
std::memcpy(result.pixels.data() + size_t(y) * result.width * 4,
static_cast<const uint8_t *>(converted->pixels) + size_t(y) * converted->pitch,
size_t(result.width) * 4);
return result;
}
std::string encode_png(const Raster &image) {
bounds(image.width, image.height);
if (image.pixels.size() != size_t(image.width) * image.height * 4)
throw Error("invalid_image");
std::string result("\x89PNG\r\n\x1a\n", 8), header;
be32(header, uint32_t(image.width));
be32(header, uint32_t(image.height));
header.append("\x08\x06\0\0\0", 5);
chunk(result, "IHDR", header);
std::string scanlines;
scanlines.reserve((size_t(image.width) * 4 + 1) * image.height);
for (int y = 0; y < image.height; ++y) {
scanlines += '\0';
scanlines.append(reinterpret_cast<const char *>(image.pixels.data() + size_t(y) * image.width * 4),
size_t(image.width) * 4);
}
mz_ulong size = mz_compressBound(scanlines.size());
std::string packed(size, '\0');
if (mz_compress2(reinterpret_cast<unsigned char *>(packed.data()), &size,
reinterpret_cast<const unsigned char *>(scanlines.data()), scanlines.size(),
MZ_BEST_SPEED) != MZ_OK)
throw Error("image_encode_failed");
packed.resize(size);
chunk(result, "IDAT", packed);
chunk(result, "IEND", {});
return result;
}
Result transform(std::string_view original, const std::string &extension, const Json &recipe) {
Geometry g(recipe);
Result result;
result.recipe = g.json();
if (g.angle == 0 && !g.flip_x && !g.flip_y && g.x == 0 && g.y == 0 && g.width == 1 && g.height == 1) {
// Import without an edit preserves the exact source pixels and codec.
auto source = decode(original, extension);
result.bytes = original;
result.extension = extension.starts_with('.') ? extension : '.' + extension;
if (result.extension == ".svg") {
auto svg = svg_document(original);
result.width = int(std::round(svg->width()));
result.height = int(std::round(svg->height()));
} else {
result.width = source.width;
result.height = source.height;
}
return result;
}
if (folded(extension) == ".svg" || extension == "svg") {
result.bytes = transform_svg(original, g, result.width, result.height);
result.extension = ".svg";
} else {
auto source = decode(original, extension);
auto output = rotate_crop(source, g);
result.width = output.width;
result.height = output.height;
result.extension = ".png";
result.bytes = encode_png(output);
}
return result;
}
Raster preview(std::string_view bytes, const std::string &extension, const Json &recipe, int maximum) {
Geometry g(recipe);
if (folded(extension) == ".svg" || extension == "svg") {
int w, h;
auto svg = transform_svg(bytes, g, w, h);
return decode(svg, ".svg", maximum);
}
return rotate_crop(decode(bytes, extension), g, maximum);
}
std::string base64(std::string_view bytes) {
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
for (size_t i = 0; i < bytes.size(); i += 3) {
uint32_t value = uint8_t(bytes[i]) << 16;
if (i + 1 < bytes.size())
value |= uint8_t(bytes[i + 1]) << 8;
if (i + 2 < bytes.size())
value |= uint8_t(bytes[i + 2]);
result += alphabet[(value >> 18) & 63];
result += alphabet[(value >> 12) & 63];
result += i + 1 < bytes.size() ? alphabet[(value >> 6) & 63] : '=';
result += i + 2 < bytes.size() ? alphabet[value & 63] : '=';
}
return result;
}
std::string silhouette() {
return R"(<svg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"><rect width="180" height="180" rx="24" fill="#293c4c"/><circle cx="90" cy="62" r="30" fill="#91acba"/><path d="M26 180v-27c0-35 25-50 64-50s64 15 64 50v27" fill="#91acba"/></svg>)";
}
} // namespace bmh::editor::images
-22
View File
@@ -1,22 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
#include <cstdint>
namespace bmh::editor::images {
struct Raster {
int width = 0, height = 0;
std::vector<uint8_t> pixels;
};
struct Result {
std::string bytes, extension;
int width = 0, height = 0;
Json recipe;
};
Raster decode(std::string_view bytes, const std::string &extension, int vector_size = 1024);
std::string encode_png(const Raster &);
Result transform(std::string_view original, const std::string &extension, const Json &recipe);
Raster preview(std::string_view original, const std::string &extension, const Json &recipe, int maximum = 1024);
std::string base64(std::string_view);
std::string silhouette();
} // namespace bmh::editor::images
-174
View File
@@ -1,174 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/ui.hpp"
#include "editor/version.hpp"
#include "launch/startup_error.hpp"
#include <SDL.h>
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <thread>
namespace {
std::atomic<bool> stopped{false};
void stop(int) { stopped = true; }
} // namespace
int main(int argc, char **argv) {
using namespace bmh::editor;
bmh::rml::attach_parent_console();
std::string language = "de";
bool graphical = true;
for (int i = 1; i < argc; ++i)
if (std::string_view(argv[i]) == "--headless" || std::string_view(argv[i]) == "--serve" ||
std::string_view(argv[i]) == "--stdio-mcp" || std::string_view(argv[i]) == "--version" ||
std::string_view(argv[i]) == "--help")
graphical = false;
try {
bool headless = false, serve = false, stdio = false, demo = false, blank = false, validate = false,
print = false;
fs::path input, output, settings, script;
UiConfig ui;
int port = -1;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
auto next = [&]() -> std::string {
if (++i >= argc)
throw Error("invalid_change", {{"argument", arg}});
return argv[i];
};
if (arg == "--version") {
std::cout << editor_product() << '\n';
return 0;
} else if (arg == "--headless")
headless = true;
else if (arg == "--serve")
serve = headless = true;
else if (arg == "--stdio-mcp")
stdio = headless = true;
else if (arg == "--open")
input = path(next());
else if (arg == "--output")
output = path(next());
else if (arg == "--settings")
settings = path(next());
else if (arg == "--commands")
script = path(next());
else if (arg == "--mcp-port")
port = std::stoi(next());
else if (arg == "--demo")
demo = true;
else if (arg == "--new")
blank = true;
else if (arg == "--validate")
validate = true;
else if (arg == "--print-mcp-config")
print = true;
else if (arg == "--assets")
ui.assets = path(next());
else if (arg == "--screenshot")
ui.screenshot = path(next());
else if (arg == "--page")
ui.page = next();
else if (arg == "--quit-after-ms")
ui.quit_after_ms = std::stoi(next());
else if (arg == "--help") {
std::cout << editor_product() << '\n'
<< "OpenBMHEditor [--open world.obw|installation] [--demo|--new]\n"
" [--settings file] [--assets directory] [--page "
"clubs|players|...]\n"
" [--headless --validate] [--output world.obw] [--commands "
"script.json]\n"
" [--serve --mcp-port 8765] [--stdio-mcp] "
"[--print-mcp-config] [--version]\n";
return 0;
} else if (!arg.starts_with('-') && input.empty())
input = path(arg);
else
throw Error("invalid_change", {{"argument", arg}});
}
auto options = Options::load(settings);
language = options.language;
if (port >= 0) {
options.mcp_port = port;
options.mcp_enabled = true;
}
Session session;
if (!input.empty())
session.execute("open", {{"path", utf8(input)}});
else if (demo || blank)
session.execute(demo ? "demo" : "new");
if (!script.empty()) {
const auto actions = Json::parse(read_file(script, 8 * 1024 * 1024));
if (!actions.is_array())
throw Error("invalid_change");
for (const auto &action : actions) {
auto result = session.execute(str(action, "command"), action.value("args", Json::object()));
if (headless && !stdio)
std::cout << result.dump() << '\n';
}
}
bool has_errors = false;
if (validate) {
auto result = session.execute("validate");
for (auto &row : result["diagnostics"])
if (row["severity"] == "error")
has_errors = true;
if (headless && !stdio)
std::cout << result.dump() << '\n';
}
if (!output.empty())
session.execute("save", {{"path", utf8(output)}});
McpServer server(session);
if (stdio) {
std::string line;
while (std::getline(std::cin, line)) {
try {
auto reply = server.dispatch(Json::parse(line));
if (!reply.is_null())
std::cout << reply.dump() << std::endl;
} catch (const std::exception &) {
std::cout << "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-"
"32700,\"message\":\"Parse error\"}}"
<< std::endl;
}
}
return 0;
}
if (serve || !headless) {
try {
server.start(options);
} catch (const Error &e) {
std::cerr << tr(language, e.code) << '\n';
if (serve)
throw;
}
}
if (print)
std::cout << server.connection(options).dump(2) << '\n';
if (serve) {
std::cerr << "OpenBMH Editor MCP: http://127.0.0.1:" << server.port() << "/mcp\n";
std::signal(SIGINT, stop);
std::signal(SIGTERM, stop);
while (!stopped)
std::this_thread::sleep_for(std::chrono::milliseconds(80));
} else if (!headless) {
if (ui.assets.empty()) {
char *base = SDL_GetBasePath();
ui.assets = (base ? path(base) : fs::absolute(path(argv[0])).parent_path()) / "assets/editor";
SDL_free(base);
}
return run_ui(session, options, server, ui);
}
return has_errors ? 2 : 0;
} catch (const Error &e) {
const auto message =
Json{{"error", e.code}, {"message", tr(language, e.code)}, {"details", e.details}}.dump();
std::cerr << message << '\n';
if (graphical)
bmh::rml::report_start_error("OpenBMHEditor", tr(language, e.code));
return 1;
} catch (const std::exception &e) {
bmh::rml::report_start_error("OpenBMHEditor", tr(language, "error") + ": " + e.what(), graphical);
return 1;
}
}
-397
View File
@@ -1,397 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/mcp.hpp"
#include "editor/version.hpp"
#include <atomic>
#include <httplib.h>
#include <thread>
namespace bmh::editor {
namespace {
Json schema(Json properties = Json::object(), Json required = Json::array()) {
if (properties.is_null())
properties = Json::object();
if (required.is_null())
required = Json::array();
return {{"type", "object"}, {"properties", properties}, {"required", required}, {"additionalProperties", false}};
}
Json field(const char *type, const char *description = "") { return {{"type", type}, {"description", description}}; }
Json rpc_error(const Json &id, int code, const std::string &message, Json data = Json::object()) {
return {{"jsonrpc", "2.0"}, {"id", id}, {"error", {{"code", code}, {"message", message}, {"data", data}}}};
}
bool local_authority(const std::string &host) {
for (auto name : {"127.0.0.1", "localhost", "[::1]"}) {
const std::string base(name);
if (host == base)
return true;
if (host.starts_with(base + ':')) {
const auto port = host.substr(base.size() + 1);
if (!port.empty() && port.find_first_not_of("0123456789") == port.npos)
return true;
}
}
return false;
}
bool local_origin(std::string value) {
if (value.starts_with("http://"))
value.erase(0, 7);
else if (value.starts_with("https://"))
value.erase(0, 8);
else
return false;
return local_authority(value);
}
bool equal_secret(const std::string &a, const std::string &b) {
if (a.size() != b.size())
return false;
unsigned difference = 0;
for (size_t i = 0; i < a.size(); ++i)
difference |= unsigned(a[i] ^ b[i]);
return difference == 0;
}
const std::map<std::string, std::string> commands{{"editor_info", "info"},
{"editor_open", "open"},
{"editor_new", "new"},
{"editor_list", "list"},
{"editor_compare", "compare"},
{"editor_regulations", "regulations"},
{"editor_get", "get"},
{"editor_apply", "apply"},
{"editor_validate", "validate"},
{"editor_rules", "rules"},
{"editor_save", "save"},
{"editor_undo", "undo"},
{"editor_redo", "redo"},
{"editor_history", "history"},
{"editor_roster_move", "roster.move"},
{"editor_roster_swap", "roster.swap"},
{"editor_roster_order", "roster.order"},
{"editor_review_resolve", "review.resolve"},
{"editor_image_import", "asset.import"},
{"editor_image_edit", "asset.edit"},
{"editor_image_preview", "asset.preview"},
{"editor_image_export", "asset.export"}};
} // namespace
struct McpServer::Impl {
explicit Impl(Session &value) : session(value) {}
Session &session;
std::unique_ptr<httplib::Server> http;
std::thread worker;
std::atomic<bool> active{false};
int port = 0;
std::string token;
};
McpServer::McpServer(Session &s) : impl_(std::make_unique<Impl>(s)) {}
McpServer::~McpServer() { stop(); }
int McpServer::port() const { return impl_->port; }
bool McpServer::running() const { return impl_->active; }
void McpServer::stop() {
if (impl_->http)
impl_->http->stop();
if (impl_->worker.joinable())
impl_->worker.join();
impl_->active = false;
impl_->http.reset();
impl_->port = 0;
}
Json McpServer::connection(const Options &options) const {
return {{"mcpServers",
{{"openbmh-editor",
{{"type", "http"},
{"url", "http://127.0.0.1:" + std::to_string(port()) + "/mcp"},
{"headers", {{"Authorization", "Bearer " + options.token}}}}}}}};
}
Json McpServer::tools() {
Json result = Json::array();
const auto revision = field("integer", "Optional optimistic concurrency guard; use revision "
"from editor_info/get.");
const auto id = field("string", "Stable world identifier; never an array index.");
const auto table = field("string", "nations, competitions, clubs, players, stadiums, staff, "
"assets, review, or read-only preserved tables.");
auto add = [&](const char *name, const char *description, Json properties, Json required = Json::array(),
bool read_only = false) {
result.push_back({{"name", name},
{"description", description},
{"inputSchema", schema(properties, required)},
{"annotations",
{{"readOnlyHint", read_only}, {"destructiveHint", !read_only}, {"openWorldHint", false}}}});
};
add("editor_info",
"Current world, counts, dirty flag, monotonic revision and undo/redo "
"state.",
{}, {}, true);
add("editor_open",
"Open OBW archive, unpacked world, or legacy BMH/FLTD installation. "
"Refuses unsaved replacement unless discard=true.",
{{"path", field("string")},
{"start_date", field("string")},
{"discard", field("boolean")},
{"expected_revision", revision}},
{"path"});
add("editor_new", "Create a blank editor world; never writes legacy files.",
{{"title", field("string")}, {"discard", field("boolean")}, {"expected_revision", revision}});
add("editor_list",
"Search, filter, sort and page rows. Maximum page size 200; no data is "
"truncated on disk.",
{{"table", table},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"team", id},
{"role", field("string")},
{"offset", field("integer")},
{"limit", field("integer")},
{"sort", field("string")},
{"descending", field("boolean")},
{"unresolved_only", field("boolean")}},
{"table"}, true);
add("editor_compare",
"Read-only ratings and salary comparison for players, clubs or leagues. Attributes are native player "
"values "
"or player-weighted group means, within one attribute_set. Mixed systems need a filter for ratings. "
"Salary is integer world-currency minor units per season, from contracts active at "
"manifest.start_date "
"and matching the player's current team. Unknown/ambiguous salaries stay null. Group totals/means "
"cover "
"known player salaries only; salary_known/unknown/complete report coverage. All reserves are "
"included; "
"source-only duplicate evidence is excluded. Sorts the complete result before paging (max 200); "
"nulls last in both directions. Does not edit the world.",
{{"table", {{"type", "string"}, {"enum", {"players", "clubs", "leagues"}}}},
{"language", {{"type", "string"}, {"enum", {"de", "en"}}}},
{"attribute_set", field("string", "Optional set ID; automatic when only one system is present.")},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"team", id},
{"sort", field("string", "name, player_count, club_count, salary, salary_total, salary_average, "
"salary_known, attributes.<key>")},
{"descending", field("boolean")},
{"offset", field("integer")},
{"limit", field("integer")}},
{}, true);
add("editor_regulations",
"Read-only declared game/league rules, promotion, relegation and qualification selectors. "
"Also identifies inherited classic-season-entrants@1 and Classic ladder policies, without "
"replacing them with current football regulations. Missing rules remain unspecified. "
"Preserves source definitions and returns all game rule records. Never simulates a season or edits "
"data.",
{{"language", {{"type", "string"}, {"enum", {"de", "en"}}}},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"expected_revision", revision}},
{}, true);
add("editor_get", "Read a complete row, including preserved extensions and sources.",
{{"table", table}, {"id", id}}, {"table", "id"}, true);
add("editor_apply",
"Atomic undoable transaction, max 5000 changes. Each change: table, "
"op=create/update/delete, id. Create has data/name; update has set {JSON "
"pointer:value}, unset [JSON pointer]. IDs are immutable. References and "
"declared attribute ranges are checked before commit.",
{{"changes", {{"type", "array"}, {"items", {{"type", "object"}}}, {"maxItems", 5000}}},
{"expected_revision", revision}},
{"changes"});
add("editor_validate", "Structural errors plus non-blocking missing/source warnings.", {}, {}, true);
add("editor_rules",
"Read attribute systems and their actual ranges. Do not guess an "
"attribute scale.",
{}, {}, true);
add("editor_history", "Shared GUI/MCP transaction history.", {}, {}, true);
add("editor_save",
"Atomically save only a new-format .obw. A Classic source requires a new "
"filename. This editor profile is not executable in Classic 0.2.",
{{"path", field("string")}, {"expected_revision", revision}});
for (auto name : {"editor_undo", "editor_redo"})
add(name, "Undo/redo one shared transaction.", {{"expected_revision", revision}});
add("editor_roster_move", "Move one player to a club, or null for an explicitly chosen free agent.",
{{"player", id},
{"team", {{"type", {"string", "null"}}}},
{"number", field("integer")},
{"expected_revision", revision}},
{"player", "team"});
add("editor_roster_swap",
"Exchange club, shirt number and squad order between two players "
"atomically.",
{{"first", id}, {"second", id}, {"expected_revision", revision}}, {"first", "second"});
add("editor_roster_order",
"Set complete club squad order; every assigned player must occur exactly "
"once.",
{{"team", id}, {"players", {{"type", "array"}, {"items", field("string")}}}, {"expected_revision", revision}},
{"team", "players"});
add("editor_review_resolve",
"Choose a recorded source alternative and update its linked entity. "
"Original claims remain preserved.",
{{"id", id}, {"choice", field("integer")}, {"expected_revision", revision}}, {"id", "choice"});
const auto crop = schema(
{{"x", field("number")}, {"y", field("number")}, {"width", field("number")}, {"height", field("number")}});
const auto transform = schema(
{{"angle", field("number")}, {"flip_x", field("boolean")}, {"flip_y", field("boolean")}, {"crop", crop}});
add("editor_image_import",
"Import PNG/JPEG/WebP/SVG with optional arbitrary rotation, mirror, crop "
"(normalized on the rotated canvas). Preserves source and recipe; "
"identity import preserves exact bytes. target={table,id,field} "
"optionally assigns the logical key.",
{{"file", field("string")},
{"key", id},
{"target", field("object")},
{"transform", transform},
{"expected_revision", revision}},
{"file"});
add("editor_image_edit",
"Re-edit an existing image using its preserved original. No repeated "
"resampling. Optional source_key clones that source into key; target assigns it to one entity without changing "
"other users of a shared fallback.",
{{"key", id},
{"source_key", id},
{"target", field("object")},
{"transform", transform},
{"expected_revision", revision}},
{"key", "transform"});
add("editor_image_preview", "Return a PNG preview as an MCP image content block.",
{{"key", id}, {"transform", transform}}, {"key"}, true);
add("editor_image_export", "Export an image as PNG to an explicit filesystem path.",
{{"key", id}, {"path", field("string")}}, {"key", "path"});
return result;
}
Json McpServer::dispatch(const Json &request) {
if (!request.is_object())
return rpc_error(nullptr, -32600, "Invalid request");
const auto id = request.value("id", Json());
if (!request.is_object() || str(request, "jsonrpc") != "2.0" || !request.contains("method") ||
!request["method"].is_string() || (request.contains("id") && !id.is_string() && !id.is_number_integer()))
return rpc_error(id, -32600, "Invalid request");
const auto method = str(request, "method");
if (!request.contains("id"))
return Json();
const auto params = request.value("params", Json::object());
if (!params.is_object())
return rpc_error(id, -32602, "Invalid parameters");
Json result;
if (method == "initialize") {
auto version = str(params, "protocolVersion");
if (version != "2025-06-18")
version = "2025-11-25";
result = {{"protocolVersion", version},
{"capabilities", {{"tools", {{"listChanged", false}}}}},
{"serverInfo", {{"name", "OpenBMH Editor"}, {"version", std::string(kEditorVersion)}}},
{"instructions", "Edits share the native editor's undo history. Read rules for real "
"attribute ranges. Save only OBW editor worlds. These are not Classic "
"0.2 playable packages."}};
} else if (method == "ping")
result = Json::object();
else if (method == "tools/list")
result = {{"tools", tools()}};
else if (method == "tools/call") {
auto name = str(params, "name");
if (!commands.contains(name))
return rpc_error(id, -32602, "Unknown tool");
auto args = params.value("arguments", Json::object());
if (!args.is_object())
return rpc_error(id, -32602, "Arguments must be an object");
try {
auto response = impl_->session.execute(commands.at(name), args);
if (name == "editor_image_preview") {
result = {{"content",
Json::array({{{"type", "image"}, {"mimeType", "image/png"}, {"data", response["data"]}}})},
{"isError", false}};
} else
result = {{"content", Json::array({{{"type", "text"}, {"text", response.dump()}}})},
{"structuredContent", response.is_object() ? response : Json{{"items", response}}},
{"isError", false}};
} catch (const Error &e) {
Json detail{{"code", e.code}, {"details", e.details}};
result = {{"content", Json::array({{{"type", "text"}, {"text", detail.dump()}}})}, {"isError", true}};
} catch (const std::exception &) {
result = {{"content",
Json::array({{{"type", "text"}, {"text", "Invalid tool arguments or inaccessible file."}}})},
{"isError", true}};
}
} else
return rpc_error(id, -32601, "Method not found");
return {{"jsonrpc", "2.0"}, {"id", id}, {"result", result}};
}
void McpServer::start(const Options &options) {
stop();
if (!options.mcp_enabled)
return;
impl_->token = options.token;
auto server = std::make_unique<httplib::Server>();
server->set_payload_max_length(8 * 1024 * 1024);
server->set_read_timeout(10, 0);
server->set_write_timeout(30, 0);
server->new_task_queue = [] { return new httplib::ThreadPool(2); };
auto authorized = [this](const httplib::Request &request, httplib::Response &response) {
response.set_header("Cache-Control", "no-store");
if (!local_authority(request.get_header_value("Host")) ||
(request.has_header("Origin") && !local_origin(request.get_header_value("Origin")))) {
response.status = 403;
return false;
}
if (!equal_secret(request.get_header_value("Authorization"), "Bearer " + impl_->token)) {
response.status = 401;
response.set_header("WWW-Authenticate", "Bearer");
return false;
}
return true;
};
server->Post("/mcp", [this, authorized](const httplib::Request &request, httplib::Response &response) {
if (!authorized(request, response))
return;
if (!request.get_header_value("Content-Type").starts_with("application/json")) {
response.status = 415;
return;
}
const auto version = request.get_header_value("MCP-Protocol-Version");
if (!version.empty() && version != "2025-11-25" && version != "2025-06-18" && version != "2025-03-26") {
response.status = 400;
response.set_content(rpc_error(nullptr, -32600, "Supported versions: 2025-11-25, 2025-06-18").dump(),
"application/json");
return;
}
try {
auto input = Json::parse(request.body);
if (!input.is_object()) {
response.status = 400;
response.set_content(rpc_error(nullptr, -32600, "Invalid request").dump(), "application/json");
return;
}
auto output = dispatch(input);
if (output.is_null()) {
response.status = 202;
return;
}
response.set_content(output.dump(), "application/json");
} catch (const Json::exception &) {
response.status = 400;
response.set_content(rpc_error(nullptr, -32700, "Parse error").dump(), "application/json");
} catch (const std::exception &) {
response.status = 500;
response.set_content(rpc_error(nullptr, -32603, "Internal error").dump(), "application/json");
}
});
for (auto method : {0, 1}) {
auto unsupported = [authorized](const httplib::Request &request, httplib::Response &response) {
if (authorized(request, response)) {
response.status = 405;
response.set_header("Allow", "POST");
}
};
if (method == 0)
server->Get("/mcp", unsupported);
else
server->Delete("/mcp", unsupported);
}
impl_->port = options.mcp_port ? (server->bind_to_port("127.0.0.1", options.mcp_port) ? options.mcp_port : -1)
: server->bind_to_any_port("127.0.0.1");
if (impl_->port <= 0) {
impl_->port = 0;
throw Error("server_failed");
}
impl_->http = std::move(server);
impl_->active = true;
impl_->worker = std::thread([this] {
impl_->http->listen_after_bind();
impl_->active = false;
});
}
} // namespace bmh::editor
-28
View File
@@ -1,28 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/options.hpp"
#include "editor/session.hpp"
#include <memory>
namespace bmh::editor {
// A local Streamable HTTP MCP endpoint. GUI and MCP own no separate world
// state. Protocol 2025-11-25 (also negotiates 2025-06-18), no optional
// SSE/session state.
class McpServer {
public:
explicit McpServer(Session &);
~McpServer();
McpServer(const McpServer &) = delete;
void start(const Options &);
void stop();
int port() const;
bool running() const;
Json connection(const Options &) const;
static Json tools();
Json dispatch(const Json &request);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace bmh::editor
-578
View File
@@ -1,578 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/options.hpp"
#include <cstdlib>
#include <map>
#include <random>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <sys/stat.h>
#endif
namespace bmh::editor {
Options Options::load(fs::path override_path) {
Options result;
if (override_path.empty()) {
#ifdef _WIN32
// The narrow CRT environment is encoded in the active Windows code
// page, not UTF-8. Use the native path for names such as Müller.
wchar_t base[32768]{};
const auto count = GetEnvironmentVariableW(L"APPDATA", base, 32768);
override_path =
(count > 0 && count < 32768 ? fs::path(base) : fs::temp_directory_path()) / "OpenBMH" / "editor.json";
#elif defined(__APPLE__)
auto base = std::getenv("HOME");
override_path =
(base ? path(base) : fs::temp_directory_path()) / "Library/Application Support/OpenBMH/editor.json";
#else
if (auto base = std::getenv("XDG_CONFIG_HOME"))
override_path = path(base) / "openbmh/editor.json";
else {
auto user = std::getenv("HOME");
override_path = (user ? path(user) : fs::temp_directory_path()) / ".config/openbmh/editor.json";
}
#endif
}
result.settings_file = std::move(override_path);
if (fs::exists(result.settings_file)) {
try {
auto json = Json::parse(read_file(result.settings_file, 1024 * 1024));
result.apply(json);
result.token = str(json, "mcp_token");
} catch (const std::exception &) {
throw Error("invalid_settings", {{"path", utf8(result.settings_file)}});
}
}
if (result.token.size() < 32) {
// random_device uses the OS entropy source on supported release targets;
// identifiers from the editor's PRNG are deliberately not credentials.
std::random_device entropy;
static constexpr char hex[] = "0123456789abcdef";
result.token.clear();
for (int i = 0; i < 8; ++i) {
auto number = entropy();
for (int j = 0; j < 8; ++j) {
result.token += hex[number & 15];
number >>= 4;
}
}
}
result.save();
return result;
}
Json Options::json(bool secret) const {
Json value{{"language", language}, {"theme", theme}, {"mcp_enabled", mcp_enabled}, {"mcp_port", mcp_port}};
if (secret)
value["mcp_token"] = token;
return value;
}
void Options::apply(const Json &value) {
auto language_value = str(value, "language", language), theme_value = str(value, "theme", theme);
auto port = value.value("mcp_port", mcp_port);
if ((language_value != "de" && language_value != "en") ||
(theme_value != "midnight" && theme_value != "silver" && theme_value != "matchday") || port < 0 || port > 65535)
throw Error("invalid_settings");
language = language_value;
theme = theme_value;
mcp_port = port;
mcp_enabled = value.value("mcp_enabled", mcp_enabled);
}
void Options::save() const {
if (settings_file.has_parent_path())
fs::create_directories(settings_file.parent_path());
write_atomic(settings_file, json(true).dump(2));
#ifndef _WIN32
chmod(settings_file.c_str(), 0600);
#endif
}
std::string tr(const std::string &language, const std::string &key) {
using Pair = std::pair<std::string, std::string>;
static const std::map<std::string, Pair> words{
{"data_areas", {"Datenbereiche", "World data"}},
{"navigation_back", {"Zurück", "Back"}},
{"navigation_forward", {"Vorwärts", "Forward"}},
{"navigation_left", {"Links", "Left"}},
{"navigation_right", {"Rechts", "Right"}},
{"drill_nations", {"Doppelklick: Ligen anzeigen", "Double-click to view leagues"}},
{"drill_competitions",
{"Doppelklick auf eine Liga: Vereine anzeigen", "Double-click a league to view clubs"}},
{"drill_clubs", {"Doppelklick: Spieler anzeigen", "Double-click to view players"}},
{"regulations", {"Regelwerk", "Regulations"}},
{"regulations_title", {"Spiel- & Ligaregeln", "Game & league rules"}},
{"subtitle_regulations",
{"Aufstieg, Abstieg und internationale Qualifikation",
"Promotion, relegation and international qualification"}},
{"regulation_readonly", {"Nur Anzeige", "Read only"}},
{"regulation_competitions", {"Ligen & Wettbewerbe", "Leagues & competitions"}},
{"regulation_game", {"Spielregeln", "Game rules"}},
{"regulation_movement_title", {"Auf- & Abstieg", "Promotion & relegation"}},
{"regulation_qualification_title",
{"Internationale Qualifikation & Teilnehmer", "International qualification & entrants"}},
{"regulation_promotion", {"Aufstieg", "Promotion"}},
{"regulation_relegation", {"Abstieg", "Relegation"}},
{"regulation_playoff", {"Relegationsspiele", "Playoffs"}},
{"regulation_playoff_winner", {"Sieger der Classic-Relegation", "Classic playoff winner"}},
{"regulation_classic_playoffs",
{"Bei parallelen unteren Ligen steigen die Meister direkt auf. Weitere Aufsteiger bestimmt die "
"Classic-Relegation. Ohne deren Ergebnis werden nur die Meister ausgetauscht.",
"For parallel lower leagues, champions go up directly. Additional promotion follows the Classic "
"playoffs. Without a playoff result, only champions are exchanged."}},
{"regulation_movement", {"Ligenwechsel", "League movement"}},
{"regulation_rank", {"Platz", "Rank"}},
{"regulation_to", {"in", "to"}},
{"regulation_closed", {"Kein regulärer Auf- oder Abstieg.", "No regular promotion or relegation."}},
{"regulation_unspecified", {"Nicht im OBW festgelegt.", "Not specified in the OBW."}},
{"regulation_amateur_pool",
{"Nachrückerpool der untersten Spielklasse", "Lowest-tier newcomer pool"}},
{"regulation_declared", {"Im OBW festgelegt", "Declared in the OBW"}},
{"regulation_classic", {"Classic-Verfahrensregel", "Classic adapter policy"}},
{"regulation_classic_movement_note",
{"Reguläre Plätze. Lizenzentzüge können die Saisonentscheidung ändern. Die Zuordnung zu parallelen "
"Ligen erfolgt beim Saisonwechsel.",
"Regular places. License withdrawals can change the season outcome. Allocation to parallel leagues "
"occurs at season rollover."}},
{"regulation_classic_intro",
{"Übernommenes Classic-Verfahren, keine heutigen UEFA-Regeln.",
"Inherited Classic policy; current UEFA regulations do not apply."}},
{"regulation_classic_champion",
{"Meister qualifiziert für die Champions League. Titelverteidiger werden zusätzlich berücksichtigt; "
"ist dieser bereits Meister, rückt der Zweite nach.",
"Champion qualifies for the Champions League. The holder also qualifies; if already champion, the "
"runner-up receives the extra place."}},
{"regulation_classic_cup",
{"Nationaler Pokalsieger qualifiziert für den Pokalsieger-Wettbewerb, bei bestehender Qualifikation "
"der Finalist. Ausländische Pokalvertreter werden im Classic-Verfahren bestimmt.",
"Domestic cup winner qualifies for the Cup Winners’ Cup; the finalist replaces an already "
"qualified winner. Foreign cup entrants follow the Classic selection policy."}},
{"regulation_classic_uefa",
{"reguläre Plätze nach Tabellenrang; bereits qualifizierte Teams werden übersprungen.",
"regular places by league rank; already qualified teams are skipped."}},
{"regulation_classic_holders",
{"Titelverteidiger von UEFA- und Pokalsieger-Cup sowie Doppelqualifikationen können zusätzliche "
"Plätze und Nachrücker auslösen.",
"UEFA/Cup Winners’ Cup holders and overlapping qualifications may produce extra places or "
"replacements."}},
{"regulation_runtime",
{"Teilnehmer werden durch das hinterlegte Classic-Verfahren bestimmt.",
"Entrants are resolved by the stored Classic policy."}},
{"regulation_winner", {"Sieger", "Winner"}},
{"regulation_runner_up", {"Finalist / Zweiter", "Runner-up"}},
{"regulation_next_unqualified", {"Nächstes noch nicht qualifiziertes Team", "Next unqualified team"}},
{"regulation_holder", {"Titelverteidiger", "Title holder"}},
{"regulation_coefficient",
{"Qualifikation nach Koeffizientenrang", "Qualification by coefficient rank"}},
{"regulation_fallback", {"Nachrücken", "Replacement"}},
{"regulation_stage", {"Phase", "Stage"}},
{"regulation_stages", {"Wettbewerbsphasen & Spielregeln", "Competition stages & match rules"}},
{"regulation_show_source", {"OBW-Details anzeigen", "Show OBW details"}},
{"regulation_hide_source", {"OBW-Details ausblenden", "Hide OBW details"}},
{"regulation_preserved",
{"Unveränderte Angaben aus world/rules.json. Diese Ansicht ist schreibgeschützt.",
"Unmodified values from world/rules.json. This view is read only."}},
{"regulation_type_league", {"Liga", "League"}},
{"regulation_type_cup", {"Pokal", "Cup"}},
{"regulation_type_national_team", {"Nationalmannschaften", "National teams"}},
{"regulation_type_club_international",
{"Internationaler Vereinswettbewerb", "International club competition"}},
{"regulation_type_friendly", {"Freundschaftsspiel", "Friendly"}},
{"regulation_type_indoor", {"Hallenturnier", "Indoor tournament"}},
{"rule_type_attribute_set", {"Spielwerte & Wertebereiche", "Attributes & ranges"}},
{"rule_type_fixture_tables", {"Spielplanverfahren", "Fixture generation"}},
{"rule_type_legacy_ladder", {"Classic-Ligenpyramide", "Classic league pyramid"}},
{"rule_type_training_camps", {"Trainingslager", "Training camps"}},
{"rule_type_credit_rates", {"Kreditregeln", "Credit rules"}},
{"rule_type_classic_runtime", {"Classic-Verfahren", "Classic runtime policies"}},
{"rule_type_classic_data_regions", {"Übernommene Classic-Regeldaten", "Preserved Classic rule data"}},
{"comparison", {"Wertevergleich", "Comparison"}},
{"comparison_title", {"Stärken & Gehälter", "Ratings & salaries"}},
{"subtitle_comparison",
{"Spieler, Mannschaften und Ligen im Vergleich", "Compare players, teams and leagues"}},
{"teams", {"Mannschaften", "Teams"}},
{"leagues", {"Ligen", "Leagues"}},
{"physical_strength", {"Körperkraft", "Physical strength"}},
{"comparison_columns", {"Spalten auswählen", "Choose columns"}},
{"comparison_columns_hint",
{"Spielwerte einblenden. Weitere Spalten sind horizontal erreichbar.",
"Select attributes. Scroll horizontally to see further columns."}},
{"comparison_all_sets", {"Alle Spieler · Systeme getrennt", "All players · separate systems"}},
{"comparison_all_players", {"alle Spieler", "all players"}},
{"all_columns", {"Alle auswählen", "Select all"}},
{"no_columns", {"Keine auswählen", "Select none"}},
{"comparison_player_values", {"Originalskala des Datensatzes", "Dataset's original scale"}},
{"comparison_mean_values", {"Spielwerte: Durchschnitt je Spieler", "Attributes: mean per player"}},
{"comparison_known_values", {"bekannte Werte", "known values"}},
{"salary_season", {"Gehalt / Saison", "Salary / season"}},
{"salary_total", {"Gehaltssumme / Saison", "Total salary / season"}},
{"salary_average", {"Ø Gehalt / Spieler", "Mean salary / player"}},
{"salary_coverage", {"Gehälter bekannt", "Salaries known"}},
{"salary_missing", {"Gehälter unbekannt", "salaries unknown"}},
{"salary_ambiguous", {"mehrere aktive Verträge", "multiple active contracts"}},
{"comparison_salary_note",
{"Gehälter je Saison in Weltwährung. * Nur bekannte Gehälter; Summe/Ø unvollständig. Stichtag",
"Salaries per season in world currency. * Known salaries only; total/mean incomplete. As of"}},
{"comparison_scope_note",
{"Gesamter Kader inklusive Reserven. Fehlende Spielwerte bleiben leer; Ø nur aus bekannten Werten.",
"Full squads including reserves. Missing attributes stay blank; means use known values only."}},
{"comparison_mixed_note",
{"Für Stärken ein Attributsystem auswählen. Unterschiedliche Systeme werden nicht vermischt.",
"Choose an attribute set to compare ratings. Different systems are not mixed."}},
{"comparison_excluded", {"Quellenduplikate nicht eingerechnet", "source duplicates excluded"}},
{"comparison_fictional",
{"Der Datensatz enthält als fiktiv oder geschätzt gekennzeichnete Ergänzungen.",
"The dataset includes additions marked as fictional or estimated."}},
{"comparison_sort_hint", {"Spaltenkopf anklicken zum Sortieren", "Click a column heading to sort"}},
{"invalid_attribute_set",
{"Dieses Attributsystem ist nicht im Datenbestand.",
"This attribute set is not present in the dataset."}},
{"invalid_comparison_sort",
{"Diese Vergleichsspalte ist nicht verfügbar.", "This comparison column is unavailable."}},
{"invalid_manifest",
{"Die Kennzeichnung der Editorwelt ist ungültig.", "The editor world identification is invalid."}},
{"facilities", {"Ausstattung", "Facilities"}},
{"draft_prompt", {"Eingaben übernehmen?", "Apply these entries?"}},
{"draft_detail",
{"Die Eigenschaften enthalten noch nicht übernommene Eingaben.",
"The inspector contains entries that have not been applied."}},
{"trophy", {"Pokalbild", "Trophy image"}},
{"author", {"Urheber", "Author"}},
{"license", {"Lizenz", "License"}},
{"copy", {"Kopie", "Copy"}},
{"applied", {"Übernommen", "Applied"}},
{"undone", {"Zurückgenommen", "Undone"}},
{"edit", {"Bearbeitung", "Edit"}},
{"image_import", {"Bild importieren", "Import image"}},
{"width", {"Breite", "Width"}},
{"height", {"Höhe", "Height"}},
{"x", {"Links", "Left"}},
{"y", {"Oben", "Top"}},
{"open_folder", {"Entpackte Welt öffnen", "Open unpacked world"}},
{"subtitle_overview",
{"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_nations", {"Länder, Verbände und Simulation", "Countries, associations and simulation"}},
{"subtitle_competitions",
{"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_clubs", {"Stammdaten, Farben und Spielstätten", "Details, colours and home grounds"}},
{"subtitle_players",
{"Spielerdaten und quellengerechte Spielwerte", "Player details and source-specific attributes"}},
{"subtitle_stadiums", {"Kapazität und Ausstattung", "Capacity and facilities"}},
{"subtitle_staff", {"Schiedsrichter und ihre Eigenschaften", "Referees and their attributes"}},
{"subtitle_assets", {"Wappen, Porträts und Pokale", "Crests, portraits and trophies"}},
{"subtitle_review", {"Quellen vergleichen", "Compare sources"}},
{"subtitle_roster", {"Vollständige Kader ohne Datenverlust", "Complete squads without losing data"}},
{"subtitle_changes",
{"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"preservation_note",
{"Quellen, Bilder und Erweiterungen bleiben erhalten. Bearbeitungen "
"ändern keine Originalinstallation.",
"Sources, images and extensions are retained. Edits do not change the "
"original installation."}},
{"unrated_hint",
{"Keine belegten Spielwerte vorhanden. Es werden keine Stärken "
"erfunden.",
"No sourced attributes available. Ratings are not invented."}},
{"crop_hint",
{"Im Bild einen Rahmen ziehen oder den Ausschnitt als Werte eingeben. "
"Ohne Zuschnitt bleibt die Originalauflösung erhalten.",
"Drag a rectangle on the image or enter crop values. Without cropping, "
"the original resolution is retained."}},
{"video_failed",
{"Die Grafikausgabe konnte nicht initialisiert werden.", "Graphics initialization failed."}},
{"ui_assets_missing",
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
"Editor interface files are missing. Please extract the complete "
"package."}},
{"dialog_failed",
{"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"invalid_attributes", {"Ungültige Spielwerte.", "Invalid player attributes."}},
{"app", {"OpenBMH Editor", "OpenBMH Editor"}},
{"editor_tagline", {"OBW-Dateneditor", "OBW world editor"}},
{"overview", {"Übersicht", "Overview"}},
{"nations", {"Länder", "Countries"}},
{"competitions", {"Ligen & Pokale", "Leagues & cups"}},
{"clubs", {"Vereine", "Clubs"}},
{"players", {"Spieler", "Players"}},
{"roster", {"Kader", "Squads"}},
{"stadiums", {"Stadien", "Stadiums"}},
{"staff", {"Schiedsrichter", "Referees"}},
{"assets", {"Bilder", "Images"}},
{"review", {"Prüfen", "Review"}},
{"changes", {"Änderungen", "Changes"}},
{"options", {"Optionen", "Options"}},
{"open", {"Öffnen", "Open"}},
{"open_world", {"OBW öffnen", "Open OBW"}},
{"import_legacy", {"BMH / FLTD importieren", "Import BMH / FLTD"}},
{"new_world", {"Neue Welt", "New world"}},
{"demo", {"Demo öffnen", "Open demo"}},
{"save", {"Speichern", "Save"}},
{"save_as", {"Speichern unter …", "Save as …"}},
{"undo", {"Rückgängig", "Undo"}},
{"redo", {"Wiederholen", "Redo"}},
{"search", {"Suchen …", "Search …"}},
{"all", {"Alle", "All"}},
{"all_nations", {"Alle Länder", "All countries"}},
{"all_leagues", {"Alle Ligen", "All leagues"}},
{"all_clubs", {"Alle Vereine", "All clubs"}},
{"add", {"Hinzufügen", "Add"}},
{"duplicate", {"Duplizieren", "Duplicate"}},
{"delete", {"Löschen", "Delete"}},
{"apply", {"Anwenden", "Apply"}},
{"cancel", {"Abbrechen", "Cancel"}},
{"close", {"Schließen", "Close"}},
{"confirm", {"Bestätigen", "Confirm"}},
{"discard", {"Verwerfen", "Discard"}},
{"unknown", {"Unbekannt", "Unknown"}},
{"empty", {"Keine Einträge", "No records"}},
{"select_record", {"Datensatz auswählen", "Select a record"}},
{"name", {"Name", "Name"}},
{"short_name", {"Kurzname", "Short name"}},
{"first", {"Vorname", "First name"}},
{"last", {"Nachname", "Last name"}},
{"known_as", {"Anzeigename", "Known as"}},
{"nation", {"Land", "Country"}},
{"nationalities", {"Nationalitätsangaben", "Nationality claims"}},
{"competition", {"Liga", "League"}},
{"team", {"Verein", "Club"}},
{"stadium", {"Stadion", "Stadium"}},
{"born", {"Geburtsdatum", "Date of birth"}},
{"age_at_start", {"Alter zum Saisonbeginn", "Age at season start"}},
{"positions", {"Position", "Position"}},
{"gk", {"Tor", "Goalkeeper"}},
{"def", {"Abwehr", "Defender"}},
{"mid", {"Mittelfeld", "Midfielder"}},
{"fwd", {"Sturm", "Forward"}},
{"squad_number", {"Rückennummer", "Shirt number"}},
{"squad_order", {"Kaderplatz", "Squad order"}},
{"attribute_set", {"Attributsystem", "Attribute set"}},
{"attributes", {"Spielwerte", "Attributes"}},
{"type", {"Art", "Type"}},
{"tier", {"Spielklasse", "Tier"}},
{"visible", {"Sichtbare Liga", "Visible league"}},
{"playable", {"Ligen vollständig simulieren", "Fully simulated leagues"}},
{"confederation", {"Verband", "Confederation"}},
{"founded", {"Gründungsjahr", "Founded"}},
{"capacity", {"Kapazität", "Capacity"}},
{"total", {"Gesamt", "Total"}},
{"standing", {"Stehplätze", "Standing"}},
{"seated", {"Sitzplätze", "Seated"}},
{"boxes", {"Logen", "Boxes"}},
{"owner", {"Eigentümer", "Owner"}},
{"colors", {"Vereinsfarben", "Club colours"}},
{"role", {"Rolle", "Role"}},
{"strictness", {"Strenge", "Strictness"}},
{"strength", {"Stärke", "Strength"}},
{"technique", {"Technik", "Technique"}},
{"condition", {"Kondition", "Condition"}},
{"form", {"Form", "Form"}},
{"overall", {"Gesamtstärke", "Overall"}},
{"tacticalawareness", {"Taktisches Verständnis", "Tactical awareness"}},
{"potential", {"Potenzial", "Potential"}},
{"acceleration", {"Antritt", "Acceleration"}},
{"sprintspeed", {"Sprinttempo", "Sprint speed"}},
{"positioning", {"Offensivstellung", "Attacking position"}},
{"finishing", {"Abschluss", "Finishing"}},
{"shotpower", {"Schusskraft", "Shot power"}},
{"longshots", {"Fernschüsse", "Long shots"}},
{"volleys", {"Volleys", "Volleys"}},
{"penalties", {"Elfmeter", "Penalties"}},
{"crossing", {"Flanken", "Crossing"}},
{"shortpassing", {"Kurzpass", "Short passing"}},
{"longpassing", {"Langpass", "Long passing"}},
{"curve", {"Effet", "Curve"}},
{"freekickaccuracy", {"Freistöße", "Free kicks"}},
{"vision", {"Übersicht", "Vision"}},
{"dribbling", {"Dribbling", "Dribbling"}},
{"ballcontrol", {"Ballkontrolle", "Ball control"}},
{"agility", {"Beweglichkeit", "Agility"}},
{"balance", {"Balance", "Balance"}},
{"reactions", {"Reaktion", "Reactions"}},
{"composure", {"Ruhe am Ball", "Composure"}},
{"interceptions", {"Abfangen", "Interceptions"}},
{"headingaccuracy", {"Kopfball", "Heading"}},
{"standingtackle", {"Zweikampf", "Standing tackle"}},
{"slidingtackle", {"Grätsche", "Sliding tackle"}},
{"defensiveawareness", {"Defensivstellung", "Defensive awareness"}},
{"jumping", {"Sprungkraft", "Jumping"}},
{"stamina", {"Ausdauer", "Stamina"}},
{"aggression", {"Aggressivität", "Aggression"}},
{"gkdiving", {"TW-Hechten", "GK diving"}},
{"gkhandling", {"TW-Fangen", "GK handling"}},
{"gkkicking", {"TW-Abschlag", "GK kicking"}},
{"gkpositioning", {"TW-Stellung", "GK positioning"}},
{"gkreflexes", {"TW-Reflexe", "GK reflexes"}},
{"bonus", {"Bonus", "Bonus"}},
{"teamplay", {"Teamspiel", "Team play"}},
{"speed", {"Schnelligkeit", "Speed"}},
{"shooting", {"Schuss", "Shooting"}},
{"passing", {"Pass", "Passing"}},
{"tackling", {"Zweikampf", "Tackling"}},
{"free_kick", {"Freistoß", "Free kick"}},
{"corner", {"Ecke", "Corner"}},
{"yes", {"Ja", "Yes"}},
{"no", {"Nein", "No"}},
{"league", {"Liga", "League"}},
{"cup", {"Pokal", "Cup"}},
{"national", {"Nationalmannschaft", "National team"}},
{"club", {"Verein", "Club"}},
{"foreign", {"Auslandsverein", "Foreign club"}},
{"amateur", {"Amateur", "Amateur"}},
{"image_import", {"Bild importieren", "Import image"}},
{"image_edit", {"Bild bearbeiten", "Edit image"}},
{"image_view", {"Bildvorschau", "Image preview"}},
{"view_asset", {"Zum Asset", "View asset"}},
{"image_export", {"PNG exportieren", "Export PNG"}},
{"angle", {"Drehwinkel", "Rotation"}},
{"flip_x", {"Horizontal spiegeln", "Flip horizontally"}},
{"flip_y", {"Vertikal spiegeln", "Flip vertically"}},
{"crop", {"Zuschnitt", "Crop"}},
{"free", {"Frei", "Free"}},
{"reset", {"Zurücksetzen", "Reset"}},
{"source", {"Quelle", "Source"}},
{"original", {"Original", "Original"}},
{"preview", {"Vorschau", "Preview"}},
{"language", {"Sprache", "Language"}},
{"theme", {"Darstellung", "Theme"}},
{"mcp_enabled", {"MCP-Server aktivieren", "Enable MCP server"}},
{"mcp_port", {"Port", "Port"}},
{"copy_connection", {"Verbindung kopieren", "Copy connection"}},
{"mcp_local", {"Lokal auf diesem Rechner", "Local to this computer"}},
{"online", {"Aktiv", "Online"}},
{"offline", {"Aus", "Offline"}},
{"saved", {"Gespeichert", "Saved"}},
{"unsaved", {"Ungespeichert", "Unsaved"}},
{"not_playable", {"Editorwelt · noch nicht im Spiel startbar", "Editor world · not yet playable"}},
{"workspace", {"Deine Fußballwelt", "Your football world"}},
{"welcome",
{"Stammdaten bearbeiten. Quellen erhalten. Neues gestalten.",
"Edit the details. Keep the sources. Build something new."}},
{"welcome_hint",
{"Öffne eine OBW-Welt, importiere BMH oder Football Limited oder "
"probiere die Demo aus.",
"Open an OBW world, import BMH or Football Limited, or explore the "
"demo."}},
{"records", {"Einträge", "records"}},
{"previous", {"Zurück", "Previous"}},
{"next", {"Weiter", "Next"}},
{"details", {"Eigenschaften", "Properties"}},
{"provenance", {"Herkunft & Hinweise", "Sources & notes"}},
{"resolve", {"Auswahl übernehmen", "Use selected value"}},
{"resolved", {"Erledigt", "Resolved"}},
{"unresolved", {"Offen", "Open"}},
{"review_hint",
{"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"roster_hint",
{"Verein wählen, Spieler verschieben oder zwei Spieler tauschen.",
"Choose a club, move a player or swap two players."}},
{"move_player", {"Spieler verschieben", "Move player"}},
{"remember_player", {"Zum Tausch merken", "Remember for swap"}},
{"swap_player", {"Mit gemerktem Spieler tauschen", "Swap with remembered player"}},
{"compatibility24", {"24-Spieler-Ansicht", "24-player view"}},
{"validate", {"Welt prüfen", "Validate world"}},
{"warnings", {"Hinweise", "Warnings"}},
{"errors", {"Fehler", "Errors"}},
{"no_changes", {"Noch keine Änderungen", "No changes yet"}},
{"dirty_prompt", {"Änderungen speichern?", "Save changes?"}},
{"dirty_detail",
{"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"delete_prompt", {"Datensatz wirklich löschen?", "Delete this record?"}},
{"new_name", {"Name des neuen Datensatzes", "Name of the new record"}},
{"new_title", {"Neue Fußballwelt", "New football world"}},
{"start_date", {"Saisonbeginn", "Season start"}},
{"title", {"Titel", "Title"}},
{"currency", {"Währung", "Currency"}},
{"loading", {"Wird geladen …", "Loading …"}},
{"saved_ok", {"Welt gespeichert", "World saved"}},
{"copied", {"In die Zwischenablage kopiert", "Copied to clipboard"}},
{"error", {"Fehler", "Error"}},
{"open_failed", {"Die Datei konnte nicht geöffnet werden.", "The file could not be opened."}},
{"save_failed",
{"Speichern fehlgeschlagen. Die bisherige Datei bleibt erhalten.",
"Saving failed. The previous file is retained."}},
{"invalid_archive",
{"Das Archiv ist beschädigt oder wird nicht unterstützt.",
"The archive is damaged or unsupported."}},
{"unsupported_archive",
{"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"archive_limit",
{"Das Datenpaket überschreitet die unterstützten Grenzen.",
"The data package exceeds the supported limits."}},
{"unsafe_path", {"Unzulässiger Dateipfad.", "Invalid file path."}},
{"size_limit", {"Die Datei ist zu groß.", "The file is too large."}},
{"missing_manifest", {"Keine OBW-Welt gefunden.", "No OBW world found."}},
{"not_world", {"Bitte eine OBW-Startdatenbank öffnen.", "Please open an OBW starting world."}},
{"unsupported_version",
{"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"invalid_json", {"Die JSON-Daten sind ungültig.", "The JSON data is invalid."}},
{"invalid_table", {"Eine Datentabelle ist ungültig.", "A data table is invalid."}},
{"unknown_table", {"Unbekannter Datenbereich.", "Unknown data table."}},
{"missing_asset", {"Das Bild fehlt im Datenpaket.", "The image is missing from the package."}},
{"unsafe_asset", {"Das Bild kann nicht übernommen werden.", "The image cannot be imported."}},
{"invalid_image", {"Das Bild konnte nicht gelesen werden.", "The image could not be decoded."}},
{"image_dimensions",
{"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"invalid_transform",
{"Der Bildzuschnitt oder Drehwinkel ist ungültig.", "The image crop or rotation is invalid."}},
{"external_svg_resource",
{"Das SVG verweist auf externe Bilddateien. Bitte ein eigenständiges "
"SVG verwenden.",
"The SVG references external images. Please use a self-contained "
"SVG."}},
{"image_encode_failed",
{"Das bearbeitete Bild konnte nicht erstellt werden.", "The edited image could not be created."}},
{"obw_only",
{"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"preserve_source",
{"Bitte unter einem neuen Namen speichern. Der Classic-Import bleibt "
"erhalten.",
"Please save under a new name. The Classic source is retained."}},
{"validation_failed",
{"Bitte zuerst die angezeigten Datenfehler beheben.", "Please fix the reported data errors first."}},
{"invalid_date",
{"Bitte ein gültiges Datum im Format JJJJ-MM-TT eingeben.",
"Please enter a valid date in YYYY-MM-DD format."}},
{"duplicate_id",
{"Eine Kennung fehlt oder ist mehrfach vorhanden.", "An identifier is missing or duplicated."}},
{"missing_reference", {"Ein verknüpfter Datensatz fehlt.", "A referenced record is missing."}},
{"attribute_range",
{"Ein Spielwert liegt außerhalb seines Wertebereichs.",
"An attribute is outside its declared range."}},
{"unknown_attribute_set",
{"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"missing_name", {"Ein Name fehlt.", "A name is missing."}},
{"missing_birthday", {"Das Geburtsdatum ist unbekannt.", "The date of birth is unknown."}},
{"review_open", {"Eine Quellenfrage ist noch offen.", "A source decision is still open."}},
{"record_referenced",
{"Der Datensatz wird noch verwendet. Bitte zuerst die Verknüpfungen "
"ändern.",
"The record is still referenced. Please update its links first."}},
{"record_missing", {"Der Datensatz wurde nicht gefunden.", "The record was not found."}},
{"immutable_id",
{"Kennungen können nicht nachträglich geändert werden.",
"Identifiers cannot be changed after creation."}},
{"stale_revision",
{"Die Daten wurden inzwischen geändert. Bitte die Ansicht "
"aktualisieren.",
"The data has changed. Please refresh the view."}},
{"invalid_change", {"Diese Änderung ist nicht gültig.", "This change is invalid."}},
{"nothing_to_undo", {"Keine Änderung zum Rückgängigmachen.", "There is nothing to undo."}},
{"nothing_to_redo", {"Keine Änderung zum Wiederholen.", "There is nothing to redo."}},
{"no_world", {"Bitte zuerst eine Welt öffnen.", "Please open a world first."}},
{"invalid_settings", {"Die Optionen sind ungültig.", "The options are invalid."}},
{"output_parent_missing", {"Der Zielordner existiert nicht.", "The output folder does not exist."}},
{"destination_exists", {"Die Zieldatei existiert bereits.", "The destination file already exists."}},
{"duplicate_entry",
{"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"server_failed",
{"MCP konnte nicht gestartet werden. Bitte den Port prüfen.",
"MCP could not be started. Please check the port."}},
{"source_changed",
{"Die Quelldatei wurde außerhalb des Editors geändert. Bitte Speichern "
"unter verwenden.",
"The source file changed outside the editor. Please use Save as."}}};
const auto found = words.find(key);
if (found == words.end())
return key;
return language == "en" ? found->second.second : found->second.first;
}
} // namespace bmh::editor
-16
View File
@@ -1,16 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
struct Options {
std::string language = "de", theme = "midnight", token;
bool mcp_enabled = true;
int mcp_port = 8765;
fs::path settings_file;
static Options load(fs::path override_path = {});
Json json(bool include_secret = false) const;
void apply(const Json &);
void save() const;
};
std::string tr(const std::string &language, const std::string &key);
} // namespace bmh::editor
-250
View File
@@ -1,250 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/regulations.hpp"
#include "editor/world.hpp"
#include <algorithm>
namespace bmh::editor {
namespace {
Json object(const Json &value, const char *key) {
const auto found = value.find(key);
return found != value.end() && found->is_object() ? *found : Json::object();
}
Json array(const Json &value, const char *key) {
const auto found = value.find(key);
return found != value.end() && found->is_array() ? *found : Json::array();
}
std::optional<int> number(const Json &value) {
if (!value.is_number_integer() || value.get<double>() < 0 || value.get<double>() > 100000)
return {};
return value.get<int>();
}
int count_teams(const Json &comp) {
if (comp.value("members", Json()).is_array() && !comp["members"].empty())
return int(comp["members"].size());
for (const auto &stage : array(comp, "stages"))
if (auto value = number(stage.value("teams", Json())))
return *value;
return 0;
}
} // namespace
Json regulation_view(const World &world, const Json &args) {
const auto language = str(args, "language", "de"), search = folded(str(args, "search")),
nation = str(args, "nation"), chosen = str(args, "competition");
if (language != "de" && language != "en")
throw Error("invalid_change");
std::map<std::string, const Json *> competitions;
std::map<int, const Json *> indexed;
for (const auto &comp : world.rows("competitions")) {
competitions[str(comp, "id")] = &comp;
const auto legacy = object(comp, "x-legacy");
if (const auto index = number(legacy.value("league_index", Json()));
index && str(comp, "type") == "league")
indexed[*index] = &comp;
}
const Json *ladder = nullptr;
bool classic = false;
for (const auto &rule : world.rows("rules")) {
if (str(rule, "type") == "legacy_ladder")
ladder = &rule;
if (str(rule, "type") == "classic_runtime" &&
str(rule, "qualifications") == "classic-season-entrants@1")
classic = true;
}
auto target = [&](const std::string &id) {
return Json{{"id", id},
{"name", competitions.contains(id) ? world.title(*competitions.at(id), language) : id}};
};
std::map<std::string, Json> movement, qualification;
std::set<std::string> movement_known;
// Explicit OBW movement always takes precedence over compatibility policy.
for (const auto &[id, comp] : competitions) {
movement[id] = Json::array();
qualification[id] = Json::array();
if (comp->contains("movement") && (*comp)["movement"].is_array()) {
movement_known.insert(id);
for (const auto &definition : (*comp)["movement"]) {
const auto to = str(definition, "to");
const auto role = str(definition, "role");
std::string kind = role == "challenger" || role == "defender" || role == "incumbent"
? "playoff"
: "movement";
if (kind == "movement" && competitions.contains(to)) {
auto from_tier = number(comp->value("tier", Json()));
auto to_tier = number(competitions.at(to)->value("tier", Json()));
if (from_tier && to_tier && str(*competitions.at(to), "type") == "league")
kind = *to_tier < *from_tier ? "promotion"
: *to_tier > *from_tier ? "relegation"
: "movement";
}
movement[id].push_back({{"kind", kind},
{"ranks", definition.value("ranks", Json())},
{"targets", Json::array({target(to)})},
{"source", "declared"},
{"definition", definition}});
}
}
}
if (classic && ladder) {
auto span = [&](const char *first_key, const char *count_key, int group) {
std::vector<const Json *> result;
const auto first = ladder->value(first_key, Json()), count = ladder->value(count_key, Json());
if (!first.is_array() || !count.is_array() || size_t(group) >= first.size() ||
size_t(group) >= count.size())
return result;
const auto start = number(first[group]), length = number(count[group]);
if (!start || !length || *length < 1 || *length > 24)
return result;
for (int i = *start; i < *start + *length; ++i) {
if (!indexed.contains(i))
return std::vector<const Json *>{};
result.push_back(indexed.at(i));
}
return result;
};
// The versioned Classic ladder has four domestic movement groups.
// Its final group draws newcomers; below[3] is not a foreign league
// destination. License withdrawals can change the actual season result.
for (int group = 0; group < 4; ++group) {
const auto upper = span("first_league", "league_count", group);
const auto lower = group < 3 ? span("below", "below_count", group) : std::vector<const Json *>{};
if (upper.empty() || (group < 3 && lower.empty()))
continue;
int down_total = 0;
bool complete = true;
for (const auto *comp : upper) {
const auto down = number(object(*comp, "x-legacy").value("relegation_places", Json()));
if (!down || *down > count_teams(*comp)) {
complete = false;
break;
}
down_total += *down;
}
if (!complete)
continue;
Json destinations = Json::array(), origins = Json::array();
for (const auto *comp : lower)
destinations.push_back(target(str(*comp, "id")));
for (const auto *comp : upper)
origins.push_back(target(str(*comp, "id")));
for (const auto *comp : upper) {
const auto id = str(*comp, "id");
if (comp->contains("movement"))
continue;
movement_known.insert(id);
const int down = *number(object(*comp, "x-legacy")["relegation_places"]);
if (down)
movement[id].push_back({{"kind", "relegation"},
{"places", down},
{"ranks", {count_teams(*comp) - down + 1, count_teams(*comp)}},
{"targets", destinations},
{"newcomer_pool", group == 3},
{"pool_size", ladder->value("newcomer_count", Json())},
{"conditional_playoffs", lower.size() > 1},
{"source", "classic-ladder@1"}});
}
if (!lower.empty())
for (const auto *comp : lower) {
const auto id = str(*comp, "id");
if (comp->contains("movement"))
continue;
const bool playoffs = lower.size() > 1;
const int up = playoffs ? 1 : down_total;
if (up > count_teams(*comp) || down_total % int(lower.size()) != 0)
continue;
movement_known.insert(id);
if (up)
movement[id].push_back({{"kind", "promotion"},
{"places", up},
{"ranks", {1, up}},
{"targets", origins},
{"source", "classic-ladder@1"}});
if (playoffs)
movement[id].push_back({{"kind", "playoff"},
{"ranks", nullptr},
{"selector", "classic-playoff-winner"},
{"conditional_playoffs", true},
{"targets", origins},
{"source", "classic-ladder@1"}});
}
}
}
auto slots = [&](const std::string &to, const std::string &stage, const Json &definitions) {
if (!definitions.is_array())
return;
for (const auto &definition : definitions) {
const auto from = str(definition, "from"), holder = str(definition, "holder");
// Fixed team lists are already participants, not a qualification
// rule. Keep the untouched stages available separately below.
if (from.empty() && holder.empty() && !definition.contains("winner") &&
!definition.contains("resolver"))
continue;
const auto destination = str(definition, "to", to);
const Json rule{
{"from", target(from)},
{"to", target(destination)},
{"stage", str(definition, "stage", stage)},
{"definition", definition},
{"source", str(definition, "resolver").empty() ? "declared" : str(definition, "resolver")}};
qualification[destination].push_back(rule);
if (competitions.contains(from) && from != destination)
qualification[from].push_back(rule);
}
};
for (const auto &[id, comp] : competitions) {
slots(id, "", comp->value("slots", Json::array()));
for (const auto &stage : array(*comp, "stages"))
slots(id, str(stage, "id"), stage.value("slots", Json::array()));
}
Json items = Json::array();
for (const auto &[id, comp] : competitions) {
const auto label = world.title(*comp, language);
if ((!chosen.empty() && id != chosen) || (!nation.empty() && str(*comp, "nation") != nation) ||
(!search.empty() && folded(label).find(search) == std::string::npos &&
folded(id).find(search) == std::string::npos))
continue;
Json policy;
if (classic) {
const auto index = number(object(*comp, "x-legacy").value("league_index", Json()));
const bool declared =
std::any_of(qualification[id].begin(), qualification[id].end(),
[](const auto &rule) { return str(rule, "source") != "classic-entry@1"; });
// Registry for classic-season-entrants@1, the named format policy
// consumed by the existing Classic adapter. These quotas are not
// the historical x-legacy.europe_places prediction/colouring field.
if (!declared && index && (*index == 0 || (*index >= 5 && *index <= 8)))
policy = {{"id", "classic-season-entrants@1"},
{"uefa_base_places", *index == 8 ? 3 : 4},
{"champion", true},
{"cup_winner_or_finalist", true},
{"titleholder_adjustments", true}};
else if (!declared &&
str(object(*comp, "classic"), "qualification") == "classic-season-entrants@1")
policy = {{"id", "classic-season-entrants@1"}, {"runtime_participants", true}};
if (index && *index >= 5)
movement_known.insert(id); // Closed foreign Classic leagues.
}
items.push_back({{"id", id},
{"name", label},
{"nation", str(*comp, "nation")},
{"type", str(*comp, "type")},
{"tier", comp->value("tier", Json())},
{"teams", count_teams(*comp)},
{"movement_defined", movement_known.contains(id)},
{"movement", movement[id]},
{"qualification", qualification[id]},
{"classic_qualification", policy},
{"stages", array(*comp, "stages")},
{"record", *comp}});
}
std::stable_sort(items.begin(), items.end(), [](const auto &a, const auto &b) {
const auto av = folded(str(a, "name")), bv = folded(str(b, "name"));
return av == bv ? str(a, "id") < str(b, "id") : av < bv;
});
return {{"read_only", true},
{"items", items},
{"rules", world.rows("rules")},
{"classic_policy", classic},
{"date", world.manifest.value("start_date", Json())}};
}
} // namespace bmh::editor
-10
View File
@@ -1,10 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
class World;
// Presentation of declared rules and versioned Classic policy, never a season
// simulation or an editable replacement for world/rules.json.
Json regulation_view(const World &, const Json &args);
} // namespace bmh::editor
-597
View File
@@ -1,597 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/session.hpp"
#include "content/digest.hpp"
#include "editor/comparison.hpp"
#include "editor/images.hpp"
#include "editor/regulations.hpp"
#include <algorithm>
#include <limits>
namespace bmh::editor {
namespace {
bool editable(const std::string &name) {
return name == "nations" || name == "competitions" || name == "clubs" || name == "players" || name == "stadiums" ||
name == "staff" || name == "assets" || name == "review" || name == "image-edits" || name == "manifest";
}
Json defaults(const std::string &table, const std::string &name) {
auto localized = Json{{"default", name}};
if (table == "players")
return {{"name", {{"first", ""}, {"last", name}}},
{"born", nullptr},
{"nationalities", Json::array()},
{"positions", Json::array()},
{"attributes", Json::object()},
{"attribute_set", "unrated@1"}};
if (table == "clubs")
return {{"name", localized}, {"type", "club"}, {"nation", nullptr}, {"colors", Json::array()}};
if (table == "nations")
return {{"name", localized}, {"confederation", "other"}, {"playable", false}};
if (table == "competitions")
return {{"name", localized}, {"type", "league"}, {"nation", nullptr}, {"tier", 1},
{"visible", true}, {"members", Json::array()}, {"stages", Json::array()}};
if (table == "stadiums")
return {{"name", localized}, {"capacity", Json::object()}, {"facilities", Json::object()}};
if (table == "staff")
return {{"name", localized}, {"role", "referee"}, {"attributes", Json::object()}};
return Json::object();
}
std::string prefix(const std::string &table) {
if (table == "nations")
return "nation:";
if (table == "competitions")
return "comp:";
if (table == "assets")
return "asset:";
if (table == "staff")
return "staff:";
if (table == "image-edits")
return "image-edit:";
return table.substr(0, table.size() - 1) + ':';
}
} // namespace
World &Session::world() {
if (!world_)
throw Error("no_world");
return *world_;
}
bool Session::dirty() const { return world_ && state_ != saved_state_; }
Json Session::info() const {
Json result = world_ ? world_->statistics() : Json{{"title", ""}, {"counts", Json::object()}};
result["loaded"] = bool(world_);
result["revision"] = revision_;
result["world_generation"] = world_generation_;
result["dirty"] = dirty();
result["can_undo"] = cursor_ > 0;
result["can_redo"] = cursor_ < history_.size();
result["path"] = utf8(saved_path_);
return result;
}
void Session::replace(World value) {
world_ = std::make_unique<World>(std::move(value));
++world_generation_;
history_.clear();
cursor_ = 0;
++revision_;
state_ = next_state_++;
saved_state_ = world_->source_path.empty() || world_->imported ? 0 : state_;
saved_path_ = world_->source_path.empty() || world_->imported || !fs::is_regular_file(world_->source_path)
? fs::path{}
: world_->source_path;
if (!saved_path_.empty() && fs::is_regular_file(saved_path_)) {
saved_time_ = fs::last_write_time(saved_path_);
saved_size_ = fs::file_size(saved_path_);
}
}
void Session::frame(const Frame &f, bool forward) {
for (const auto &change : f.changes) {
auto value = forward ? change.after : change.before;
if (change.table == "manifest") {
if (value)
world().manifest = *value;
} else
world().change(change.table, change.id, value);
}
for (const auto &file : f.files)
world().store->restore(file.name, forward ? file.after : file.before);
state_ = forward ? f.after : f.before;
}
Json Session::apply(const Json &args, std::vector<FileDelta> files, const std::string &label) {
auto &w = world();
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (!args.contains("changes") || !args["changes"].is_array() || args["changes"].size() > 5000)
throw Error("invalid_change");
Frame transaction;
transaction.label = label;
transaction.files = std::move(files);
transaction.before = state_;
transaction.after = next_state_;
std::map<std::pair<std::string, std::string>, size_t> staged;
Json created = Json::array();
for (const auto &action : args["changes"]) {
const auto name = str(action, "table"), op = str(action, "op", "update");
if (!editable(name))
throw Error("unknown_table");
auto id = str(action, "id");
if (op == "create" && id.empty()) {
id = new_id(prefix(name) + "editor-");
created.push_back(id);
}
if (name == "manifest")
id = "manifest";
auto key = std::make_pair(name, id);
if (!staged.contains(key)) {
const auto *existing = name == "manifest" ? &w.manifest : w.find(name, id);
std::optional<Json> before = existing ? std::optional<Json>(*existing) : std::nullopt;
staged[key] = transaction.changes.size();
transaction.changes.push_back({name, id, before, before});
}
auto &delta = transaction.changes[staged[key]];
if (op == "create") {
if (delta.after || name == "manifest")
throw Error("duplicate_id");
delta.after = defaults(name, str(action, "name"));
if (action.contains("data"))
delta.after->update(action["data"]);
(*delta.after)[name == "assets" ? "key" : "id"] = id;
} else if (op == "delete") {
if (!delta.after)
throw Error("record_missing", {{"table", name}, {"id", id}});
if (name == "manifest")
throw Error("invalid_change");
delta.after.reset();
} else if (op == "update") {
if (!delta.after)
throw Error("record_missing", {{"table", name}, {"id", id}});
const auto set = action.value("set", Json::object());
if (!set.is_object())
throw Error("invalid_change");
for (auto it = set.begin(); it != set.end(); ++it) {
const auto pointer = it.key();
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || pointer.starts_with("/id/") ||
(name == "assets" && pointer == "/key"))
throw Error("immutable_id");
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
pointer != "/languages")
throw Error("immutable_id");
(*delta.after)[Json::json_pointer(pointer)] = it.value();
}
for (const auto &field : action.value("unset", Json::array())) {
auto pointer = field.get<std::string>();
if (pointer.empty() || pointer[0] != '/' || pointer == "/id" || (name == "assets" && pointer == "/key"))
throw Error("immutable_id");
if (name == "manifest" && pointer != "/title" && !pointer.starts_with("/title/") &&
pointer != "/start_date" && pointer != "/currency" && !pointer.starts_with("/currency/") &&
pointer != "/languages")
throw Error("immutable_id");
auto split = pointer.rfind('/');
auto parent = Json::json_pointer(pointer.substr(0, split));
if (delta.after->contains(parent)) {
auto leaf_pointer = Json::json_pointer(pointer);
auto &container = (*delta.after)[parent];
const auto leaf = leaf_pointer.back();
if (container.is_object())
container.erase(leaf);
else if (container.is_array()) {
const auto index = std::stoull(leaf);
if (index < container.size())
container.erase(container.begin() + std::ptrdiff_t(index));
}
}
}
} else
throw Error("invalid_change");
}
transaction.changes.erase(std::remove_if(transaction.changes.begin(), transaction.changes.end(),
[](const Delta &d) { return d.before == d.after; }),
transaction.changes.end());
// Membership is edited once, at the club, and stays consistent in each
// affected league. This derived change belongs to the same undo frame.
std::map<std::string, Json> memberships;
for (const auto &d : transaction.changes)
if (d.table == "clubs") {
const auto old_league = d.before ? str(*d.before, "competition") : "";
const auto new_league = d.after ? str(*d.after, "competition") : "";
if (old_league == new_league)
continue;
for (auto league : {old_league, new_league})
if (!league.empty()) {
auto *comp = w.find("competitions", league);
if (!memberships.contains(league)) {
if (comp)
memberships[league] = *comp;
for (const auto &staged_delta : transaction.changes)
if (staged_delta.table == "competitions" && staged_delta.id == league && staged_delta.after)
memberships[league] = *staged_delta.after;
if (!memberships.contains(league))
throw Error("missing_reference");
}
auto &members = memberships[league]["members"];
if (members.is_null())
members = Json::array();
if (!members.is_array())
throw Error("invalid_change");
members.erase(std::remove(members.begin(), members.end(), Json(d.id)), members.end());
if (league == new_league)
members.push_back(d.id);
}
}
for (auto &[id, after] : memberships) {
bool found = false;
for (auto &d : transaction.changes)
if (d.table == "competitions" && d.id == id) {
d.after = after;
found = true;
break;
}
if (!found)
transaction.changes.push_back({"competitions", id, *w.find("competitions", id), after});
}
if (transaction.changes.empty() && transaction.files.empty())
return {{"changed", false}, {"revision", revision_}, {"created", created}};
try {
frame(transaction, true);
for (auto &change : transaction.changes)
if (!change.after) {
auto refs = w.references(change.id);
if (!refs.empty()) {
Json list = Json::array();
for (auto &[table, id] : refs)
list.push_back({{"table", table}, {"id", id}});
throw Error("record_referenced", {{"references", list}});
}
}
for (const auto &problem : w.validate())
if (problem["severity"] == "error")
throw Error("validation_failed", {{"diagnostics", w.validate()}});
} catch (...) {
frame(transaction, false);
throw;
}
history_.resize(cursor_);
history_.push_back(std::move(transaction));
++cursor_;
++next_state_;
++revision_;
if (history_.size() > 100) {
history_.erase(history_.begin());
--cursor_;
}
return {{"changed", true}, {"revision", revision_}, {"created", created}};
}
Json Session::import_image(const Json &args) {
auto &w = world();
std::string original, extension, original_name;
const auto source_key = str(args, "source_key", str(args, "key"));
const auto *existing = w.find("assets", source_key);
if (args.contains("file")) {
original = read_file(path(str(args, "file")));
extension = folded(utf8(path(str(args, "file")).extension()));
original_name = utf8(path(str(args, "file")).filename());
} else if (source_key.starts_with("portrait:") && w.find("players", source_key.substr(9))) {
auto value = asset_bytes(source_key);
original = std::move(value.first);
extension = value.second;
original_name = w.title(*w.find("players", source_key.substr(9)));
} else {
if (!existing)
throw Error("record_missing");
auto source = str(existing->value("x-editor", Json::object()), "original");
if (source.empty())
source = w.asset_file(source_key);
original = w.store->read(source);
extension = folded(utf8(path(source).extension()));
original_name = text(existing->value("name", Json(str(args, "key"))));
}
if (extension != ".png" && extension != ".jpg" && extension != ".jpeg" && extension != ".webp" &&
extension != ".svg")
throw Error("invalid_image");
auto result = images::transform(original, extension, args.value("transform", Json::object()));
auto key = str(args, "key");
const auto target = args.value("target", Json::object());
const auto target_table = str(target, "table");
const auto target_field = str(target, "field",
target_table == "players" || target_table == "staff" ? "photo"
: target_table == "competitions" ? "trophy"
: "crest");
if (key.empty()) {
if (!target.empty()) {
auto id = str(target, "id");
auto table = str(target, "table");
key = "asset:" + table + '/' + id + '/' + target_field;
} else
key = new_id("asset:uploaded/");
}
if (!target.empty() && w.find("assets", key)) {
for (const auto &[table, id] : w.references(key))
if (table != str(target, "table") || id != str(target, "id")) {
key = "asset:editor/" + target_table + '/' + str(target, "id") + '/' + target_field;
break;
}
}
const auto original_hash = content::sha256(original), edited_hash = content::sha256(result.bytes);
auto source_file = "x-editor/originals/" + original_hash + extension;
auto output_file = "assets/edited/" + edited_hash + result.extension;
std::vector<FileDelta> files;
for (auto &[name, data] :
std::vector<std::pair<std::string, std::string>>{{source_file, original}, {output_file, result.bytes}}) {
if (!w.store->contains(name))
files.push_back({name, w.store->overlay(name), std::make_shared<const std::string>(std::move(data))});
}
Json row{
{"key", key},
{"name", {{"default", original_name}}},
{"files", {{result.extension == ".svg" ? "svg" : "native", output_file}}},
{"width", result.width},
{"height", result.height},
{"source", "user-import"},
{"author", "user-supplied"},
{"license", "user-supplied"},
{"kind", result.extension == ".svg" ? "vector" : "raster"},
{"x-editor", {{"original", source_file}, {"original_sha256", original_hash}, {"transform", result.recipe}}}};
if (!args.contains("file") && !source_key.empty() && source_key != key)
row["x-editor"]["source_asset"] = source_key;
Json changes = Json::array();
if (const auto *before = w.find("assets", key)) {
auto after = *before;
after.update(row);
Json set = Json::object();
for (auto it = after.begin(); it != after.end(); ++it)
if (it.key() != "key")
set['/' + it.key()] = it.value();
changes.push_back({{"op", "update"}, {"table", "assets"}, {"id", key}, {"set", set}});
} else
changes.push_back({{"op", "create"}, {"table", "assets"}, {"id", key}, {"data", row}});
if (!target.empty())
changes.push_back({{"op", "update"},
{"table", str(target, "table")},
{"id", str(target, "id")},
{"set", {{'/' + target_field, key}}}});
Json command{{"changes", changes}};
if (args.contains("expected_revision"))
command["expected_revision"] = args["expected_revision"];
auto response = apply(command, std::move(files), "image_import");
response["key"] = key;
return response;
}
std::pair<std::string, std::string> Session::asset_bytes(const std::string &key) const {
std::lock_guard guard(mutex_);
if (!world_)
return {images::silhouette(), ".svg"};
if (key.starts_with("portrait:")) {
const auto *player = world_->find("players", key.substr(9));
if (player) {
auto photo = world_->asset_file(str(*player, "photo"));
if (!photo.empty())
return {world_->store->read(photo), utf8(path(photo).extension())};
auto recipe = player->value("appearance", Json::object());
auto set = str(recipe, "set");
const auto file = "assets/portrait-sets/" + set + "/set.json";
if (safe_name(file) && world_->store->contains(file)) {
const auto parts = Json::parse(world_->store->read(file));
int width = parts.value("width", 0), height = parts.value("height", 0);
if (width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
uint64_t(width) * height > 32ull * 1024 * 1024)
throw Error("image_dimensions");
images::Raster portrait{width, height, std::vector<uint8_t>(size_t(width) * height * 4)};
auto paint = [&](const std::string &asset, int x, int y) {
auto input = world_->asset_file(asset);
if (input.empty())
return;
auto layer = images::decode(world_->store->read(input), utf8(path(input).extension()));
for (int sy = 0; sy < layer.height; ++sy)
for (int sx = 0; sx < layer.width; ++sx) {
int dx = x + sx, dy = y + sy;
if (dx < 0 || dy < 0 || dx >= width || dy >= height)
continue;
const auto *src = layer.pixels.data() + (size_t(sy) * layer.width + sx) * 4;
auto *dst = portrait.pixels.data() + (size_t(dy) * width + dx) * 4;
const unsigned alpha = src[3] * 255u + dst[3] * (255u - src[3]);
for (int c = 0; c < 3; ++c)
dst[c] =
alpha
? uint8_t((src[c] * src[3] * 255u + dst[c] * dst[3] * (255u - src[3])) / alpha)
: 0;
dst[3] = uint8_t((alpha + 127) / 255);
}
};
auto backgrounds = parts.value("backgrounds", Json::array());
auto background = recipe.value("background", size_t(0));
if (background < backgrounds.size()) {
const auto &b = backgrounds[background];
paint(str(b, "asset"), b.value("x", 0), b.value("y", 0));
}
auto layers = parts.value("layers", Json::array()), choices = recipe.value("layers", Json::array());
for (size_t i = 0; i < std::min(layers.size(), choices.size()); ++i) {
auto options = layers[i].value("parts", Json::array());
const auto choice = choices[i].get<size_t>();
if (choice < options.size())
paint(options[choice].get<std::string>(), layers[i].value("x", 0), layers[i].value("y", 0));
}
return {images::encode_png(portrait), ".png"};
}
}
return {images::silhouette(), ".svg"};
}
auto file = key.starts_with("asset:") ? world_->asset_file(key) : key;
if (file.empty() || !world_->store->contains(file))
return {images::silhouette(), ".svg"};
return {world_->store->read(file), utf8(path(file).extension())};
}
Json Session::execute(const std::string &command, const Json &args) {
std::lock_guard guard(mutex_);
if (!args.is_object())
throw Error("invalid_change");
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (command == "info")
return info();
if (command == "open" || command == "new" || command == "demo") {
if (dirty() && !args.value("discard", false))
throw Error("unsaved_changes");
if (command == "open")
replace(World::open(path(str(args, "path")), str(args, "start_date", "2026-07-01")));
else
replace(command == "demo" ? World::demo() : World::blank(str(args, "title", "Untitled world")));
return info();
}
auto &w = world();
if (command == "list")
return w.query(args);
if (command == "compare") {
const Json key{{"table", str(args, "table", "players")},
{"attribute_set", str(args, "attribute_set")},
{"language", str(args, "language", "de")}};
if (comparison_revision_ != revision_ || comparison_key_ != key.dump()) {
auto data = comparison_data(w, key);
comparison_cache_ = std::move(data);
comparison_key_ = key.dump();
comparison_revision_ = revision_;
}
auto result = query_comparison(comparison_cache_, args);
result["revision"] = revision_;
return result;
}
if (command == "get") {
auto name = str(args, "table"), id = str(args, "id");
const auto *found = name == "manifest" ? &w.manifest : w.find(name, id);
if (!found)
throw Error("record_missing");
return {{"record", *found}, {"revision", revision_}};
}
if (command == "rules")
return w.rows("rules");
if (command == "regulations") {
auto result = regulation_view(w, args);
result["revision"] = revision_;
return result;
}
if (command == "validate")
return {{"diagnostics", w.validate()}, {"revision", revision_}};
if (command == "history") {
Json values = Json::array();
for (size_t i = 0; i < history_.size(); ++i) {
Json affected = Json::array();
for (auto &delta : history_[i].changes)
affected.push_back({{"table", delta.table},
{"id", delta.id},
{"before", delta.before ? *delta.before : Json()},
{"after", delta.after ? *delta.after : Json()}});
values.push_back({{"label", history_[i].label}, {"applied", i < cursor_}, {"changes", affected}});
}
return {{"items", values}, {"revision", revision_}};
}
if (command == "apply")
return apply(args);
if (command == "undo" || command == "redo") {
if (args.contains("expected_revision") && args["expected_revision"].get<uint64_t>() != revision_)
throw Error("stale_revision");
if (command == "undo") {
if (!cursor_)
throw Error("nothing_to_undo");
frame(history_[--cursor_], false);
} else {
if (cursor_ >= history_.size())
throw Error("nothing_to_redo");
frame(history_[cursor_++], true);
}
++revision_;
return info();
}
if (command == "save") {
const auto destination = args.contains("path") ? path(str(args, "path")) : saved_path_;
if (destination.empty())
throw Error("output_parent_missing");
if (!saved_path_.empty() && fs::absolute(destination) == fs::absolute(saved_path_) &&
fs::is_regular_file(saved_path_) &&
(fs::last_write_time(saved_path_) != saved_time_ || fs::file_size(saved_path_) != saved_size_))
throw Error("source_changed");
w.save(destination);
saved_path_ = fs::absolute(destination);
saved_time_ = fs::last_write_time(saved_path_);
saved_size_ = fs::file_size(saved_path_);
saved_state_ = state_;
return info();
}
if (command == "roster.move") {
auto person = str(args, "player");
Json set{{"/team", args.value("team", Json())}};
if (args.contains("number"))
set["/squad_number"] = args["number"];
auto change = Json{{"op", "update"}, {"table", "players"}, {"id", person}, {"set", set}};
return apply({{"changes", Json::array({change})}}, {}, "move_player");
}
if (command == "roster.swap") {
auto first = w.find("players", str(args, "first")), second = w.find("players", str(args, "second"));
if (!first || !second || first == second)
throw Error("invalid_change");
Json changes = Json::array();
for (auto pair : {std::pair{first, second}, std::pair{second, first}}) {
Json set;
for (auto field : {"team", "squad_number", "squad_order"})
set['/' + std::string(field)] = pair.second->value(field, Json());
changes.push_back({{"op", "update"}, {"table", "players"}, {"id", (*pair.first)["id"]}, {"set", set}});
}
return apply({{"changes", changes}}, {}, "swap_player");
}
if (command == "roster.order") {
auto team = str(args, "team");
auto order = args.value("players", Json::array());
std::set<std::string> expected, actual;
for (auto &row : w.rows("players"))
if (str(row, "team") == team)
expected.insert(str(row, "id"));
for (auto &row : order)
actual.insert(row.get<std::string>());
if (expected != actual || actual.size() != order.size())
throw Error("invalid_change");
Json changes = Json::array();
for (size_t i = 0; i < order.size(); ++i)
changes.push_back(
{{"op", "update"}, {"table", "players"}, {"id", order[i]}, {"set", {{"/squad_order", i}}}});
return apply({{"changes", changes}}, {}, "roster");
}
if (command == "review.resolve") {
auto record = w.find("review", str(args, "id"));
if (!record)
throw Error("record_missing");
const auto choice = args.value("choice", size_t(0));
auto alternatives = record->value("alternatives", Json::array());
if (choice >= alternatives.size())
throw Error("invalid_change");
const auto chosen = alternatives[choice].at("value");
Json changes =
Json::array({{{"op", "update"},
{"table", "review"},
{"id", str(args, "id")},
{"set", {{"/resolved", true}, {"/selected_index", choice}, {"/chosen_value", chosen}}}}});
if (record->contains("entity") && record->contains("field"))
changes.push_back({{"op", "update"},
{"table", record->value("table", "players")},
{"id", (*record)["entity"]},
{"set", {{str(*record, "field"), chosen}}}});
return apply({{"changes", changes}}, {}, "resolve");
}
if (command == "asset.import" || command == "asset.edit")
return import_image(args);
if (command == "asset.preview") {
auto [bytes, extension] = asset_bytes(str(args, "key"));
auto raster = images::preview(bytes, extension, args.value("transform", Json::object()), 1024);
return {{"mimeType", "image/png"},
{"data", images::base64(images::encode_png(raster))},
{"width", raster.width},
{"height", raster.height}};
}
if (command == "asset.export") {
auto [bytes, extension] = asset_bytes(str(args, "key"));
auto data = images::encode_png(images::decode(bytes, extension, 2048));
auto target = path(str(args, "path"));
if (folded(utf8(target.extension())) != ".png")
throw Error("invalid_image");
write_atomic(target, data);
return {{"path", utf8(target)}};
}
throw Error("invalid_change", {{"command", command}});
}
} // namespace bmh::editor
-48
View File
@@ -1,48 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/world.hpp"
#include <mutex>
namespace bmh::editor {
// One command boundary for native widgets, MCP and synthetic tests. No command
// owns game rules or operates on a live career.
class Session {
public:
Json execute(const std::string &command, const Json &args = Json::object());
std::pair<std::string, std::string> asset_bytes(const std::string &key_or_path) const;
private:
struct Delta {
std::string table, id;
std::optional<Json> before, after;
};
struct FileDelta {
std::string name;
std::shared_ptr<const std::string> before, after;
};
struct Frame {
std::string label;
std::vector<Delta> changes;
std::vector<FileDelta> files;
uint64_t before = 0, after = 0;
};
mutable std::recursive_mutex mutex_;
std::unique_ptr<World> world_;
std::vector<Frame> history_;
size_t cursor_ = 0;
uint64_t revision_ = 0, world_generation_ = 0, state_ = 0, next_state_ = 1, saved_state_ = 0;
fs::path saved_path_;
fs::file_time_type saved_time_{};
uint64_t saved_size_ = 0;
Json comparison_cache_;
std::string comparison_key_;
std::optional<uint64_t> comparison_revision_;
World &world();
bool dirty() const;
Json info() const;
Json apply(const Json &, std::vector<FileDelta> files = {}, const std::string &label = "edit");
void frame(const Frame &, bool forward);
void replace(World value);
Json import_image(const Json &);
};
} // namespace bmh::editor
-75
View File
@@ -1,75 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include <optional>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace bmh::editor {
using Json = nlohmann::ordered_json;
namespace fs = std::filesystem;
struct Error : std::runtime_error {
std::string code;
Json details;
explicit Error(std::string key, Json info = Json::object())
: std::runtime_error(key), code(std::move(key)), details(std::move(info)) {}
};
inline std::string text(const Json &value) {
if (value.is_string())
return value.get<std::string>();
if (value.is_null())
return {};
if (value.is_object()) {
for (auto key : {"default", "known_as", "full"})
if (value.contains(key) && value[key].is_string() && !value[key].get<std::string>().empty())
return value[key].get<std::string>();
if (value.contains("first") || value.contains("last")) {
auto first = value.value("first", Json());
auto last = value.value("last", Json());
return text(first) + (text(first).empty() || text(last).empty() ? "" : " ") + text(last);
}
}
return value.dump();
}
inline std::string str(const Json &object, std::string_view key, const std::string &fallback = {}) {
auto it = object.find(std::string(key));
return it == object.end() || !it->is_string() ? fallback : it->get<std::string>();
}
inline std::string escaped(std::string_view value) {
std::string out;
for (auto c : value)
switch (c) {
case '&':
out += "&amp;";
break;
case '<':
out += "&lt;";
break;
case '>':
out += "&gt;";
break;
case '"':
out += "&quot;";
break;
case '\'':
out += "&#39;";
break;
default:
out += c;
}
return out;
}
std::string utf8(const fs::path &);
fs::path path(std::string_view);
std::string read_file(const fs::path &, uint64_t maximum = 64ull * 1024 * 1024);
void write_atomic(const fs::path &, std::string_view, bool overwrite = true);
std::string new_id(const std::string &prefix);
std::string folded(std::string value);
bool safe_name(std::string_view);
} // namespace bmh::editor
-2369
View File
File diff suppressed because it is too large. Load diff
-11
View File
@@ -1,11 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/mcp.hpp"
namespace bmh::editor {
struct UiConfig {
fs::path assets, screenshot;
std::string page = "overview";
int quit_after_ms = 0;
};
int run_ui(Session &, Options &, McpServer &, const UiConfig &);
} // namespace bmh::editor
-9
View File
@@ -1,9 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <string>
#include <string_view>
namespace bmh::editor {
inline constexpr std::string_view kEditorVersion = OPENBMH_EDITOR_VERSION;
inline std::string editor_product() { return "OpenBMH Editor " + std::string(kEditorVersion); }
} // namespace bmh::editor
-555
View File
@@ -1,555 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/world.hpp"
#include "content/digest.hpp"
#include "content/package.hpp"
#include "editor/version.hpp"
#include "import/obw.hpp"
#include "launch/game_data.hpp"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
namespace bmh::editor {
namespace {
Json table(const std::string &name) { return {{"schema", name + "@1.1"}, {"items", Json::array()}}; }
bool date_valid(const Json &value) {
if (value.is_null())
return true;
if (!value.is_string())
return false;
auto s = value.get<std::string>();
if (s.size() != 10 || s[4] != '-' || s[7] != '-')
return false;
for (size_t i = 0; i < s.size(); ++i)
if (i != 4 && i != 7 && (s[i] < '0' || s[i] > '9'))
return false;
int y = std::stoi(s.substr(0, 4)), m = std::stoi(s.substr(5, 2)), d = std::stoi(s.substr(8));
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return y >= 1583 && m >= 1 && m <= 12 && d >= 1 &&
d <= days[m - 1] + (m == 2 && (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)));
}
void walk_refs(const Json &node, const std::function<void(const std::string &)> &emit, bool extension = false) {
if (node.is_object()) {
for (auto it = node.begin(); it != node.end(); ++it) {
if (it.key() == "id" || it.key().starts_with("x-") || it.key() == "sources")
continue;
if (it.value().is_string() &&
(it.key() == "nation" || it.key() == "team" || it.key() == "competition" || it.key() == "stadium" ||
it.key() == "owner" || it.key() == "person" || it.key() == "national_team" || it.key() == "photo" ||
it.key() == "crest" || it.key() == "trophy"))
emit(it.value());
else if ((it.key() == "nationalities" || it.key() == "members" || it.key() == "participants" ||
it.key() == "teams") &&
it.value().is_array()) {
for (const auto &value : it.value())
if (value.is_string())
emit(value);
} else if (it.value().is_object() || it.value().is_array())
walk_refs(it.value(), emit, extension);
}
} else if (node.is_array())
for (const auto &child : node)
walk_refs(child, emit, extension);
}
Json parse(const std::string &data, const std::string &file) {
try {
return Json::parse(data);
} catch (const Json::exception &e) {
throw Error("invalid_json", {{"file", file}, {"detail", e.what()}});
}
}
} // namespace
const std::vector<std::string> &World::tables() {
static const std::vector<std::string> names{"nations", "competitions", "clubs", "players", "stadiums",
"staff", "contracts", "finance", "rules", "calendar",
"assets", "review", "image-edits"};
return names;
}
std::string World::file_for(const std::string &name) {
if (name == "assets")
return "assets/index.json";
if (name == "review" || name == "image-edits")
return "x-editor/" + name + ".json";
return "world/" + name + ".json";
}
std::string World::identity(const Json &row, const std::string &name) {
return str(row, name == "assets" ? "key" : "id");
}
World World::blank(const std::string &title_value) {
World w;
w.manifest = {{"format", "openbmh-world"},
{"format_version", "1.1"},
{"min_reader", "1.1"},
{"kind", "world"},
{"title", {{"default", title_value}}},
{"generator", editor_product()},
{"provenance", "native"},
{"content_license", "user-supplied"},
{"start_date", "2026-07-01"},
{"currency", {{"code", "EUR"}, {"minor_units", 2}}},
{"languages", {"de", "en"}},
{"requires", {"editor:world-v1"}},
{"extensions", Json::array()},
{"x-editor", {{"profile", "editor-world-v1"}, {"playable", false}}}};
for (auto &name : tables())
w.docs_[file_for(name)] = table(name == "assets" ? "asset-index" : name);
w.docs_[file_for("rules")]["items"].push_back({{"id", "rule:unrated@1"},
{"type", "attribute_set"},
{"attribute_set", "unrated@1"},
{"fields", Json::object()}});
for (auto &[name, _] : w.docs_)
w.dirty_.insert(name);
return w;
}
World World::open(const fs::path &source, const std::string &start_date) {
World w;
const auto input = fs::absolute(source);
bool legacy = false;
if (fs::is_directory(input))
legacy = !fs::exists(input / "manifest.json");
else
legacy = folded(utf8(input.extension())) == ".exe";
if (legacy) {
if (!date_valid(start_date))
throw Error("invalid_date");
bmh::obw::Options options;
options.start_date = start_date;
auto docs = bmh::obw::import_installation(input, options);
for (auto &[name, bytes] : docs)
w.store->set(name, std::make_shared<const std::string>(std::move(bytes)));
w.imported = true;
} else
w.store = ArchiveStore::open(input);
w.manifest = parse(w.store->read("manifest.json"), "manifest.json");
if (str(w.manifest, "format") != "openbmh-world" || str(w.manifest, "kind") != "world")
throw Error("not_world");
auto version = str(w.manifest, "format_version");
if (!version.starts_with("1."))
throw Error("unsupported_version", {{"version", version}});
const bool editor = str(w.manifest.value("x-editor", Json::object()), "profile") == "editor-world-v1";
if (editor && (version != "1.1" || str(w.manifest, "min_reader") != "1.1" ||
w.manifest.value("x-editor", Json::object()).value("playable", true)))
throw Error("unsupported_version");
if (!editor) {
// Only bounded 1.0 Classic packages use the Classic validator. Its
// compatibility and seal checks are not relaxed by the new reader.
if (!w.imported) {
auto docs = bmh::obw::read(input);
if (docs.contains("x-classic/seal.json"))
bmh::content::verify(docs);
}
w.imported = true;
}
w.source_path = input;
w.load();
if (w.imported)
w.editor_profile();
return w;
}
void World::load() {
for (auto &name : tables()) {
auto file = file_for(name);
if (store->contains(file)) {
auto bytes = store->read(file);
auto value = parse(bytes, file);
if (!value.is_object() || !value.contains("items") || !value["items"].is_array())
throw Error("invalid_table", {{"file", file}});
original_[file] = std::move(bytes);
docs_[file] = std::move(value);
} else {
docs_[file] = table(name == "assets" ? "asset-index" : name);
dirty_.insert(file);
}
}
}
void World::editor_profile() {
manifest["x-editor"] = {{"profile", "editor-world-v1"},
{"playable", false},
{"original_manifest", manifest},
{"source_filename", utf8(source_path.filename())}};
manifest["format_version"] = "1.1";
manifest["min_reader"] = "1.1";
manifest["requires"] = Json::array({"editor:world-v1"});
manifest["generator"] = editor_product();
// The historical seal remains original evidence only. The editor profile
// deliberately cannot be passed to the Classic runtime as sealed content.
for (auto &comp : rows("competitions")) {
if (!comp.contains("members")) {
comp["members"] = Json::array();
for (auto &stage : comp.value("stages", Json::array()))
for (auto &slot : stage.value("slots", Json::array())) {
auto teams = slot.value("teams", Json::array());
if (slot.contains("team") && slot["team"].is_string())
teams.push_back(slot["team"]);
for (const auto &team : teams)
if (team.is_string()) {
const auto tid = team.get<std::string>();
if (str(comp, "type") == "league")
if (auto club = find("clubs", tid))
(*club)["competition"] = comp["id"];
if (std::find(comp["members"].begin(), comp["members"].end(), tid) == comp["members"].end())
comp["members"].push_back(tid);
}
}
}
}
for (auto &person : rows("players")) {
if (person.contains("x-legacy") && person["x-legacy"].contains("squad_row"))
person["squad_order"] = person["x-legacy"]["squad_row"];
}
touch("competitions");
touch("clubs");
touch("players");
}
Json &World::document(const std::string &name) { return docs_.at(file_for(name)); }
const Json &World::document(const std::string &name) const { return docs_.at(file_for(name)); }
Json &World::rows(const std::string &name) { return document(name)["items"]; }
const Json &World::rows(const std::string &name) const { return document(name).at("items"); }
const Json *World::find(const std::string &name, const std::string &id) const {
for (auto &row : rows(name))
if (identity(row, name) == id)
return &row;
return nullptr;
}
Json *World::find(const std::string &name, const std::string &id) {
return const_cast<Json *>(std::as_const(*this).find(name, id));
}
void World::touch(const std::string &name) { dirty_.insert(file_for(name)); }
void World::change(const std::string &name, const std::string &id, const std::optional<Json> &after) {
auto &values = rows(name);
for (auto i = values.begin(); i != values.end(); ++i)
if (identity(*i, name) == id) {
if (after)
*i = *after;
else
values.erase(i);
touch(name);
return;
}
if (after) {
values.push_back(*after);
touch(name);
}
}
std::string World::title(const Json &value, const std::string &language) const {
if (value.contains("name")) {
const auto &name = value["name"];
if (name.is_object() && name.contains(language) && name[language].is_string())
return name[language];
return text(name);
}
return str(value, "key", str(value, "id"));
}
Json World::statistics() const {
Json counts = Json::object();
for (auto &name : tables())
counts[name] = rows(name).size();
return {{"title", text(manifest.value("title", Json()))},
{"start_date", manifest.value("start_date", Json())},
{"format_version", manifest.value("format_version", Json())},
{"counts", counts},
{"source", utf8(source_path)},
{"imported", imported},
{"profile", "editor-world-v1"},
{"playable", false}};
}
Json World::query(const Json &args) const {
const auto name = str(args, "table", "clubs");
if (std::find(tables().begin(), tables().end(), name) == tables().end())
throw Error("unknown_table");
std::map<std::string, const Json *> clubs;
for (const auto &club : rows("clubs"))
clubs[str(club, "id")] = &club;
std::vector<const Json *> matches;
const auto search = folded(str(args, "search")), nation = str(args, "nation"), comp = str(args, "competition"),
team = str(args, "team");
for (const auto &row : rows(name)) {
const Json *club =
name == "clubs" ? &row : (clubs.contains(str(row, "team")) ? clubs[str(row, "team")] : nullptr);
if (!nation.empty() && str(row, "nation") != nation && (!club || str(*club, "nation") != nation))
continue;
if (!comp.empty() && str(row, "competition") != comp && (!club || str(*club, "competition") != comp))
continue;
if (!team.empty() && str(row, "team") != team && str(row, "owner") != team)
continue;
if (args.contains("role") && str(row, "role") != str(args, "role"))
continue;
if (name == "competitions" && args.value("leagues_only", false) && str(row, "type") != "league")
continue;
if (name == "review" && args.value("unresolved_only", false) && row.value("resolved", false))
continue;
if (!search.empty() && folded(title(row)).find(search) == std::string::npos &&
folded(identity(row, name)).find(search) == std::string::npos &&
(!club || folded(title(*club)).find(search) == std::string::npos))
continue;
matches.push_back(&row);
}
auto sort = str(args, "sort", "name");
bool descending = args.value("descending", false);
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
Json av = sort == "name" ? Json(folded(title(*a))) : a->value(sort, Json());
Json bv = sort == "name" ? Json(folded(title(*b))) : b->value(sort, Json());
if (av == bv)
return identity(*a, name) < identity(*b, name);
return descending ? av > bv : av < bv;
});
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
Json result = Json::array();
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
i < matches.size() && int64_t(result.size()) < limit; ++i)
result.push_back(*matches[i]);
return {{"items", std::move(result)}, {"total", matches.size()}, {"offset", offset}, {"limit", limit}};
}
std::vector<std::pair<std::string, std::string>> World::references(const std::string &id) const {
std::vector<std::pair<std::string, std::string>> found;
for (auto &name : tables())
if (name != "review" && name != "image-edits" && name != "assets")
for (auto &row : rows(name))
if (identity(row, name) != id) {
bool referenced = false;
walk_refs(row, [&](auto &ref) {
if (ref == id)
referenced = true;
});
if (referenced)
found.emplace_back(name, identity(row, name));
}
return found;
}
std::string World::asset_file(const std::string &key) const {
auto row = find("assets", key);
if (!row || !row->contains("files") || !(*row)["files"].is_object())
return {};
for (auto type : {"svg", "native", "default", "original", "512", "256", "128", "64"}) {
auto found = (*row)["files"].find(type);
if (found != (*row)["files"].end() && found->is_string() && store->contains(*found))
return *found;
}
for (auto &value : (*row)["files"])
if (value.is_string() && store->contains(value))
return value;
return {};
}
std::string World::portrait(const Json &person) const {
auto key = str(person, "photo");
auto file = asset_file(key.empty() ? "asset:player/" + str(person, "id") + "/photo" : key);
return file;
}
Json World::validate() const {
Json diagnostics = Json::array();
auto issue = [&](const std::string &severity, const std::string &code, const std::string &name,
const std::string &id, Json details = Json::object()) {
diagnostics.push_back(
{{"severity", severity}, {"code", code}, {"table", name}, {"id", id}, {"details", details}});
};
std::map<std::string, std::string> ids;
const auto editor = manifest.value("x-editor", Json::object());
const auto requirements = manifest.value("requires", Json::array());
if (str(manifest, "format") != "openbmh-world" || str(manifest, "kind") != "world" ||
str(manifest, "format_version") != "1.1" || str(manifest, "min_reader") != "1.1" || !editor.is_object() ||
str(editor, "profile") != "editor-world-v1" || !editor.contains("playable") || editor["playable"] != false ||
!requirements.is_array() ||
std::find(requirements.begin(), requirements.end(), Json("editor:world-v1")) == requirements.end())
issue("error", "invalid_manifest", "manifest", "manifest");
if (!date_valid(manifest.value("start_date", Json())))
issue("error", "invalid_date", "manifest", "manifest");
std::map<std::string, const Json *> attribute_sets;
for (auto &rule : rows("rules"))
if (str(rule, "type") == "attribute_set") {
auto key = str(rule, "attribute_set", str(rule, "id"));
attribute_sets[key] = &rule;
if (key.starts_with("rule:"))
attribute_sets[key.substr(5)] = &rule;
}
for (const auto &name : tables()) {
if (name == "image-edits" || name == "review")
continue;
for (const auto &row : rows(name)) {
auto id = identity(row, name);
if (id.empty() || !ids.emplace(id, name).second)
issue("error", "duplicate_id", name, id);
if (name != "assets" && name != "calendar" && name != "rules" && title(row).empty())
issue("warning", "missing_name", name, id);
if (name == "players") {
if (!date_valid(row.value("born", Json())))
issue("error", "invalid_date", name, id);
if (!row.contains("born") && !row.contains("age_at_start"))
issue("warning", "missing_birthday", name, id);
if (row.contains("born") && row["born"].is_null())
issue("warning", "missing_birthday", name, id);
const auto attrs = row.value("attributes", Json::object());
if (!attrs.is_object()) {
issue("error", "invalid_attributes", name, id);
continue;
}
const auto set = attribute_sets.find(str(row, "attribute_set"));
if (set == attribute_sets.end())
issue("warning", "unknown_attribute_set", name, id);
else {
auto fields = set->second->value("fields", Json::object());
for (auto it = attrs.begin(); it != attrs.end(); ++it) {
if (it->is_null() || !fields.contains(it.key()))
continue;
const auto &field = fields[it.key()];
if (!it->is_number_integer() ||
it->get<int64_t>() < field.value("min", std::numeric_limits<int64_t>::min()) ||
it->get<int64_t>() > field.value("max", std::numeric_limits<int64_t>::max()))
issue("error", "attribute_range", name, id, {{"field", it.key()}});
}
}
}
}
}
for (auto &name : tables())
if (name != "review" && name != "image-edits")
for (auto &row : rows(name))
walk_refs(row, [&](const std::string &ref) {
if (!ref.empty() && !ids.contains(ref) && !ref.starts_with("asset:"))
issue("error", "missing_reference", name, identity(row, name), {{"reference", ref}});
});
const std::map<std::string, std::string> reference_types{{"team", "clubs"}, {"owner", "clubs"},
{"nation", "nations"}, {"competition", "competitions"},
{"stadium", "stadiums"}, {"national_team", "clubs"}};
for (auto &name : tables())
if (name != "review" && name != "image-edits")
for (const auto &row : rows(name)) {
for (const auto &[field, target] : reference_types)
if (row.contains(field) && !row[field].is_null()) {
const auto key = str(row, field);
if (!row[field].is_string() || (!key.empty() && ids.contains(key) && ids.at(key) != target))
issue("error", "missing_reference", name, identity(row, name),
{{"field", field}, {"expected_table", target}});
}
for (const auto &[field, target] :
std::map<std::string, std::string>{{"nationalities", "nations"}, {"members", "clubs"}})
if (row.contains(field)) {
if (!row[field].is_array())
issue("error", "missing_reference", name, identity(row, name), {{"field", field}});
else
for (const auto &key : row[field])
if (!key.is_string() ||
(ids.contains(key.get<std::string>()) && ids.at(key.get<std::string>()) != target))
issue("error", "missing_reference", name, identity(row, name),
{{"field", field}, {"expected_table", target}});
}
}
for (auto &asset : rows("assets")) {
if (asset_file(str(asset, "key")).empty())
issue("warning", "missing_asset", "assets", str(asset, "key"));
}
for (auto &review : rows("review"))
if (!review.value("resolved", false))
issue("warning", "review_open", "review", str(review, "id"));
return diagnostics;
}
void World::save(const fs::path &destination) const {
if (imported && !source_path.empty() &&
fs::absolute(destination).lexically_normal() == source_path.lexically_normal())
throw Error("preserve_source");
const auto problems = validate();
for (auto &row : problems)
if (row["severity"] == "error")
throw Error("validation_failed", {{"diagnostics", problems}});
std::map<std::string, std::string> docs{{"manifest.json", manifest.dump(2)}};
for (const auto &[file, value] : docs_)
docs[file] = !dirty_.contains(file) && original_.contains(file) ? original_.at(file) : value.dump(2);
store->save(destination, docs);
}
World World::demo() {
auto w = blank("OpenBMH Editor – Demo");
w.rows("nations").push_back({{"id", "nation:de"},
{"name", {{"default", "Deutschland"}, {"en", "Germany"}}},
{"confederation", "uefa"},
{"playable", true}});
w.rows("competitions")
.push_back({{"id", "comp:demo"},
{"name", {{"default", "Demo-Liga"}, {"en", "Demo league"}}},
{"nation", "nation:de"},
{"type", "league"},
{"tier", 1},
{"visible", true},
{"members", {"club:north", "club:south"}},
{"stages", Json::array()}});
w.rows("rules").push_back({{"id", "demo@1"},
{"type", "attribute_set"},
{"fields",
{{"strength", {{"min", 0}, {"max", 99}}},
{"technique", {{"min", 0}, {"max", 99}}},
{"condition", {{"min", 0}, {"max", 100}}},
{"form", {{"min", 0}, {"max", 99}}}}}});
for (int i = 0; i < 2; ++i) {
auto id = i ? "club:south" : "club:north";
auto stadium = i ? "stadium:south" : "stadium:north";
const auto key = std::string("asset:demo/") + (i ? "south" : "north");
const auto file = std::string("assets/demo/") + (i ? "south.svg" : "north.svg");
const auto color = i ? "#b44b5c" : "#3698aa";
std::string svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"128\" "
"height=\"144\" viewBox=\"0 0 128 144\"><path d=\"M10 8h108v80q0 26-54 "
"48Q10 114 10 88Z\" fill=\"" +
std::string(color) +
"\" stroke=\"#e5efef\" stroke-width=\"6\"/><path d=\"M34 98V40h15l30 "
"38V40h15v58H79L49 60v38Z\" fill=\"#fff\"/></svg>";
w.store->set(file, std::make_shared<const std::string>(svg));
w.rows("assets").push_back({{"key", key},
{"name", {{"default", i ? "Südstadt" : "Nordstadt"}}},
{"files", {{"svg", file}}},
{"source", "synthetic-demo"},
{"license", "GPL-3.0-only"},
{"kind", "vector"},
{"width", 128},
{"height", 144}});
w.rows("clubs").push_back({{"id", id},
{"name", {{"default", i ? "SV Südstadt" : "FC Nordstadt"}}},
{"short_name", i ? "Südstadt" : "Nordstadt"},
{"type", "club"},
{"nation", "nation:de"},
{"competition", "comp:demo"},
{"stadium", stadium},
{"crest", key},
{"colors", {i ? "#9c3949" : "#277c8b", "#ffffff"}},
{"founded", 1900 + i}});
w.rows("stadiums")
.push_back({{"id", stadium},
{"name", {{"default", i ? "Südpark" : "Nordpark"}}},
{"owner", id},
{"capacity", {{"total", 22000 + 6000 * i}, {"seated", 18000 + 6000 * i}, {"standing", 4000}}}});
for (int n = 0; n < 26; ++n) {
w.rows("players").push_back(
{{"id", "player:demo-" + std::to_string(i * 26 + n)},
{"name", {{"first", n % 2 ? "Alex" : "Robin"}, {"last", "Spieler " + std::to_string(i * 26 + n + 1)}}},
{"born", "2000-03-12"},
{"nationalities", {"nation:de"}},
{"positions",
{n < 2 ? "gk"
: n < 10 ? "def"
: n < 18 ? "mid"
: "fwd"}},
{"team", id},
{"squad_number", n + 1},
{"squad_order", n},
{"attribute_set", "demo@1"},
{"attributes",
{{"strength", 68 + (n % 15)}, {"technique", 65 + n % 20}, {"condition", 90}, {"form", 70}}}});
// Synthetic per-season salaries make the comparison demo useful.
// The last player deliberately has no known contract.
if (n != 25)
w.rows("contracts")
.push_back({{"id", "contract:demo-" + std::to_string(i * 26 + n)},
{"name", "Demo contract"},
{"person", "player:demo-" + std::to_string(i * 26 + n)},
{"team", id},
{"start", "2026-07-01"},
{"end", "2027-06-30"},
{"salary", (40000 + 5000 * n + 10000 * i) * 100}});
}
}
w.rows("staff").push_back({{"id", "staff:referee-demo"},
{"name", {{"default", "Kim Beispiel"}}},
{"role", "referee"},
{"nation", "nation:de"},
{"attributes", {{"strictness", 2}}}});
return w;
}
} // namespace bmh::editor
-42
View File
@@ -1,42 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/archive.hpp"
namespace bmh::editor {
class World {
public:
Json manifest;
std::shared_ptr<ArchiveStore> store = std::make_shared<ArchiveStore>();
fs::path source_path;
bool imported = false;
static World open(const fs::path &, const std::string &start_date = "2026-07-01");
static World blank(const std::string &title = "Untitled world");
static World demo();
Json &document(const std::string &);
const Json &document(const std::string &) const;
Json &rows(const std::string &);
const Json &rows(const std::string &) const;
const Json *find(const std::string &, const std::string &) const;
Json *find(const std::string &, const std::string &);
void change(const std::string &table, const std::string &id, const std::optional<Json> &);
void touch(const std::string &table);
Json query(const Json &) const;
Json validate() const;
Json statistics() const;
std::string asset_file(const std::string &key) const;
std::string portrait(const Json &) const;
std::string title(const Json &entity, const std::string &language = "de") const;
std::vector<std::pair<std::string, std::string>> references(const std::string &id) const;
void save(const fs::path &) const;
static std::string file_for(const std::string &table);
static std::string identity(const Json &row, const std::string &table);
static const std::vector<std::string> &tables();
private:
std::map<std::string, Json> docs_;
std::map<std::string, std::string> original_;
std::set<std::string> dirty_;
void load();
void editor_profile();
};
} // namespace bmh::editor
-10
View File
@@ -1,10 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/executable_layout.hpp"
namespace bmh::layout {
// Football Limited V2.20 data-segment locations of the OPL voice slots and
// the 96-word key-on frequency table. Kept separate from simulation tables.
inline constexpr auto EnglishAudioOperatorSlots = EnDataStart + 0x6a63;
inline constexpr auto EnglishAudioNoteFrequencies = EnDataStart + 0xb310;
} // namespace bmh::layout
-3
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/binary.hpp"
#include <fstream>
@@ -8,8 +7,6 @@
namespace bmh {
Bytes read_file(const std::filesystem::path& path) {
if (const auto r = content::find(path))
return content::bytes(*r);
std::ifstream in(path, std::ios::binary);
if (!in) throw FormatError("cannot open " + path.string());
return Bytes(std::istreambuf_iterator<char>(in), {});
-69
View File
@@ -1,69 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include <algorithm>
#include <cctype>
namespace bmh::content {
namespace {
std::mutex mutex;
struct Binding {
std::shared_ptr<const Classic> content;
int year;
};
std::map<std::filesystem::path, Binding> mounts;
auto normalized(const std::filesystem::path &p) { return std::filesystem::absolute(p).lexically_normal(); }
} // namespace
std::string key(const std::filesystem::path &p) {
auto result = p.generic_string();
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return char(std::tolower(c)); });
return result;
}
Mount::Mount(std::filesystem::path root, std::shared_ptr<const Classic> value) : root_(normalized(root)) {
if (!value)
throw FormatError("content: empty mount");
std::lock_guard lock(mutex);
const auto year = value->start_year;
if (!mounts.emplace(root_, Binding{std::move(value), year}).second)
throw FormatError("content: already mounted");
}
Mount::~Mount() {
std::lock_guard lock(mutex);
mounts.erase(root_);
}
std::optional<Resource> find(const std::filesystem::path &p) {
const auto full = normalized(p);
std::lock_guard lock(mutex);
for (const auto &[root, data] : mounts) {
const auto relative = full.lexically_relative(root);
if (relative.empty() || *relative.begin() == "..")
continue;
return Resource{data.content, key(relative), data.year};
}
return std::nullopt;
}
void set_display_start_year(const std::filesystem::path &root, int year) {
if (year < 1900 || year > 9998)
throw FormatError("Invalid Classic display origin");
std::lock_guard lock(mutex);
const auto it = mounts.find(normalized(root));
if (it == mounts.end())
throw FormatError("Content is not mounted");
it->second.year = year;
}
Bytes bytes(const Resource &r) {
if (r.key == "m3.men")
return r.content->desktops;
if (r.key == "m3.dat")
return r.content->formations;
if (r.key == "textd.blk.header")
return r.content->text_header;
if (r.key.starts_with("s/")) {
const auto it = r.content->audio.find(r.key.substr(2));
if (it != r.content->audio.end())
return it->second;
}
if (const auto it = r.content->supplemental.find(r.key); it != r.content->supplemental.end())
return it->second;
throw FormatError("content: no byte resource: " + r.key);
}
} // namespace bmh::content
-54
View File
@@ -1,54 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include "formats/font.hpp"
#include "formats/palette.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/textd.hpp"
namespace bmh::content {
// Immutable decoded Classic content. Logical aliases keep the existing UI geometry
// independent of both storage layout and the legacy binary codecs.
struct Classic {
bool english = false;
Database database;
TextDb texts;
LeImage executable, source_tables;
Bytes desktops, formations, text_header;
Palette palette;
std::map<std::string, Image> images;
std::map<std::string, Font> fonts;
std::map<std::string, Palette> image_palettes;
std::map<std::string, Bytes> audio;
std::map<std::string, Bytes> supplemental;
std::map<std::string, std::string> documents;
std::string content_id;
int start_year = 2026;
};
struct Resource {
std::shared_ptr<const Classic> content;
std::string key;
int display_start_year = 2026;
};
// The mount owns a shared content reference; callers never reconstruct legacy files.
// One game runs per process. Multiple mounts are supported by tools and tests.
class Mount {
public:
Mount(std::filesystem::path root, std::shared_ptr<const Classic> content);
~Mount();
Mount(const Mount &) = delete;
Mount &operator=(const Mount &) = delete;
const std::filesystem::path &root() const { return root_; }
private:
std::filesystem::path root_;
};
std::optional<Resource> find(const std::filesystem::path &locator);
void set_display_start_year(const std::filesystem::path &root, int year);
Bytes bytes(const Resource &resource);
std::string key(const std::filesystem::path &relative);
} // namespace bmh::content
+2 -5
View File
@@ -764,7 +764,7 @@ inline constexpr auto EnglishLayoutTranslation156 = 0x6e08c;
inline constexpr auto EnglishLayoutTranslation157 = 0x6e094;
inline constexpr auto EnglishLayoutTranslation158 = 0x6e0b8;
inline constexpr auto EnglishLayoutTranslation159 = 0x6e0bb;
inline constexpr auto EnglishLayoutTranslation16 = 0x6be50;
inline constexpr auto EnglishLayoutTranslation16 = 0x6be4f;
inline constexpr auto EnglishLayoutTranslation160 = 0x6e0d8;
inline constexpr auto EnglishLayoutTranslation161 = 0x6e110;
inline constexpr auto EnglishLayoutTranslation162 = 0x6e11c;
@@ -986,7 +986,7 @@ inline constexpr auto EnglishLayoutTranslation7 = 0x6be0c;
inline constexpr auto EnglishLayoutTranslation70 = 0x6d270;
inline constexpr auto EnglishLayoutTranslation71 = 0x6d272;
inline constexpr auto EnglishLayoutTranslation72 = 0x6d274;
inline constexpr auto EnglishLayoutTranslation73 = 0x6d29d;
inline constexpr auto EnglishLayoutTranslation73 = 0x6d29c;
inline constexpr auto EnglishLayoutTranslation74 = 0x6d3b4;
inline constexpr auto EnglishLayoutTranslation75 = 0x6d404;
inline constexpr auto EnglishLayoutTranslation76 = 0x6d408;
@@ -1972,7 +1972,4 @@ inline constexpr auto EnglishFourTeamFixtureTable = 0x6eea0;
inline constexpr auto EnglishSixTeamFixtureTable = 0x6eed4;
inline constexpr auto EnglishTwelveTeamFixtureTable = 0x6f0bc;
inline constexpr auto EnglishTwentyTeamFixtureTable = 0x6ee40;
inline constexpr auto EnglishDesktopBinSourceX = 0x6e180;
inline constexpr auto EnglishDesktopBinSourceY = 0x6e182;
inline constexpr auto EnglishDesktopSocketSourceX = 0x6e184;
} // namespace bmh::layout
-7
View File
@@ -1,16 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/font.hpp"
namespace bmh {
Font load_font(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
const auto found = r->content->fonts.find(std::filesystem::path(r->key).filename().string());
if (found == r->content->fonts.end())
throw FormatError("content: missing font: " + r->key);
return found->second;
}
Bytes d = read_file(path);
if (d.size() < 28) throw FormatError("FNT: file too short");
Font f;
+3 -11
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/le.hpp"
#include "formats/rule_base.hpp"
@@ -37,21 +36,14 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
if (!file) throw FormatError("cannot write the OpenBMH image");
}
LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules) {
if (const auto r = content::find(path)) {
if (r->key != "bmh.exe")
throw FormatError("content: unknown Classic table set");
auto tables = apply_supported_rules ? r->content->executable : r->content->source_tables;
tables.set_display_start_year(r->display_start_year);
return tables;
}
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()));
if (apply_supported_rules) apply_rule_base(img);
apply_rule_base(img);
return img;
}
auto u8 = [&](size_t o) -> uint32_t {
@@ -141,7 +133,7 @@ LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules) {
}
}
}
if (apply_supported_rules) apply_rule_base(img);
apply_rule_base(img);
return img;
}
+18 -24
View File
@@ -18,23 +18,20 @@ namespace bmh {
class LeImage {
public:
int display_start_year() const { return display_start_year_; }
void set_display_start_year(int year) { display_start_year_ = year; }
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];
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
@@ -47,21 +44,18 @@ public:
}
const Bytes& bytes() const { return bytes_; }
friend LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules);
friend LeImage load_le(const std::filesystem::path& path);
private:
int display_start_year_ = 2026;
uint32_t base_ = 0;
Bytes bytes_;
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.
// The installation importer passes false to preserve source tables separately;
// ordinary engine callers retain the default behavior.
LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules = true);
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.
+1 -10
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/m3d.hpp"
#include <cstring>
@@ -36,15 +35,7 @@ std::string pool_string(const Bytes& pool, size_t offset) {
} // namespace
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
if (const auto r = content::find(path)) {
if (r->key != "m3d.man")
throw FormatError("content: unknown database");
return r->content->database;
}
return decode_database(read_file(path), c);
}
Database decode_database(const Bytes& d, 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);
-1
View File
@@ -74,6 +74,5 @@ struct Database {
};
Database load_database(const std::filesystem::path& path, const DbCounts& counts = {});
Database decode_database(const Bytes& data, const DbCounts& counts = {});
} // namespace bmh
-64
View File
@@ -1,64 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/native_file.hpp"
#include "formats/binary.hpp"
#include <chrono>
#include <fstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
namespace bmh::content {
namespace fs = std::filesystem;
namespace {
[[noreturn]] void fail(const std::string &error) { throw FormatError(error); }
} // namespace
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
fail("destination directory unavailable");
const auto status = fs::symlink_status(file);
if (fs::is_symlink(status) || fs::is_directory(status) || (!overwrite && fs::exists(status)))
fail("destination already exists or is unsafe");
fs::path staging;
for (int i = 0; i < 100; ++i) {
auto candidate =
parent /
(".openbmh-write-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) +
"-" + std::to_string(i));
if (fs::create_directory(candidate)) {
staging = std::move(candidate);
break;
}
}
if (staging.empty())
fail("cannot reserve staging directory");
struct Cleanup {
fs::path path;
~Cleanup() {
std::error_code ec;
fs::remove_all(path, ec);
}
} cleanup{staging};
const auto temp = staging / "payload";
std::ofstream stream(temp, std::ios::binary);
stream.write(data.data(), std::streamsize(data.size()));
stream.close();
if (!stream)
fail("cannot write temporary file");
const auto current = fs::symlink_status(file);
if (fs::is_symlink(current) || fs::is_directory(current) || (!overwrite && fs::exists(current)))
fail("destination changed while writing");
#ifdef _WIN32
if (!MoveFileExW(temp.c_str(), file.c_str(),
MOVEFILE_WRITE_THROUGH | (overwrite ? MOVEFILE_REPLACE_EXISTING : 0)))
fail("cannot publish file");
#else
if (overwrite)
fs::rename(temp, file);
else {
fs::create_hard_link(temp, file);
fs::remove(temp);
}
#endif
}
} // namespace bmh::content
-7
View File
@@ -1,7 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <string_view>
namespace bmh::content {
void write_atomic(const std::filesystem::path &, std::string_view, bool overwrite = false);
}
-195
View File
@@ -1,195 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/native_state.hpp"
#include <limits>
#include <type_traits>
namespace bmh {
namespace {
using J = cli::Json;
using O = J::Object;
using A = J::Array;
[[noreturn]] void invalid() { throw FormatError("native state: invalid or missing field"); }
const J &field(const J &obj, const char *name) {
if (!obj.object())
invalid();
const auto it = obj.object()->find(name);
if (it == obj.object()->end())
invalid();
return it->second;
}
template <class T> J number(T v) { return J(int64_t(v)); }
template <class T> void number(const J &j, T &v) {
if (!j.integer())
invalid();
const auto n = *j.integer();
if constexpr (std::is_unsigned_v<T>) {
if (n < 0 || uint64_t(n) > uint64_t(std::numeric_limits<T>::max()))
invalid();
} else if (n < std::numeric_limits<T>::min() || n > std::numeric_limits<T>::max())
invalid();
v = T(n);
}
J scalar(bool b) { return b; }
void scalar(const J &j, bool &b) {
if (!j.boolean())
invalid();
b = *j.boolean();
}
template <class T> J scalar(T n) { return number(n); }
template <class T> void scalar(const J &j, T &n) { number(j, n); }
template <class Range> J sequence(const Range &values) {
A out;
for (const auto v : values)
out.push_back(number(v));
return out;
}
template <class T> void sequence(const J &j, std::vector<T> &values) {
if (!j.array() || j.array()->size() > 1000000)
invalid();
values.resize(j.array()->size());
for (size_t i = 0; i < values.size(); ++i)
number((*j.array())[i], values[i]);
}
template <class T, size_t N> void sequence(const J &j, std::array<T, N> &values) {
if (!j.array() || j.array()->size() != N)
invalid();
for (size_t i = 0; i < N; ++i)
number((*j.array())[i], values[i]);
}
std::string hex(const Bytes &data) {
constexpr char d[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (auto c : data) {
out += d[c >> 4];
out += d[c & 15];
}
return out;
}
Bytes unhex(const J &value) {
if (!value.string() || value.string()->size() % 2 || value.string()->size() > 32 * 1024 * 1024)
invalid();
const auto &s = *value.string();
Bytes b;
b.reserve(s.size() / 2);
const auto digit = [](char c) -> int {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
invalid();
};
for (size_t i = 0; i < s.size(); i += 2)
b.push_back(uint8_t(digit(s[i]) * 16 + digit(s[i + 1])));
return b;
}
} // namespace
cli::Json encode_native_bytes(const Bytes &bytes) {
return O{{"schema", "classic-bytes@1.0"}, {"hex", hex(bytes)}};
}
Bytes decode_native_bytes(const J &value, size_t expected) {
if (!field(value, "schema").string() || *field(value, "schema").string() != "classic-bytes@1.0")
invalid();
auto b = unhex(field(value, "hex"));
if (b.size() != expected)
invalid();
return b;
}
#define STATE_SCALARS(X) \
X(indoor) \
X(level) X(chance_rain) X(chance_temperature) X(last_shooter) X(last_pick_quality) X(live_scene) \
X(sportschau_selection_available) X(sportschau_club_threshold) X(list_toggle) X(lineups_frozen) \
X(offer_answer) X(transfer_notice_suppressed) X(pools_open) X(autosave_months) X(autosave_month) \
X(display_start_year) X(date) X(season_start) X(development_balance) X(trend_rotation) \
X(season)
#define STATE_BYTES(X) \
X(team_morale) \
X(player_bonus) X(formations) X(manager_records) X(tactics) X(manager_options) X(club_table) \
X(club_heap_bc) X(club_heap_78) X(club_heap_b8) X(master_database_metadata) X(referee_names) \
X(stadium_names) X(tournament_name) X(manager_results) X(manager_ratings) X(position_history) \
X(league_rounds) X(results) X(stocks) X(foreign_strength) X(mailbox) X(club_names) \
X(player_names)
#define STATE_NUMBERS(X) \
X(squad_slots) \
X(team_flags) X(manager_teams) X(live_matches) X(sportschau_homes) X(sportschau_priorities) X(club_ids) \
X(player_cards) X(player_name_offsets)
J encode_native_state(const GameState &g) {
O out{{"schema", "classic-state@1.0"}};
#define PUT_SCALAR(name) out[#name] = scalar(g.name);
STATE_SCALARS(PUT_SCALAR)
#undef PUT_SCALAR
#define PUT_BYTES(name) out[#name] = hex(g.name);
STATE_BYTES(PUT_BYTES)
#undef PUT_BYTES
#define PUT_NUMBERS(name) out[#name] = sequence(g.name);
STATE_NUMBERS(PUT_NUMBERS)
#undef PUT_NUMBERS
A players;
for (const auto &p : g.players)
players.push_back(O{{"name_hex", hex(Bytes(p.name.begin(), p.name.end()))},
{"form", number(p.w35c)},
{"skills", number(p.w368)},
{"identity", number(p.w364)}});
out["players"] = std::move(players);
A blocks;
for (const auto &[at, bytes] : g.memory.blocks())
blocks.push_back(O{{"address", number(at)}, {"hex", hex(bytes)}});
out["memory"] = std::move(blocks);
// Reality scene residues influence later matches and must survive a checkpoint.
out["reality"] = O{{"initialized", g.reality.initialized}, {"deflected", g.reality.deflected},
{"card_kind", number(g.reality.card_kind)}, {"distance", g.reality.distance},
{"actors", sequence(g.reality.cue_actors)}, {"grid", g.reality.grid.checkpoint()}};
return out;
}
GameState decode_native_state(const J &in) {
if (!field(in, "schema").string() || *field(in, "schema").string() != "classic-state@1.0")
invalid();
GameState g;
#define GET_SCALAR(name) scalar(field(in, #name), g.name);
STATE_SCALARS(GET_SCALAR)
#undef GET_SCALAR
#define GET_BYTES(name) g.name = unhex(field(in, #name));
STATE_BYTES(GET_BYTES)
#undef GET_BYTES
#define GET_NUMBERS(name) sequence(field(in, #name), g.name);
STATE_NUMBERS(GET_NUMBERS)
#undef GET_NUMBERS
const auto &players = field(in, "players");
if (!players.array() || players.array()->size() > 4095)
invalid();
for (const auto &row : *players.array()) {
Player p;
auto bytes = unhex(field(row, "name_hex"));
p.name.assign(bytes.begin(), bytes.end());
number(field(row, "form"), p.w35c);
number(field(row, "skills"), p.w368);
number(field(row, "identity"), p.w364);
g.players.push_back(std::move(p));
}
const auto &memory = field(in, "memory");
if (!memory.array() || memory.array()->size() > 8192)
invalid();
std::map<uint32_t, Bytes> blocks;
for (const auto &row : *memory.array()) {
uint32_t at;
number(field(row, "address"), at);
auto b = unhex(field(row, "hex"));
if (uint64_t(at) + b.size() > UINT32_MAX || !blocks.emplace(at, std::move(b)).second)
invalid();
}
g.memory = StaticMemory::from_blocks(std::move(blocks));
const auto &reality = field(in, "reality");
scalar(field(reality, "initialized"), g.reality.initialized);
scalar(field(reality, "deflected"), g.reality.deflected);
number(field(reality, "card_kind"), g.reality.card_kind);
number(field(reality, "distance"), g.reality.distance);
sequence(field(reality, "actors"), g.reality.cue_actors);
g.reality.grid.restore_checkpoint(field(reality, "grid"));
if (g.display_start_year < 1900 || g.display_start_year > 9998 || g.manager_teams.size() > 4 ||
g.level < 0 || g.level > 9 || g.date < g.season_start || g.date > 3000000)
invalid();
return g;
}
#undef STATE_SCALARS
#undef STATE_BYTES
#undef STATE_NUMBERS
} // namespace bmh
-11
View File
@@ -1,11 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "cli/json.hpp"
#include "game/state.hpp"
namespace bmh {
// Explicit, platform-independent checkpoint. No object dumps, pointers or callbacks.
cli::Json encode_native_state(const GameState &);
GameState decode_native_state(const cli::Json &);
cli::Json encode_native_bytes(const Bytes &);
Bytes decode_native_bytes(const cli::Json &, size_t expected);
} // namespace bmh
-6
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/palette.hpp"
#include "formats/binary.hpp"
@@ -7,11 +6,6 @@
namespace bmh {
Palette load_palette(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
if (r->key != "m3pc.col")
throw FormatError("content: unknown palette");
return r->content->palette;
}
Bytes b = read_file(path);
if (b.size() < 768) throw FormatError("palette too short: " + path.string());
Palette p;
-6
View File
@@ -1,5 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/textd.hpp"
#include "formats/binary.hpp"
@@ -7,11 +6,6 @@
namespace bmh {
TextDb load_textd(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
if (r->key != "textd.blk")
throw FormatError("content: unknown text set");
return r->content->texts;
}
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
+1 -12
View File
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/vga.hpp"
#include "formats/content.hpp"
namespace bmh {
@@ -41,16 +40,6 @@ Image decode_vga(const Bytes& d) {
return img;
}
Image load_vga(const std::filesystem::path &path) {
if (const auto r = content::find(path)) {
auto name = std::filesystem::path(r->key);
name.replace_extension();
const auto found = r->content->images.find(name.generic_string());
if (found == r->content->images.end())
throw FormatError("content: missing image: " + r->key);
return found->second;
}
return decode_vga(read_file(path));
}
Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); }
} // namespace bmh
+1 -29
View File
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/highscore.hpp"
#include "formats/native_state.hpp"
#include "formats/native_file.hpp"
#include <algorithm>
#include <bit>
@@ -188,25 +186,11 @@ HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) {
}
return rows;
}
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix, bool native) {
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");
if (native)
return base / ("highscore-" + std::to_string(signature) + ".obscore");
return base / (prefix + std::to_string(signature));
}
HighscoreTable load_highscore_table(const std::filesystem::path& file) {
if (file.extension() == ".obscore") {
const auto data = read_file(file);
const auto j = cli::parse_json(std::string(data.begin(), data.end()));
if (!j.object() || !j.object()->contains("schema") || !j.object()->at("schema").string() ||
*j.object()->at("schema").string() != "classic-highscore@1.0" || !j.object()->contains("payload"))
throw FormatError("Invalid native highscore");
const auto raw = decode_native_bytes(j.object()->at("payload"), 360);
HighscoreBytes bytes;
std::copy(raw.begin(), raw.end(), bytes.begin());
return decode_highscore_table(bytes);
}
std::ifstream in(file, std::ios::binary);
if (!in) {
HighscoreTable empty{};
@@ -219,18 +203,6 @@ HighscoreTable load_highscore_table(const std::filesystem::path& file) {
}
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) {
const auto bytes = encode_highscore_table(rows);
if (file.extension() == ".obscore") {
try {
content::write_atomic(file,
cli::dump_json(cli::Json::Object{
{"schema", "classic-highscore@1.0"},
{"payload", encode_native_bytes(Bytes(bytes.begin(), bytes.end()))}}),
true);
return true;
} catch (const std::exception &) {
return false;
}
}
std::ofstream out(file, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
+2 -2
View File
@@ -53,8 +53,8 @@ HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable
HighscoreBytes encode_highscore_table(const HighscoreTable& rows);
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes);
// The caller supplies the configured installation base and Original TEXTD889 prefix.
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix = "high/h.", bool native = false);
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);
-7
View File
@@ -70,13 +70,6 @@ public:
}
void set_pointer(uint32_t a, uint32_t address) { set32(a, address == 0 ? 0 : address + kGuestDataBase); }
const std::map<uint32_t, Bytes> &blocks() const { return blocks_; }
static StaticMemory from_blocks(std::map<uint32_t, Bytes> blocks) {
StaticMemory memory;
memory.blocks_ = std::move(blocks);
return memory;
}
private:
static std::string hex(uint32_t v) {
char b[16];
-10
View File
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include <algorithm>
#include <cstdio>
@@ -151,13 +150,4 @@ std::string format_number(const GameState& g, int32_t value, int flags) {
std::string format_amount(const GameState& g, int32_t value) { return format_number(g, value, 0x101); }
void install_message_texts(const LeImage& 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);
}
} // namespace bmh
-6
View File
@@ -16,7 +16,6 @@
#include <string>
#include <vector>
#include "formats/le.hpp"
#include "game/state.hpp"
namespace bmh {
@@ -60,11 +59,6 @@ inline std::string kIndoorInvitationText;
inline std::string kChampionshipBonusText;
inline std::string kFriendlyPayerPrefixText;
// Installs the six texts above from the game image (the English game uses its own wording).
// Both career sessions call it at start; standalone engine tools (week_check, the season sims)
// must call it too, or these messages lose their text (#14: the indoor entry bonus mail).
void install_message_texts(const LeImage& exe);
// 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);
-8
View File
@@ -20,10 +20,6 @@ public:
void srand(uint32_t seed) { seed_ = seed; }
uint32_t seed() const { return seed_; }
uint64_t calls() const { return calls_; }
void restore(uint32_t seed, uint64_t calls) {
seed_ = seed;
calls_ = calls;
}
int rand() {
calls_++;
if (draw_hook) draw_hook(1);
@@ -51,10 +47,6 @@ public:
int32_t seed() const { return seed_; }
void set_seed(int32_t seed) { seed_ = seed; }
uint64_t calls() const { return calls_; }
void restore(int32_t seed, uint64_t calls) {
seed_ = seed;
calls_ = calls;
}
int32_t range(int32_t lo, int32_t hi) {
calls_++;
if (draw_hook) draw_hook(0);
-57
View File
@@ -166,60 +166,3 @@ std::pair<int,int> RealityGrid::position(int figure) const {
}
} // namespace bmh
namespace bmh {
cli::Json RealityGrid::checkpoint() const {
cli::Json::Array planes, positions;
for (const auto &plane : occupied_) {
cli::Json::Array cells;
for (auto b : plane)
cells.emplace_back(int(b));
planes.emplace_back(std::move(cells));
}
for (const auto &[x, y] : positions_)
positions.emplace_back(cli::Json::Array{x, y});
return cli::Json::Object{
{"planes", std::move(planes)},
{"positions", std::move(positions)},
{"ball", cli::Json::Array{ball_.first, ball_.second}},
{"previous_ball", cli::Json::Array{previous_ball_.first, previous_ball_.second}}};
}
void RealityGrid::restore_checkpoint(const cli::Json &value) {
const auto field = [&](const char *name) -> const cli::Json & {
if (!value.object() || !value.object()->contains(name))
throw FormatError("native Reality grid field missing");
return value.object()->at(name);
};
const auto array = [](const cli::Json &j, size_t size) -> const cli::Json::Array & {
if (!j.array() || j.array()->size() != size)
throw FormatError("invalid native Reality grid dimensions");
return *j.array();
};
const auto integer = [](const cli::Json &j) -> int {
if (!j.integer() || *j.integer() < INT32_MIN || *j.integer() > INT32_MAX)
throw FormatError("invalid native Reality coordinate");
return int(*j.integer());
};
RealityGrid restored;
const auto &planes = array(field("planes"), 2);
for (size_t p = 0; p < 2; ++p) {
const auto &cells = array(planes[p], 0x478);
for (size_t i = 0; i < cells.size(); ++i) {
const int n = integer(cells[i]);
if (n < 0 || n > 255)
throw FormatError("invalid native Reality cell");
restored.occupied_[p][i] = uint8_t(n);
}
}
const auto pair = [&](const cli::Json &j) {
const auto &xy = array(j, 2);
return std::pair<int, int>{integer(xy[0]), integer(xy[1])};
};
const auto &positions = array(field("positions"), 24);
for (size_t i = 0; i < 24; ++i)
restored.positions_[i] = pair(positions[i]);
restored.ball_ = pair(field("ball"));
restored.previous_ball_ = pair(field("previous_ball"));
*this = std::move(restored);
}
} // namespace bmh
+9 -12
View File
@@ -6,7 +6,6 @@
#include <utility>
#include "formats/le.hpp"
#include "cli/json.hpp"
namespace bmh {
@@ -60,17 +59,15 @@ RealityPath reality_goal_path(int x, int y, int goal_x);
// either player plane. This is runtime scene state, not a Native save extension.
class RealityGrid {
public:
cli::Json checkpoint() const;
void restore_checkpoint(const cli::Json &);
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<int, int> position(int figure) const;
std::pair<int, int> ball() const { return ball_; }
std::pair<int, int> previous_ball() const { return previous_ball_; }
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<int, int> position(int figure) const;
std::pair<int, int> ball() const { return ball_; }
std::pair<int, int> previous_ball() const { return previous_ball_; }
private:
std::array<std::array<uint8_t, 0x478>, 2> occupied_{};
std::array<std::pair<int, int>, 24> positions_{};
+1 -8
View File
@@ -228,22 +228,15 @@ bool undo_reschedule(GameState& g, int manager, int day) {
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
int kept = 0; // local_18: the replays of other clubs that stay on the day
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) { ++kept; continue; }
if (f.home != team && f.away != team) continue;
g.results.at(result_at(league, round, m)) = kNotPlayed;
g.memory.set16(at, 0);
}
// with no replay left the day loses its replay bit 0x4000 again (calendar high byte & 0xbf),
// so it can be a target once more
if (kept == 0) {
const uint32_t high = kCalendar + uint32_t(day) * 2 + 1;
g.memory.set8(high, uint8_t(g.memory.u8(high) & 0xbf));
}
return true;
}
+2 -2
View File
@@ -15,8 +15,8 @@
// 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. When no replay of another
// club stays on that day, the day loses bit 0x4000 again and can be a target once more.
// 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.
+3 -3
View File
@@ -27,7 +27,7 @@ void put32(Bytes& d, size_t at, uint32_t x) {
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
// four-year leap cycle that starts with the third year).
std::string date_text(uint32_t counter, int start_year) {
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))) {
@@ -45,7 +45,7 @@ std::string date_text(uint32_t counter, int start_year) {
if (++month == 13) month = 1, ++years;
}
char buf[16];
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, start_year + years);
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, 2026 + years);
return buf;
}
@@ -133,7 +133,7 @@ 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, g.display_start_year);
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++) {
-1
View File
@@ -174,7 +174,6 @@ struct GameState {
// 3 (stadiums, *ba360): not used by the engine, kept for writing savegames.
std::vector<uint8_t> master_database_metadata, referee_names, stadium_names;
std::vector<uint16_t> player_cards; // *PlayerCards, per player: card counters per competition
int display_start_year = 2026; // Cosmetic Classic origin; does not alter scheduling.
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.
-59
View File
@@ -1,59 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp save.cpp ../audio/container.cpp)
target_include_directories(bmh_obw PUBLIC ..)
target_link_libraries(bmh_obw PUBLIC bmhlaunch PRIVATE bmh_miniz)
add_executable(openbmh_import main.cpp)
target_link_libraries(openbmh_import PRIVATE bmh_content)
set_target_properties(openbmh_import PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
add_executable(obw_import_tests ../../tests/obw_import_tests.cpp)
target_link_libraries(obw_import_tests PRIVATE bmh_content bmh_miniz)
if(MSVC)
target_compile_options(bmh_obw PRIVATE /W4 /utf-8)
target_compile_options(openbmh_import PRIVATE /W4 /utf-8)
target_compile_options(obw_import_tests PRIVATE /W4 /utf-8)
else()
target_compile_options(bmh_obw PRIVATE -Wall -Wextra)
endif()
add_test(NAME obw_import_tests COMMAND obw_import_tests)
add_executable(obw_classic_installation_tests ../../tests/obw_classic_installation_tests.cpp)
target_link_libraries(obw_classic_installation_tests PRIVATE bmh_obw)
if(MSVC)
target_compile_options(obw_classic_installation_tests PRIVATE /W4 /utf-8)
endif()
bmh_add_data_test(NAME obw_classic_installation_tests COMMAND obw_classic_installation_tests "${BMH_DATA}")
install(TARGETS openbmh_import RUNTIME DESTINATION . COMPONENT Runtime)
add_library(bmh_content STATIC ../content/digest.cpp ../content/package.cpp ../content/save.cpp)
target_include_directories(bmh_content PUBLIC ..)
target_link_libraries(bmh_content PUBLIC bmh_obw PRIVATE bmh_miniz)
add_library(bmh_launcher STATIC ../launch/mods.cpp ../launch/process.cpp ../launch/launcher.cpp)
target_include_directories(bmh_launcher PUBLIC ..)
target_link_libraries(bmh_launcher PUBLIC bmh_content)
include(../launch/rmlui.cmake)
target_sources(bmh_launcher PRIVATE ../launch/launcher_rmlui.cpp)
target_link_libraries(bmh_launcher PRIVATE bmh_rmlui nfd)
add_executable(launcher_gui_smoke ../../tests/launcher_gui_smoke.cpp)
target_link_libraries(launcher_gui_smoke PRIVATE bmh_launcher bmh_rmlui)
set_target_properties(launcher_gui_smoke PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
add_executable(launcher_document_tests ../../tests/launcher_document_tests.cpp)
target_include_directories(launcher_document_tests PRIVATE ..)
target_link_libraries(launcher_document_tests PRIVATE RmlUi::Core)
add_test(NAME launcher_document_tests COMMAND launcher_document_tests "${launcher_assets}")
add_test(NAME launcher_unicode_document_tests COMMAND launcher_document_tests "${launcher_assets}" unicode)
if(MSVC)
target_compile_options(launcher_document_tests PRIVATE /utf-8)
endif()
add_executable(native_content_tests ../../tests/native_content_tests.cpp)
target_link_libraries(native_content_tests PRIVATE bmh_launcher)
add_test(NAME native_content_tests COMMAND native_content_tests)
add_executable(native_runtime_tests ../../tests/native_runtime_tests.cpp ${BMH_APP_SESSION_SDL_SOURCE} ${BMH_APP_CONTROLLER_SOURCE})
target_link_libraries(native_runtime_tests PRIVATE bmhui bmh_launcher openbmh_audio)
bmh_add_data_test(NAME native_runtime_tests COMMAND native_runtime_tests "${BMH_DATA}")
if(MSVC)
target_compile_options(bmh_content PRIVATE /W4 /utf-8)
target_compile_options(bmh_launcher PRIVATE /W4 /utf-8)
target_compile_options(native_content_tests PRIVATE /utf-8)
target_compile_options(native_runtime_tests PRIVATE /utf-8)
endif()
-335
View File
@@ -1,335 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/assets.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include "audio/container.hpp"
#include <algorithm>
#include <cctype>
#include <limits>
namespace bmh::obw {
namespace {
using namespace detail;
namespace fs = std::filesystem;
void be32(std::string& out, uint32_t value) {
for (int shift = 24; shift >= 0; shift -= 8) out += char(value >> shift);
}
void chunk(std::string& out, const char* name, const std::string& payload) {
be32(out, uint32_t(payload.size()));
const auto start = out.size();
out.append(name, 4);
out += payload;
be32(out, crc(out.substr(start)));
}
std::string png(const Image& image, const Palette& palette, bool transparent) {
std::string out("\x89PNG\r\n\x1a\n", 8), header;
be32(header, uint32_t(image.width)); be32(header, uint32_t(image.height));
header.append("\x08\x03\x00\x00\x00", 5); // indexed PNG, exact palette indices
chunk(out, "IHDR", header);
std::string colors;
for (const uint32_t color : palette.argb)
for (int shift : {16, 8, 0}) colors += char(color >> shift);
chunk(out, "PLTE", colors);
if (transparent) chunk(out, "tRNS", std::string(1, '\0'));
std::string rows;
for (int y = 0; y < image.height; ++y) {
rows += '\0';
rows.append(reinterpret_cast<const char*>(image.pixels.data() + size_t(y) * image.width), size_t(image.width));
}
mz_ulong size = mz_compressBound(static_cast<mz_ulong>(rows.size()));
std::string compressed(size, '\0');
if (mz_compress2(reinterpret_cast<unsigned char*>(compressed.data()), &size,
reinterpret_cast<const unsigned char*>(rows.data()), static_cast<mz_ulong>(rows.size()), MZ_BEST_COMPRESSION) != MZ_OK)
fail("cannot compress PNG");
compressed.resize(size);
chunk(out, "IDAT", compressed); chunk(out, "IEND", "");
return out;
}
fs::path required(const fs::path& root, const std::string& name) {
const auto path = launch::find_file(root, name);
if (!path || !fs::is_regular_file(*path) || fs::is_symlink(fs::symlink_status(*path))) fail("missing regular resource: " + name);
return *path;
}
std::string lower(std::string value) {
for (char& c : value) c = char(std::tolower(static_cast<unsigned char>(c)));
return value;
}
bool numeric(const std::string& name) {
return !name.empty() && std::all_of(name.begin(), name.end(), [](unsigned char c) { return c >= '0' && c <= '9'; });
}
// Source sprites use a linear packed stride; a feature may cross a row edge.
Image extract(const Image& atlas, int sx, int sy, int width, int height) {
if (sx < 0 || sy < 0 || width <= 0 || height <= 0 || width > 1024 || height > 1024) fail("invalid sprite geometry");
Image out(width, height);
for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) {
const auto at = size_t(sy + y) * size_t(atlas.width) + size_t(sx + x);
if (at >= atlas.pixels.size()) fail("sprite exceeds its packed atlas");
out.at(x, y) = atlas.pixels[at];
}
return out;
}
J asset(const std::string& key, const std::string& path, const std::string& source, const std::string& kind) {
return O{{"key", key}, {"files", O{{"native", path}}}, {"source", source},
{"author", "Original installation rights holders"}, {"license", "local-import-only"}, {"kind", kind}};
}
void image_entry(Documents& out, A& resources, A& index, const std::string& key,
const std::string& name, const Image& image, const Palette& palette, bool transparent = false) {
const auto base = "assets/classic/images/" + name;
out[base + ".png"] = png(image, palette, transparent);
out[base + ".pixels"] = binary(image.pixels);
resources.emplace_back(O{{"name", name}, {"width", image.width}, {"height", image.height},
{"pixels", base + ".pixels"}, {"png", base + ".png"}});
index.emplace_back(asset(key, base + ".png", name, "indexed-image"));
}
} // namespace
cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe) {
using namespace detail;
// Unsigned overflow and signed source characters deliberately match the UI.
uint32_t seed = 0x14344;
for (size_t i = 0; i < legacy_name.size(); ++i) seed += int(int8_t(legacy_name[i])) * uint32_t(i) * 10;
const auto next = [&](uint32_t maximum) {
seed = (seed * 16 + 0xa7) % 4000000;
return int(seed * (maximum + 1) / 4000000);
};
next(100);
const int background = next(3);
A layers;
for (uint32_t layer = 0; layer < 5; ++layer) {
const auto count = exe.u8(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + layer);
if (!count) fail("portrait layer has no parts");
layers.emplace_back(next(uint32_t(count - 1)));
}
return O{{"set", "bmh-classic@1"}, {"background", background}, {"layers", std::move(layers)}};
}
void import_assets(Documents& out, const std::filesystem::path& root, const Database& db, const LeImage& exe) {
using namespace detail;
const auto palette = load_palette(required(root, "M3PC.COL"));
A colors, index, images, fonts, audio, animations, palettes, supplemental;
for (const auto color : palette.argb) colors.emplace_back(int64_t(color));
put(out, "assets/classic/palette.json", O{{"schema", "classic-palette@1.0"}, {"argb", std::move(colors)}});
std::map<std::string, Image> atlases;
for (const char* group : {"KB", "W"}) {
const auto folder = launch::find_file(root, group);
if (!folder || !fs::is_directory(*folder)) fail(std::string("missing directory: ") + group);
std::vector<fs::path> paths;
for (const auto& entry : fs::directory_iterator(*folder))
if (entry.is_regular_file() && lower(launch::path_to_utf8(entry.path().extension())) == ".vga" &&
numeric(launch::path_to_utf8(entry.path().stem()))) paths.push_back(entry.path());
std::sort(paths.begin(), paths.end());
for (const auto& path : paths) {
if (fs::is_symlink(fs::symlink_status(path)) || fs::file_size(path) > 16 * 1024 * 1024) fail("unsafe image input");
const auto bytes = read_file(path);
if (bytes.size() < 8 || le16(bytes, 0) == 0 || le16(bytes, 2) == 0 ||
uint64_t(le16(bytes, 0)) * le16(bytes, 2) > 16 * 1024 * 1024) fail("invalid image dimensions");
const auto name = lower(group) + '/' + launch::path_to_utf8(path.stem());
if (atlases.contains(name)) fail("duplicate image resource: " + name);
auto image = decode_vga(bytes);
const size_t end = 8 + size_t(le32(bytes, 4));
if (end > bytes.size())
fail("invalid indexed image stream length");
Palette effective = palette;
if (bytes.size() - end >= 768) {
A entries;
for (size_t i = 0; i < 256; ++i) {
auto channel = [&](size_t c) { return uint32_t(vga_dac_rgb8(bytes[end + i * 3 + c])); };
effective.argb[i] = 0xff000000u | channel(0) << 16 | channel(1) << 8 | channel(2);
entries.emplace_back(int64_t(effective.argb[i]));
}
palettes.emplace_back(O{{"name", name}, {"argb", std::move(entries)}});
} else if (end != bytes.size())
fail("truncated embedded palette");
image_entry(out, images, index, "asset:classic/" + name, name, image, effective);
atlases.emplace(name, std::move(image));
}
}
// Crests reference their original database identity, independently of runtime draws.
auto clubs = items(out, "clubs");
for (auto& club : clubs) {
const auto team = size_t(num(get(get(club, "x-legacy"), "team_index")));
const int selector = le16(db.raw_club_badge_selectors, team * 2) & 511;
const std::string sheet = "w/" + std::to_string(selector >> 3);
const bool neutral = (team >= 90 && team < 138) || (team >= 168 && team < 357);
const std::string atlas_name = neutral ? "kb/0" : sheet;
if (!atlases.contains(atlas_name)) fail("missing crest sheet " + atlas_name);
const auto name = "crests/" + std::to_string(team);
const auto key = "asset:club/" + str(get(club, "id")).substr(str(get(club, "id")).find(':') + 1) + "/crest";
image_entry(out, images, index, key, name, extract(atlases.at(atlas_name), neutral ? 8 : (selector & 7) * 38, 0, 38, 38), palette, true);
(*club.object())["crest"] = key;
}
table(out, "clubs", std::move(clubs));
const auto portrait = atlases.find("kb/29");
if (portrait == atlases.end()) fail("missing player portrait atlas KB/29.VGA");
A backgrounds, layers;
for (int i = 0; i < 4; ++i) {
const auto name = "portraits/background-" + std::to_string(i);
const auto key = "asset:portrait/bmh-classic/background/" + std::to_string(i);
image_entry(out, images, index, key, name, extract(portrait->second, 108 + i * 38, 168, 38, 38), palette);
backgrounds.emplace_back(O{{"asset", key}, {"x", 0}, {"y", 0}});
}
for (uint32_t layer = 0; layer < 5; ++layer) {
int sx = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField + layer);
int sy = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField2 + layer);
const int count = exe.u8(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + layer);
const int width = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField3 + layer);
const int height = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField4 + layer);
if (!count) fail("empty portrait layer");
A parts;
for (int part = 0; part < count; ++part) {
const auto name = "portraits/layer-" + std::to_string(layer) + '-' + std::to_string(part);
const auto key = "asset:portrait/bmh-classic/layer/" + std::to_string(layer) + '/' + std::to_string(part);
image_entry(out, images, index, key, name, extract(portrait->second, sx, sy, width, height), palette, true);
parts.emplace_back(key);
sx += width;
if (sx > exe.u16(layout::ClubPlayerDetail_DrawPortrait_RuntimeField7 + layer * 2)) {
sx = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField + layer); sy += height;
}
}
// Destination relative to the 38x38 background at (181,109) in the legacy card.
layers.emplace_back(O{{"x", 1 + int(exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField5 + layer))},
{"y", 5 + int(exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField6 + layer))}, {"parts", std::move(parts)}});
}
put(out, "assets/portrait-sets/bmh-classic@1/set.json", O{{"schema", "portrait-set@1.0"},
{"id", "bmh-classic@1"}, {"width", 38}, {"height", 38}, {"transparent_index", 0},
{"backgrounds", std::move(backgrounds)}, {"layers", std::move(layers)}});
const auto font_dir = launch::find_file(root, "F");
if (!font_dir) fail("missing F directory");
for (const char* source : {"BMH2.FNT", "BMH3.FNT"}) {
const auto font = load_font(required(*font_dir, source));
const auto name = lower(source);
A glyphs;
for (const auto& glyph : font.glyphs) glyphs.emplace_back(O{{"bit_offset", int(glyph.bit_offset)},
{"bit_width", int(glyph.bit_width)}, {"advance", int(glyph.advance)}});
const auto bitmap = "assets/classic/fonts/" + name + ".bitmap";
out[bitmap] = binary(font.bitmap);
fonts.emplace_back(O{{"name", name}, {"height", font.height}, {"baseline", font.baseline},
{"nominal_width", font.nominal_width}, {"flags", int(font.flags)}, {"lo_char", int(font.lo_char)},
{"hi_char", int(font.hi_char)}, {"modulo", font.modulo}, {"glyphs", std::move(glyphs)}, {"bitmap", bitmap}});
index.emplace_back(asset("asset:font/classic/" + name, bitmap, std::string("F/") + source, "bitmap-font"));
}
const auto sound_dir = launch::find_file(root, "S");
if (!sound_dir) fail("missing S directory");
for (int i = 2000; i <= 2003; ++i) {
const auto name = std::to_string(i);
const auto bank = read_file(required(*sound_dir, name));
openbmh::audio::Container parsed;
std::string error;
if (!openbmh::audio::parse_container(bank, parsed, error)) fail("audio bank " + name + ": " + error);
const auto path = "assets/classic/audio/" + name + ".bank";
out[path] = binary(bank);
A chunks;
for (const auto& c : parsed.chunks) chunks.emplace_back(O{{"id", c.id}, {"offset", int64_t(c.payload_offset)}, {"size", int64_t(c.payload_size)}});
audio.emplace_back(O{{"name", name}, {"path", path}, {"codec", "original-alptraum@1"}, {"chunks", std::move(chunks)}});
index.emplace_back(asset("asset:audio/classic/" + name, path, "S/" + name, "audio-bank"));
}
// Preserve optional animation/editor artwork, but never personal options or saves.
for (const auto& entry : fs::directory_iterator(root)) {
const auto name = lower(launch::path_to_utf8(entry.path().filename()));
const auto ext = lower(launch::path_to_utf8(entry.path().extension()));
if (!entry.is_regular_file() || (ext != ".fli" && ext != ".flc" && name != "wappen.lbm")) continue;
if (entry.is_symlink() || entry.file_size() > 32 * 1024 * 1024) fail("unsafe optional artwork");
const auto path = "assets/classic/optional/" + name;
out[path] = binary(read_file(entry.path()));
animations.emplace_back(O{{"name", name}, {"path", path}});
index.emplace_back(asset("asset:classic/optional/" + name, path, name, "legacy-artwork"));
}
// The in-game readme is content too; preserve its original byte encoding locally.
const bool english = str(get(parse(out, "manifest.json"), "provenance")) == "import:fltd";
const auto texts = load_textd(required(root, english ? "TEXTE.BLK" : "TEXTD.BLK"));
if (texts.strings.size() > 839) {
const auto name = texts[839];
if (!name.empty() && fs::path(name) == fs::path(name).filename()) {
if (const auto source = launch::find_file(root, name); source && fs::is_regular_file(*source)) {
if (fs::is_symlink(fs::symlink_status(*source)) || fs::file_size(*source) > 1024 * 1024)
fail("unsafe readme input");
const auto path = "assets/classic/documents/readme.bytes";
out[path] = binary(read_file(*source));
supplemental.emplace_back(O{{"name", lower(name)}, {"path", path}});
}
}
}
put(out, "assets/classic/resources.json",
O{{"schema", "classic-resources@1.0"},
{"images", std::move(images)},
{"fonts", std::move(fonts)},
{"audio", std::move(audio)},
{"optional", std::move(animations)},
{"palettes", std::move(palettes)},
{"supplemental", std::move(supplemental)}});
put(out, "assets/index.json", O{{"schema", "asset-index@1.0"}, {"items", std::move(index)}});
}
void load_assets(const Documents& out, ClassicData& data) {
using namespace detail;
const auto palette = parse(out, "assets/classic/palette.json");
const auto& colors = arr(get(palette, "argb"));
if (colors.size() != 256) fail("palette must contain 256 colors");
for (size_t i = 0; i < 256; ++i) {
const auto color = num(colors[i]);
if (color < 0 || color > UINT32_MAX) fail("invalid palette color");
data.palette.argb[i] = uint32_t(color);
}
const auto resources = parse(out, "assets/classic/resources.json");
for (const auto& row : arr(get(resources, "images"))) {
const auto width = num(get(row, "width")), height = num(get(row, "height"));
const auto& pixels = out.at(str(get(row, "pixels")));
if (width <= 0 || height <= 0 || width > 65535 || height > 65535 || width * height != int64_t(pixels.size())) fail("image pixel count disagrees with dimensions");
Image image(int(width), int(height), 0);
image.pixels = bytes(pixels);
if (!data.images.emplace(str(get(row, "name")), std::move(image)).second) fail("duplicate indexed image");
}
for (const auto& row : arr(get(resources, "fonts"))) {
Font font;
font.height = int(num(get(row, "height"))); font.baseline = int(num(get(row, "baseline")));
font.nominal_width = int(num(get(row, "nominal_width"))); font.flags = uint8_t(num(get(row, "flags")));
font.lo_char = uint8_t(num(get(row, "lo_char"))); font.hi_char = uint8_t(num(get(row, "hi_char")));
font.modulo = int(num(get(row, "modulo"))); font.bitmap = bytes(out.at(str(get(row, "bitmap"))));
if (font.height <= 0 || font.modulo <= 0 || int64_t(font.height) * font.modulo != int64_t(font.bitmap.size())) fail("invalid font bitmap");
for (const auto& glyph : arr(get(row, "glyphs"))) {
const auto offset = num(get(glyph, "bit_offset")), width = num(get(glyph, "bit_width")), advance = num(get(glyph, "advance"));
// BMH2's zero-width replacement glyph points beyond the bitmap;
// it never dereferences that offset when drawing.
if (offset < 0 || offset > UINT16_MAX || width < 0 || width > UINT16_MAX ||
(width && offset + width > int64_t(font.modulo) * 8) || advance < INT16_MIN || advance > INT16_MAX) fail("invalid font glyph");
font.glyphs.push_back({uint16_t(offset), uint16_t(width), int16_t(advance)});
}
if (font.glyphs.size() != size_t(int(font.hi_char) - font.lo_char + 2)) fail("invalid font glyph count");
if (!data.fonts.emplace(str(get(row, "name")), std::move(font)).second) fail("duplicate font");
}
for (const auto& row : arr(get(resources, "audio"))) {
auto bank = bytes(out.at(str(get(row, "path"))));
openbmh::audio::Container parsed;
std::string error;
if (!openbmh::audio::parse_container(bank, parsed, error)) fail("invalid audio container: " + error);
if (!data.audio.emplace(str(get(row, "name")), std::move(bank)).second) fail("duplicate audio bank");
}
if (resources.object()->contains("palettes"))
for (const auto &row : arr(get(resources, "palettes"))) {
const auto &colors = arr(get(row, "argb"));
if (colors.size() != 256)
fail("invalid embedded palette");
Palette palette;
for (size_t i = 0; i < 256; ++i) {
const auto n = num(colors[i]);
if (n < 0 || n > UINT32_MAX)
fail("invalid color");
palette.argb[i] = uint32_t(n);
}
if (!data.image_palettes.emplace(str(get(row, "name")), palette).second)
fail("duplicate embedded palette");
}
if (resources.object()->contains("supplemental"))
for (const auto &row : arr(get(resources, "supplemental"))) {
if (!data.supplemental.emplace(str(get(row, "name")), bytes(out.at(str(get(row, "path")))))
.second)
fail("duplicate supplemental content");
}
if (!data.images.contains("kb/29") || data.fonts.size() != 2 || data.audio.size() != 4) fail("incomplete classic media");
}
} // namespace bmh::obw
-11
View File
@@ -1,11 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/classic.hpp"
namespace bmh::obw {
cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe);
// PNGs retain original resolution. Portrait PARTS are exported, never composed faces.
void import_assets(Documents& out, const std::filesystem::path& root,
const Database& db, const LeImage& exe);
void load_assets(const Documents& out, ClassicData& data);
} // namespace bmh::obw
-532
View File
@@ -1,532 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/classic.hpp"
#include "import/assets.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <cctype>
#include <iterator>
#include <set>
namespace bmh::obw {
namespace {
using namespace detail;
namespace fs = std::filesystem;
constexpr const char* profile = "classic-installation-v1";
constexpr const char* feature = "runtime:classic-v1";
constexpr const char* layout_id = "openbmh-classic-layout@1";
const A initializers{"classic-load-seeds@1", "classic-player-ratings@1", "classic-pending-offers@1",
"classic-markets-and-moods@1", "classic-free-agents@1", "classic-setup-options@1",
"classic-confirm-managers@1", "classic-season-setup@1"};
const A runtime_inputs{"game_rng_seed", "watcom_rng_seed", "managers", "game_level", "mode", "duration", "competition_options"};
struct Literal { const char* name; uint32_t address, size; };
// These four read-only labels share an LE code object. Extract the bounded
// strings individually, never the containing executable object/instructions.
constexpr Literal literals[] = {
{"free_kick_taker", layout::FreeKickTakerLabel, 9}, {"penalty_taker", layout::PenaltyTakerLabel, 9},
{"corner_taker", layout::CornerTakerLabel, 8}, {"automatic_takers", layout::AutomaticTakersLabel, 5}};
A literal_data(const LeImage& exe) {
constexpr char digits[] = "0123456789abcdef";
A values;
for (const auto& literal : literals) {
std::string hex;
bool terminated = false;
for (uint32_t i = 0; i < literal.size; ++i) {
const auto c = exe.u8(literal.address + i);
hex += digits[c >> 4]; hex += digits[c & 15];
if (c == 0) { terminated = true; break; }
if (c < 32 || c > 126) fail("invalid bounded embedded text literal");
}
if (!terminated) fail("unterminated bounded embedded text literal");
values.emplace_back(O{{"name", literal.name}, {"address", int(literal.address)}, {"bytes_hex", hex}});
}
return values;
}
Bytes required(const fs::path& root, const std::string& name, size_t size) {
const auto file = launch::find_file(root, name);
if (!file || !fs::is_regular_file(*file) || fs::is_symlink(fs::symlink_status(*file)) || fs::file_size(*file) != size)
fail(name + ": missing or incorrect size (expected " + std::to_string(size) + ')');
return read_file(*file);
}
A data_regions(Documents& out, const LeImage& exe, bool english, const std::string& variant) {
A regions;
const auto add = [&](const char* name, uint32_t begin, uint32_t end) {
if (!exe.contains(begin) || !exe.contains(end - 1)) fail("incomplete executable data region");
const std::string path = "x-classic/" + variant + '/' + name + ".bin";
out[path] = std::string(reinterpret_cast<const char*>(exe.data(begin)), end - begin);
regions.emplace_back(O{{"name", name}, {"base", int(begin)}, {"size", int(end - begin)}, {"path", path}});
};
add("common-data", layout::GermanDataSegmentBegin, layout::GermanImageEnd);
if (english) add("english-data", layout::EnDataStart, layout::Career_CompetitionPointersEnglish_RuntimeField);
return regions;
}
LeImage load_regions(const Documents& out, const J& value, const J& embedded, bool english) {
const auto& regions = arr(value);
if (regions.size() != size_t(english ? 2 : 1)) fail("incorrect data-region count");
Bytes image(layout::GermanImageEnd - 0x10000, 0);
std::set<uint32_t> seen;
for (const auto& region : regions) {
const auto base = num(get(region, "base")), size = num(get(region, "size"));
const bool german = base == layout::GermanDataSegmentBegin && size == layout::GermanImageEnd - layout::GermanDataSegmentBegin;
const bool en = english && base == layout::EnDataStart && size == layout::Career_CompetitionPointersEnglish_RuntimeField - layout::EnDataStart;
if ((!german && !en) || !seen.insert(uint32_t(base)).second) fail("unsupported/duplicate data region (code is forbidden)");
const auto& bytes = out.at(str(get(region, "path")));
if (int64_t(bytes.size()) != size) fail("truncated data region");
std::copy(bytes.begin(), bytes.end(), image.begin() + (base - 0x10000));
}
const auto& texts = arr(embedded);
if (texts.size() != std::size(literals)) fail("incomplete embedded text literals");
for (size_t i = 0; i < std::size(literals); ++i) {
const auto& literal = literals[i];
const auto data = unhex(str(get(texts[i], "bytes_hex")));
if (num(get(texts[i], "address")) != literal.address || str(get(texts[i], "name")) != literal.name ||
data.empty() || data.size() > literal.size || data.back() != 0) fail("invalid embedded text literal binding");
for (size_t ch = 0; ch + 1 < data.size(); ++ch)
if (data[ch] < 32 || data[ch] > 126) fail("invalid embedded text character");
std::copy(data.begin(), data.end(), image.begin() + (literal.address - 0x10000));
}
return LeImage::from_bytes(0x10000, std::move(image));
}
J localized(const std::string& value) { return O{{"default", legacy_text(value)}}; }
void competitions(Documents& out, const LeImage& exe) {
auto comps = items(out, "competitions");
const auto texts = parse(out, "x-legacy/texts.json");
const auto& strings = arr(get(texts, "items"));
std::map<int, A> cups;
for (uint32_t entry = 0; entry < 36; ++entry) {
const uint32_t at = layout::CupTable + entry * 0x28;
const int cup = int(int16_t(exe.u16(at + 0x18)));
if (cup < 0 || cup > 26) continue; // reserved sentinel entries stay in data regions
const int flags = exe.u8(at + 0x14), next = int(int8_t(exe.u8(at + 0x16)));
const int parallel = int(int8_t(exe.u8(at + 0x17)));
const int count = exe.u8(at + 0x1a);
O stage{{"id", "entry-" + std::to_string(entry)}, {"format", (flags & 4) ? "knockout" : "groups"},
{"teams", count}, {"legs", 1 + (flags & 1)}, {"matchdays", "calendar:classic-cup-" + std::to_string(cup)},
{"slots", A{O{{"resolver", "classic-entry@1"}, {"entry", int(entry)}, {"count", count}}}},
{"classic", O{{"entry", int(entry)}, {"flags", flags}, {"next_entry", next}, {"parallel_entry", parallel},
{"rounds", int(exe.u8(at + 0x1b))}, {"qualifying_rounds", int(exe.u8(at + 0x1c))},
{"groups", int(exe.u8(at + 0x1e) & 15)}, {"group_index", int(exe.u8(at + 0x1e) >> 4)},
{"qualification_quota", int(int8_t(exe.u8(at + 0x1f)))},
{"draw_each_round", bool(flags & 0x20)}, {"decide_on_day", bool(flags & 8)}}}};
cups[cup].emplace_back(std::move(stage));
}
const auto english = str(get(parse(out, "manifest.json"), "provenance")) == "import:fltd";
for (auto& [cup, stages] : cups) {
const auto text_index = (layout::DeskState_FormatError_ExecutableField3 - layout::TextPointerTable) / 4 + uint32_t(cup + 1);
const auto label = text_index < strings.size() ? get(strings[text_index], "text") : J("Classic competition " + std::to_string(cup));
std::string type = cup == 0 ? "cup" : cup >= 1 && cup <= 3 ? "club_international" :
cup >= 4 && cup <= 8 ? "national_team" : cup == 10 ? "friendly" : cup == 11 && !english ? "indoor" : "cup";
comps.emplace_back(O{{"id", "comp:classic-cup-" + std::to_string(cup)}, {"name", O{{"default", label}}},
{"trophy", "asset:comp/classic-cup-" + std::to_string(cup) + "/trophy"},
{"type", type}, {"played", true}, {"stages", std::move(stages)},
{"classic", O{{"competition_id", cup}, {"calendar_bit", cup + 5},
{"qualification", "classic-season-entrants@1"}, {"runtime_participants", true}}}});
}
table(out, "competitions", std::move(comps));
auto calendars = items(out, "calendar");
auto& calendar = *calendars.at(0).object();
auto series = arr(calendar.at("series"));
for (const auto& [cup, unused] : cups) {
(void)unused;
series.emplace_back(O{{"id", "classic-cup-" + std::to_string(cup)}, {"legacy_calendar_bit", cup + 5}});
}
calendar["series"] = std::move(series);
calendar["initialization"] = O{{"policy", "classic-calendar@1"},
{"inputs", A{"start_date", "season_index", "competition_options"}},
{"source_anchor", "07-01"}, {"weekday_alignment", "classic-season-calendar@1"}};
table(out, "calendar", std::move(calendars));
}
} // namespace
void complete_classic(Documents& out, const fs::path& root, const Database& db,
const LeImage& exe, const LeImage& source_tables, bool english, const Options& options) {
using namespace detail;
const auto mod = english ? "FLTD-classic" : "BMH-classic";
if (!options.mod.empty() && options.mod != mod) fail("--mod does not match the source edition (expected " + std::string(mod) + ')');
const auto desktop = required(root, "M3.MEN", 864);
const auto formations = required(root, "M3.DAT", 1408);
out["x-classic/desktop-seed.bin"] = binary(desktop);
out["x-classic/formation-seed.bin"] = binary(formations);
const auto source_text = launch::find_file(root, english ? "TEXTE.BLK" : "TEXTD.BLK");
if (!source_text) fail("missing source text block");
const auto raw_texts = read_file(*source_text);
if (raw_texts.size() < 7) fail("truncated source text block");
out["x-classic/text-blob.bin"] = std::string(raw_texts.begin() + 7, raw_texts.end());
A text_header;
for (size_t i = 0; i < 7; ++i) text_header.emplace_back(int(raw_texts[i]));
const auto effective_regions = data_regions(out, exe, english, "effective");
const auto original_regions = data_regions(out, source_tables, english, "source");
put(out, "x-classic/startup.json", O{{"schema", "classic-startup@1.0"}, {"layout", layout_id},
{"mod", mod}, {"english", english}, {"rule_profile", "openbmh-supported@1"},
{"data_regions", effective_regions}, {"source_regions", original_regions},
{"embedded_literals", literal_data(exe)}, {"source_literals", literal_data(source_tables)},
{"desktop_seed", "x-classic/desktop-seed.bin"}, {"formation_seed", "x-classic/formation-seed.bin"},
{"text_blob", "x-classic/text-blob.bin"},
{"text_header", std::move(text_header)},
{"initializers", initializers}, {"runtime_inputs", runtime_inputs},
{"rng", O{{"import_consumes_draws", false}, {"game", "bmh-game@1"}, {"secondary", "watcom@1"}}}});
auto manifest = parse(out, "manifest.json");
auto& m = *manifest.object();
m["id"] = std::string("world:") + mod;
m["mod"] = mod;
m["requires"] = A{feature};
m["extensions"] = A{O{{"id", "x-legacy"}, {"version", "1.0"}}, O{{"id", "x-classic"}, {"version", "1.0"}}};
m["x-import"] = O{{"profile", profile}, {"content_complete", true}, {"runtime", feature},
{"rule_profile", "openbmh-supported@1"}, {"source_rules_preserved", true},
{"default_attribute_set", "bmh-classic@1"}, {"default_portrait_set", "bmh-classic@1"}};
put(out, "manifest.json", std::move(manifest));
auto players = items(out, "players");
A contracts;
for (size_t i = 0; i < players.size(); ++i) {
auto& player = *players[i].object();
player["appearance"] = portrait_recipe(db.players.at(i).name, exe);
player["photo"] = "asset:player/" + str(player.at("id")).substr(7) + "/photo";
if (player.contains("team")) contracts.emplace_back(O{{"id", id("contract", i)}, {"person", player.at("id")},
{"team", player.at("team")}, {"initialization", O{{"policy", "classic-player-contract@1"},
{"source_identity_word", int64_t(db.players.at(i).w364)}, {"source_skill_word", int64_t(db.players.at(i).w368)}}}});
}
table(out, "players", std::move(players));
table(out, "contracts", std::move(contracts));
auto nations = items(out, "nations");
auto clubs = items(out, "clubs");
A finance;
for (auto& club : clubs) {
auto& row = *club.object();
const auto team = size_t(num(get(row.at("x-legacy"), "team_index")));
if (team >= 168 && team < 357) row["nation"] = get(nations.at(5 + (team - 168) / 7), "id");
if (team >= 168) {
constexpr int levels[] = {55, 61, 65, 67, 70, 73, 76, 80};
const auto code = db.raw_foreign_club_strength.at(team - 168);
row["classic_strength"] = O{{"band", int(code >> 5)}, {"base", levels[code >> 5]},
{"style_flags", int(code & 31)}, {"policy", "classic-strength-only-team@1"}};
}
row["kit"] = O{{"set", "bmh-classic@1"}, {"selector", int(db.raw_club_kit_selectors.at(team))}};
if (team < 138) {
row["stadium_initialization"] = O{{"policy", "classic-stadium@1"}, {"name_pool", "stadiums"}};
finance.emplace_back(O{{"id", id("finance", team)}, {"team", row.at("id")},
{"initialization", O{{"policy", "classic-manager-finance@1"},
{"when", "human_manager_assigned"}, {"inputs", A{"game_level", "mode", "start_league"}}}}});
}
}
table(out, "clubs", std::move(clubs));
nations.erase(std::remove_if(nations.begin(), nations.end(), [](const J& nation) {
return str(get(nation, "id")) == "nation:x-legacy-unassigned";
}), nations.end());
table(out, "nations", std::move(nations));
table(out, "finance", std::move(finance));
A staff;
for (size_t i = 0; i < db.referees.size(); ++i) {
if (i >= db.raw_referee_properties.size()) fail("referee property count mismatch");
const auto property = db.raw_referee_properties[i];
staff.emplace_back(O{{"id", id("staff", i)}, {"name", localized(db.referees[i])}, {"role", "referee"},
{"attributes", O{{"strictness", int((property >> 3) & 3)}}},
{"x-legacy", O{{"referee_index", int(i)}, {"property", int(property)}}}});
}
table(out, "staff", std::move(staff));
auto rules = items(out, "rules");
rules.emplace_back(O{{"id", "rule:classic-runtime"}, {"type", "classic_runtime"}, {"version", 1},
{"startup", "x-classic/startup.json"}, {"layout", layout_id},
{"calendar", "classic-calendar@1"}, {"qualifications", "classic-season-entrants@1"},
{"financial_initialization", "classic-manager-finance@1"}, {"stadium_initialization", "classic-stadium@1"},
{"contract_initialization", "classic-player-contract@1"}, {"staff_initialization", "classic-confirm-managers@1"},
{"default_portrait_set", "bmh-classic@1"}});
rules.emplace_back(O{{"id", "rule:classic-data-tables"}, {"type", "classic_data_regions"},
{"layout", layout_id}, {"effective", effective_regions}, {"source", original_regions},
{"coverage", A{"competition_configuration", "qualification_and_movement", "calendar", "player_generation",
"contracts", "finance", "sponsors", "training", "stadiums", "transfer_market", "national_teams",
"match_parameters", "embedded_texts", "interface_tables", "audio_tables"}}});
table(out, "rules", std::move(rules));
competitions(out, exe);
import_assets(out, root, db, exe);
auto report = parse(out, "x-legacy/import-report.json");
auto& r = *report.object();
r["profile"] = profile;
r["unmapped"] = A{};
auto warnings = arr(r.at("warnings"));
warnings.erase(std::remove_if(warnings.begin(), warnings.end(), [](const J& warning) {
return warning.string() && warning.string()->starts_with("foreign club nation assignments");
}), warnings.end());
r["warnings"] = std::move(warnings);
r["coverage"] = O{{"core_entities", true}, {"all_classic_data_regions", true}, {"media", true},
{"new_career_initialization", "runtime:classic-v1"}, {"savegame_conversion", false}};
r["notes"] = A{"Complete installation content for the versioned Classic adapter, not a running career.",
"Runtime-generated values are initialization policies, not fabricated initial contracts or stadiums.",
"Generic competitions/rules are projections. Exact classic semantics use x-classic data and runtime:classic-v1.",
"Both the supported effective tables and unpatched source data tables are retained; no executable code is exported.",
"Player appearances are frozen from the original byte names; only portrait parts, never composed faces, are stored.",
"No FBM, personal EIN, SOUND.CFG, high scores, or executable is copied.",
"No 0.1 frontend reads OBW. The 0.2 runtime adapter is separate work."};
put(out, "x-legacy/import-report.json", std::move(report));
// All payload entries, including binary assets, are checked before publication/load.
refresh_classic_inventory(out);
}
void refresh_classic_inventory(Documents& out) {
using namespace detail;
A inventory;
for (const auto& [path, contents] : out)
if (path != "x-classic/inventory.json" && path != "x-classic/seal.json")
inventory.emplace_back(O{{"path", path}, {"bytes", int64_t(contents.size())}, {"crc32", int64_t(crc(contents))}});
put(out, "x-classic/inventory.json", O{{"schema", "classic-inventory@1.0"}, {"entries", std::move(inventory)}});
}
static ClassicData decode_classic(const Documents& out) {
using namespace detail;
const auto startup = parse(out, "x-classic/startup.json");
if (str(get(startup, "schema")) != "classic-startup@1.0" || str(get(startup, "layout")) != layout_id)
fail("unsupported classic startup/layout version");
ClassicData data;
const auto *en = get(startup, "english").boolean();
if (!en)
fail("invalid edition flag");
data.english = *en;
data.executable =
load_regions(out, get(startup, "data_regions"), get(startup, "embedded_literals"), data.english);
data.source_tables =
load_regions(out, get(startup, "source_regions"), get(startup, "source_literals"), data.english);
// Reconstruct the native Classic database fields directly. The original M3D
// byte stream is retained as import provenance only, never parsed at runtime.
const auto database = parse(out, "x-legacy/database.json");
const auto &counts = get(database, "counts");
if (num(get(counts, "clubs")) != 419 || num(get(counts, "players")) != 2574 ||
num(get(counts, "n42")) != 168 || num(get(counts, "n66")) != 3096)
fail("unsupported Classic database dimensions");
auto &db = data.database;
const auto &pools = arr(get(database, "pools"));
if (pools.size() != 4)
fail("invalid native name pools");
for (size_t i = 0; i < 4; ++i)
db.pools[i] = unhex(str(pools[i]));
const auto &tables = get(database, "tables");
const auto table = [&](const char *name, Bytes &target, size_t expected) {
target = unhex(str(get(tables, name)));
if (target.size() != expected)
fail(std::string("invalid Classic table size: ") + name);
};
table("player_bonus_values", db.raw_player_bonus_values, 3096 + 0x32);
table("database_metadata", db.raw_database_metadata, 100);
table("club_auxiliary_words", db.raw_club_auxiliary_words, 168 * 2);
table("club_badge_selectors", db.raw_club_badge_selectors, 419 * 2);
table("foreign_club_strength", db.raw_foreign_club_strength, 0xfb);
table("league_auxiliary_bytes", db.raw_league_auxiliary_bytes, 0xbd);
table("referee_properties", db.raw_referee_properties, 50);
table("club_kit_selectors", db.raw_club_kit_selectors, 419);
table("club_short_name_offsets", db.raw_club_short_name_offsets, 168);
table("club_name_offsets", db.raw_club_name_offsets, 419 * 2);
table("player_name_offsets", db.raw_player_name_offsets, 2574 * 2);
table("squad_list", db.squad_list, (3096 - 4) * 2 + 0x6c);
const auto name = [&](size_t pool, size_t offset) {
const auto &bytes = db.pools[pool];
if (offset >= bytes.size())
fail("native name offset outside pool");
const auto end = std::find(bytes.begin() + offset, bytes.end(), 0);
if (end == bytes.end())
fail("unterminated native name");
return std::string(bytes.begin() + offset, end);
};
for (size_t i = 0; i < 419; ++i)
db.club_names.push_back(name(0, le16(db.raw_club_name_offsets, i * 2)));
db.players.resize(2574);
std::set<size_t> player_ids;
for (const auto &player : items(out, "players")) {
const auto &raw = get(player, "x-legacy");
const auto id = num(get(raw, "player_index"));
if (id < 0 || id >= 2574 || !player_ids.insert(size_t(id)).second)
fail("invalid native player identity");
auto &value = db.players[size_t(id)];
value.name = name(1, le16(db.raw_player_name_offsets, size_t(id) * 2));
const auto word = [&](const char *key) {
const auto n = num(get(raw, key));
if (n < 0 || n > UINT32_MAX)
fail("invalid native player word");
return uint32_t(n);
};
value.w35c = word("condition_technique_form_word");
value.w368 = word("skill_word");
value.w364 = word("identity_word");
}
if (player_ids.size() != 2574)
fail("incomplete native player records");
const auto split = [&](size_t pool, std::vector<std::string> &values) {
size_t at = 0;
while (at < db.pools[pool].size()) {
auto value = name(pool, at);
at += value.size() + 1;
values.push_back(std::move(value));
}
};
split(2, db.referees);
split(3, db.stadiums);
data.desktops = bytes(out.at(str(get(startup, "desktop_seed"))));
data.formations = bytes(out.at(str(get(startup, "formation_seed"))));
if (data.desktops.size() != 864 || data.formations.size() != 1408)
fail("invalid startup seed sizes");
data.texts.blob = bytes(out.at(str(get(startup, "text_blob"))));
const auto &header = arr(get(startup, "text_header"));
if (header.size() != 7)
fail("invalid source text header");
for (const auto &byte : header) {
if (num(byte) < 0 || num(byte) > 255)
fail("invalid source text header byte");
data.text_header.push_back(uint8_t(num(byte)));
}
size_t position = 0;
while (data.texts.strings.size() < TEXT_COUNT && position < data.texts.blob.size()) {
const auto begin = position;
while (position < data.texts.blob.size() && data.texts.blob[position])
++position;
if (position == data.texts.blob.size())
fail("unterminated classic text");
data.texts.offsets.push_back(begin);
data.texts.strings.emplace_back(data.texts.blob.begin() + begin, data.texts.blob.begin() + position);
++position;
}
if (data.texts.strings.size() != TEXT_COUNT)
fail("incomplete classic texts");
load_assets(out, data);
return data;
}
void validate_classic(const Documents &out) {
using namespace detail;
const auto manifest = parse(out, "manifest.json");
const auto &imported = get(manifest, "x-import");
if (str(get(imported, "profile")) != profile || !get(imported, "content_complete").boolean() ||
!*get(imported, "content_complete").boolean())
fail("incomplete classic profile");
const auto &required_features = arr(get(manifest, "requires"));
if (required_features.size() != 1 || str(required_features[0]) != feature)
fail("missing classic runtime requirement");
const auto startup = parse(out, "x-classic/startup.json");
const auto expected = str(get(manifest, "provenance")) == "import:fltd" ? "FLTD-classic" : "BMH-classic";
if (str(get(manifest, "mod")) != expected || str(get(startup, "mod")) != expected)
fail("mod/edition mismatch");
if (str(get(imported, "rule_profile")) != "openbmh-supported@1" ||
str(get(startup, "rule_profile")) != "openbmh-supported@1" ||
cli::dump_json(get(startup, "initializers")) != cli::dump_json(initializers) ||
cli::dump_json(get(startup, "runtime_inputs")) != cli::dump_json(runtime_inputs))
fail("unsupported classic initialization contract");
std::set<std::string> seen;
const auto inventory = parse(out, "x-classic/inventory.json");
for (const auto& entry : arr(get(inventory, "entries"))) {
const auto path = str(get(entry, "path"));
if (!safe_path(path) || path == "x-classic/inventory.json" || !seen.insert(path).second || !out.contains(path)) fail("invalid inventory entry: " + path);
const auto& bytes = out.at(path);
if (int64_t(bytes.size()) != num(get(entry, "bytes")) || int64_t(crc(bytes)) != num(get(entry, "crc32"))) fail("damaged entry: " + path);
if (path.starts_with("state/")) fail("save state is forbidden in an installation mod");
auto suffix = fs::path(path).extension().string();
for (char& ch : suffix) ch = char(std::tolower(static_cast<unsigned char>(ch)));
if (suffix == ".exe" || suffix == ".fbm" || suffix == ".obs" || suffix == ".ein" || suffix == ".cfg") fail("non-content file in classic world");
}
if (seen.size() + 1 + size_t(out.contains("x-classic/seal.json")) != out.size())
fail("unlisted archive entries");
auto data = decode_classic(out);
if (data.english != (std::string(expected) == "FLTD-classic")) fail("startup edition mismatch");
// Every fixture pointer must remain readable from the exported DATA view.
const auto fixture_rules = items(out, "rules");
const auto fixture = std::find_if(fixture_rules.begin(), fixture_rules.end(), [](const J& row) {
return str(get(row, "id")) == "rule:legacy-fixtures";
});
if (fixture == fixture_rules.end()) fail("missing fixture generators");
const std::map<int, uint32_t> bindings = data.english ?
std::map<int, uint32_t>{{4, layout::EnglishFourTeamFixtureTable}, {6, layout::EnglishSixTeamFixtureTable},
{12, layout::EnglishTwelveTeamFixtureTable}, {20, layout::EnglishTwentyTeamFixtureTable}} :
std::map<int, uint32_t>{{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}};
std::set<int> fixture_sizes;
for (const auto& entry : arr(get(*fixture, "tables"))) {
const int teams = int(num(get(entry, "teams")));
if (!bindings.contains(teams) || !fixture_sizes.insert(teams).second) fail("invalid fixture generator size");
if (str(get(entry, "id")) != "legacy:" + std::to_string(teams)) fail("invalid fixture generator identity");
const auto& rounds = arr(get(entry, "rounds"));
if (rounds.size() != size_t(teams - 1)) fail("invalid fixture round count");
for (size_t round = 0; round < rounds.size(); ++round) {
const auto row = data.executable.cstring(data.executable.u32(bindings.at(teams) + uint32_t(round + 1) * 4));
if (row.size() != size_t(teams) || arr(rounds[round]).size() != size_t(teams / 2)) fail("incomplete fixture round data");
std::set<char> seen;
for (const char team : row)
if (team < 'a' || team >= 'a' + teams || !seen.insert(team).second) fail("invalid fixture round participants");
for (size_t match = 0; match < size_t(teams / 2); ++match) {
const auto& pair = arr(arr(rounds[round])[match]);
if (pair.size() != 2 || num(pair[0]) != row[match * 2] - 'a' || num(pair[1]) != row[match * 2 + 1] - 'a') fail("fixture projection disagrees with classic data");
}
}
}
if (fixture_sizes.size() != bindings.size()) fail("incomplete fixture generators");
const auto portrait_set = parse(out, "assets/portrait-sets/bmh-classic@1/set.json");
const auto& layers = arr(get(portrait_set, "layers"));
if (layers.size() != 5 || arr(get(portrait_set, "backgrounds")).size() != 4) fail("invalid portrait set");
std::set<std::string> assets;
const auto index = parse(out, "assets/index.json");
for (const auto& row : arr(get(index, "items"))) {
const auto key = str(get(row, "key"));
if (!key.starts_with("asset:") || !assets.insert(key).second || str(get(row, "license")) != "local-import-only") fail("invalid asset metadata");
const auto* files = get(row, "files").object();
if (!files || files->empty()) fail("missing asset files");
for (const auto& [size, path] : *files) {
(void)size;
if (!out.contains(str(path))) fail("missing asset file: " + str(path));
}
}
for (const auto& row : arr(get(portrait_set, "backgrounds")))
if (!assets.contains(str(get(row, "asset")))) fail("missing portrait background asset");
for (const auto& layer : layers) for (const auto& part : arr(get(layer, "parts")))
if (!assets.contains(str(part))) fail("missing portrait part asset");
const auto players = items(out, "players");
if (players.size() != data.database.players.size()) fail("incomplete player projections");
for (const auto& player : players) {
const auto& appearance = get(player, "appearance");
const auto background = num(get(appearance, "background"));
const auto& parts = arr(get(appearance, "layers"));
if (str(get(appearance, "set")) != "bmh-classic@1" || background < 0 || background > 3 || parts.size() != 5) fail("invalid frozen player appearance");
for (size_t i = 0; i < 5; ++i)
if (num(parts[i]) < 0 || num(parts[i]) >= int64_t(arr(get(layers[i], "parts")).size())) fail("portrait part index out of range");
}
const auto clubs = items(out, "clubs");
for (const auto& club : clubs) if (!assets.contains(str(get(club, "crest")))) fail("missing club crest");
if (items(out, "finance").size() != 138 || items(out, "staff").size() != data.database.referees.size()) fail("incomplete finance/staff seeds");
std::map<std::string, std::string> owned;
for (const auto& player : players)
if (player.object()->contains("team")) owned.emplace(str(get(player, "id")), str(get(player, "team")));
const auto contracts = items(out, "contracts");
if (contracts.size() != owned.size()) fail("incomplete contract seeds");
for (const auto& contract : contracts) {
const auto who = str(get(contract, "person"));
if (!owned.contains(who) || owned.at(who) != str(get(contract, "team"))) fail("contract does not match its player/team");
owned.erase(who);
}
std::set<int> entries;
size_t leagues = 0;
for (const auto& competition : items(out, "competitions")) {
if (str(get(competition, "type")) == "league") { ++leagues; continue; }
const auto cup = num(get(get(competition, "classic"), "competition_id"));
for (const auto& stage : arr(get(competition, "stages"))) {
const auto entry = num(get(get(stage, "classic"), "entry"));
if (entry < 0 || entry >= 36 || !entries.insert(int(entry)).second ||
data.executable.u16(layout::CupTable + uint32_t(entry) * 0x28 + 0x18) != cup) fail("invalid classic cup stage binding");
}
}
if (leagues != 9) fail("classic world requires nine league definitions");
for (uint32_t entry = 0; entry < 36; ++entry) {
const int cup = int(int16_t(data.executable.u16(layout::CupTable + entry * 0x28 + 0x18)));
if (cup >= 0 && cup <= 26 && !entries.contains(int(entry))) fail("missing classic cup stage");
}
}
ClassicData load_classic(const Documents& out) {
validate(out);
return decode_classic(out);
}
} // namespace bmh::obw
-18
View File
@@ -1,18 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/obw.hpp"
#include "formats/content.hpp"
#include "formats/palette.hpp"
namespace bmh::obw {
// Installation content only. No manager choices, career RNG or save state.
using ClassicData = content::Classic;
void complete_classic(Documents& out, const std::filesystem::path& root,
const Database& database, const LeImage& executable,
const LeImage& source_tables, bool english, const Options& options);
void validate_classic(const Documents& out);
// For an editor after deliberate changes. CRC32 detects damage, not authenticity.
void refresh_classic_inventory(Documents& out);
ClassicData load_classic(const Documents& out);
} // namespace bmh::obw
-83
View File
@@ -1,83 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/obw.hpp"
#include <iomanip>
#include <sstream>
#include <string_view>
#include "miniz.h"
namespace bmh::obw::detail {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
[[noreturn]] inline void fail(const std::string& message) { throw FormatError("OBW: " + message); }
inline const J& get(const J& value, std::string_view key) {
if (!value.object()) fail("expected object for field: " + std::string(key));
const auto found = value.object()->find(key);
if (found == value.object()->end()) fail("missing field: " + std::string(key));
return found->second;
}
inline std::string str(const J& value) {
if (!value.string()) fail("expected string");
return *value.string();
}
inline int64_t num(const J& value) {
if (!value.integer()) fail("expected integer");
return *value.integer();
}
inline const A& arr(const J& value) {
if (!value.array()) fail("expected array");
return *value.array();
}
inline J parse(const Documents& out, const std::string& path) {
if (!out.contains(path)) fail("missing entry: " + path);
return cli::parse_json(out.at(path));
}
inline void put(Documents& out, const std::string& path, J value) {
out[path] = cli::dump_json(value) + '\n';
}
inline A items(const Documents& out, const std::string& table) {
return arr(get(parse(out, "world/" + table + ".json"), "items"));
}
inline void table(Documents& out, const std::string& name, A values) {
put(out, "world/" + name + ".json", O{{"schema", name + "@1.0"}, {"items", std::move(values)}});
}
inline std::string id(const std::string& prefix, size_t index) {
std::ostringstream out;
out << prefix << ':' << std::setfill('0') << std::setw(5) << index;
return out.str();
}
inline std::string binary(const Bytes& bytes) { return std::string(bytes.begin(), bytes.end()); }
inline Bytes bytes(const std::string& value) { return Bytes(value.begin(), value.end()); }
inline std::string legacy_text(const std::string& raw) {
std::string result;
for (const unsigned char byte : raw) {
if (byte >= 128) { result += char(0xc0 | (byte >> 6)); result += char(0x80 | (byte & 63)); }
else { const char one[] = {char(byte), 0}; result += iso646de_to_utf8(one, 1); }
}
return result;
}
inline Bytes unhex(const std::string& hex) {
if (hex.size() % 2) fail("odd hex length");
const auto digit = [](char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
fail("invalid hex digit");
};
Bytes result;
result.reserve(hex.size() / 2);
for (size_t i = 0; i < hex.size(); i += 2) result.push_back(uint8_t(digit(hex[i]) * 16 + digit(hex[i + 1])));
return result;
}
inline uint32_t crc(const std::string& data) {
return uint32_t(mz_crc32(MZ_CRC32_INIT, reinterpret_cast<const unsigned char*>(data.data()), data.size()));
}
inline bool safe_path(const std::string& path) {
if (path.empty() || path.front() == '/' || path.back() == '/' || path.find('\\') != std::string::npos ||
path.find(':') != std::string::npos || path.find('\0') != std::string::npos) return false;
std::istringstream parts(path);
std::string part;
while (std::getline(parts, part, '/')) if (part.empty() || part == "." || part == "..") return false;
return true;
}
} // namespace bmh::obw::detail
-83
View File
@@ -1,83 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/obw.hpp"
#include "content/package.hpp"
#include "launch/archive.hpp"
#include "version.hpp"
#include <iostream>
#include <stdexcept>
int main(int argc, char** argv) {
try {
const auto args = bmh::launch::utf8_arguments(argc, argv);
std::filesystem::path source, destination, validate_path;
bmh::obw::Options options;
bool directory = false;
for (size_t i = 1; i < args.size(); ++i) {
const auto& arg = args[i];
if (arg == "--help" || arg == "-h") {
std::cout << "OpenBMH installation-to-OBW converter\n"
"Usage: openbmh_import --data DIR_OR_EXE --output WORLD.obw\n"
" --start-date YYYY-07-01 [--mod BMH-classic|FLTD-classic]\n"
" [--title TEXT] [--directory] [--database-only]\n"
" openbmh_import --validate WORLD.obw_OR_DIRECTORY\n\n"
"Imports a complete BMH or Football Limited installation, including media.\n"
"--directory writes an unpacked world instead of a ZIP archive.\n"
"Existing destinations are never overwritten. Imported content stays local.\n"
"--database-only explicitly selects the old partial development export.\n"
"Classic content targets the 0.2 adapter; 0.1 cannot load OBW. No FBM conversion.\n";
return 0;
}
if (arg == "--version") {
std::cout << "OpenBMH importer " << bmh::kOpenBmhVersion << " (OBW 1.0)\n";
return 0;
}
if (arg == "--directory") { directory = true; continue; }
if (arg == "--database-only") { options.database_only = true; continue; }
if (arg != "--data" && arg != "--output" && arg != "--start-date" && arg != "--title" &&
arg != "--mod" && arg != "--validate")
throw std::runtime_error("unknown option: " + arg);
if (++i == args.size()) throw std::runtime_error("missing value for " + arg);
if (arg == "--data") source = bmh::launch::path_from_utf8(args[i]);
if (arg == "--output") destination = bmh::launch::path_from_utf8(args[i]);
if (arg == "--start-date") options.start_date = args[i];
if (arg == "--title") options.title = args[i];
if (arg == "--mod") {
options.mod = args[i];
if (options.mod == "FTDL-classic" || options.mod == "FTLD-classic") options.mod = "FLTD-classic";
if (options.mod != "BMH-classic" && options.mod != "FLTD-classic")
throw std::runtime_error("--mod must be BMH-classic or FLTD-classic");
}
if (arg == "--validate") validate_path = bmh::launch::path_from_utf8(args[i]);
}
if (!validate_path.empty()) {
if (!source.empty() || !destination.empty() || !options.start_date.empty() || !options.mod.empty() || directory || options.database_only)
throw std::runtime_error("--validate cannot be combined with conversion options");
const auto documents = bmh::obw::read(validate_path);
if (documents.contains("x-classic/seal.json"))
bmh::content::verify(documents);
std::cout << "Valid OBW content: " << documents.size() << " entries; no engine runtime test implied.\n";
return 0;
}
if (source.empty() || destination.empty() || options.start_date.empty())
throw std::runtime_error("--data, --output and --start-date are required; see --help");
if (!directory && destination.extension() != ".obw")
throw std::runtime_error("archive output must use the .obw extension");
auto documents = bmh::obw::import_installation(source, options);
if (!options.database_only)
bmh::content::seal(documents);
bmh::obw::write(documents, destination, directory);
std::cout << "Converted " << documents.size() << " documents to "
<< bmh::launch::path_to_utf8(destination) << "\n"
<< "Profile: "
<< (options.database_only ? "legacy-database-v1 (partial)"
: "classic-installation-v1 (complete Classic content)")
<< "; content_license: local-import-only.\n"
<< "See manifest.json and x-legacy/import-report.json. Classic packages can be added to "
"the 0.2 portable mods directory.\n";
return 0;
} catch (const std::exception& error) {
std::cerr << "openbmh_import: " << error.what() << '\n';
return 1;
}
}
-699
View File
@@ -1,699 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/obw.hpp"
#include "import/classic.hpp"
#include "import/detail.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cctype>
#include <fstream>
#include <iomanip>
#include <set>
#include <sstream>
#include <string_view>
#include <stdexcept>
#include "formats/executable_layout.hpp"
#include "launch/archive.hpp"
#include "launch/fltd.hpp"
#include "launch/game_data.hpp"
#include "miniz.h"
#include "version.hpp"
namespace fs = std::filesystem;
namespace bmh::obw {
namespace {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
[[noreturn]] void fail(const std::string& message) { throw FormatError("OBW: " + message); }
std::string id(const std::string& type, size_t index) {
std::ostringstream out;
out << type << ':' << std::setfill('0') << std::setw(5) << index;
return out.str();
}
std::string hex(const Bytes& bytes) {
constexpr char digits[] = "0123456789abcdef";
std::string result;
result.reserve(bytes.size() * 2);
for (const auto byte : bytes) {
result += digits[byte >> 4];
result += digits[byte & 15];
}
return result;
}
// The documented ISO 646-DE substitutions, with the installation's extended
// Latin-1 bytes represented as Unicode as well. Raw bytes are preserved separately.
std::string text(const std::string& raw) {
std::string result;
for (const unsigned char byte : raw) {
if (byte >= 128) {
result += char(0xc0 | (byte >> 6));
result += char(0x80 | (byte & 63));
} else {
const char one[] = {char(byte), 0};
result += iso646de_to_utf8(one, 1);
}
}
return result;
}
bool named(const std::string& value) {
return std::any_of(value.begin(), value.end(), [](unsigned char ch) {
return std::isalnum(ch) || ch >= 128;
});
}
J localized(const std::string& value) { return O{{"default", value}}; }
J table(const std::string& schema, A items) {
return O{{"schema", schema + "@1.0"}, {"items", std::move(items)}};
}
void put(Documents& out, const std::string& path, J value) {
out.emplace(path, cli::dump_json(value) + '\n');
}
int start_year(const std::string& date) {
if (date.size() != 10 || date.substr(4) != "-07-01" ||
!std::all_of(date.begin(), date.begin() + 4, [](unsigned char c) { return c >= '0' && c <= '9'; }))
fail("start_date must be YYYY-07-01 (legacy season anchor)");
const int year = std::stoi(date.substr(0, 4));
if (year < 1900 || year > 9998) fail("start_date year must be between 1900 and 9998");
return year;
}
A bytes_at(const LeImage& exe, uint32_t address, size_t count) {
A result;
for (size_t i = 0; i < count; ++i) result.emplace_back(int(exe.u8(address + uint32_t(i))));
return result;
}
struct NationKey { std::string key, confederation; };
NationKey nation_key(const std::string& label, size_t index) {
// Generic geographic aliases, never an edition-dependent positional inventory.
// Unknown or renamed countries retain a private, documented source key.
std::string upper = label;
for (char& ch : upper) if (ch >= 'a' && ch <= 'z') ch = char(ch - 'a' + 'A');
static const std::map<std::string, std::string> aliases = {
{"DEUTSCHLAND", "de"}, {"GERMANY", "de"}, {"ENGLAND", "x-eng"},
{"SPANIEN", "es"}, {"SPAIN", "es"}, {"FRANKREICH", "fr"}, {"FRANCE", "fr"},
{"ITALIEN", "it"}, {"ITALY", "it"}, {"PORTUGAL", "pt"},
{"NIEDERLANDE", "nl"}, {"HOLLAND", "nl"}, {"NETHERLANDS", "nl"},
{"BELGIEN", "be"}, {"BELGIUM", "be"}, {"SCHOTTLAND", "x-sco"}, {"SCOTLAND", "x-sco"},
{"WALES", "x-wal"}, {"N.IRELAND", "x-nir"}, {"NORTHERN IRELAND", "x-nir"},
{"IRLAND", "ie"}, {"IRELAND", "ie"}, {"REP. OF IRELAND", "ie"},
{"ÖSTERREICH", "at"}, {"AUSTRIA", "at"}, {"SCHWEIZ", "ch"}, {"SWITZERLAND", "ch"},
{"DÄNEMARK", "dk"}, {"DENMARK", "dk"}, {"SCHWEDEN", "se"}, {"SWEDEN", "se"},
{"NORWEGEN", "no"}, {"NORWAY", "no"}, {"FINNLAND", "fi"}, {"FINLAND", "fi"},
{"POLEN", "pl"}, {"POLAND", "pl"}, {"TÜRKEI", "tr"}, {"TURKEY", "tr"},
{"RUSSLAND", "ru"}, {"RUSSIA", "ru"}, {"UKRAINE", "ua"},
{"TSCHECHIEN", "cz"}, {"TSCHECHEI", "cz"}, {"SLOWAKEI", "sk"}, {"SLOVAKIA", "sk"},
{"UNGARN", "hu"}, {"HUNGARY", "hu"}, {"RUMÄNIEN", "ro"}, {"ROMANIA", "ro"},
{"KROATIEN", "hr"}, {"CROATIA", "hr"}, {"BULGARIEN", "bg"}, {"BULGARIA", "bg"},
{"GRIECHENLAND", "gr"}, {"GREECE", "gr"}, {"SERBIEN", "rs"}, {"SERBIA", "rs"},
{"SLOWENIEN", "si"}, {"SLOVENIA", "si"}, {"BOSNIEN", "ba"}, {"BOSNIA", "ba"},
{"KOSOVO", "x-kos"}, {"LITHUANIA", "lt"}, {"LUXEMBURG", "lu"},
{"CYPRUS", "cy"}, {"MALTA", "mt"}, {"ISRAEL", "il"},
{"BRASILIEN", "br"}, {"BRASIL", "br"}, {"BRAZIL", "br"},
{"ARGENTINIEN", "ar"}, {"ARGENTINA", "ar"}, {"URUGUAY", "uy"}, {"PERU", "pe"},
{"CHILE", "cl"}, {"KOLUMBIEN", "co"}, {"COLUMBIA", "co"}, {"COLOMBIA", "co"},
{"BOLIVIEN", "bo"}, {"BOLIVIA", "bo"}, {"PARAGUAY", "py"},
{"VENEZUELA", "ve"}, {"ECUADOR", "ec"},
{"USA", "us"}, {"KANADA", "ca"}, {"CANADA", "ca"},
{"MEXIKO", "mx"}, {"MEXICO", "mx"}, {"PANAMA", "pa"},
{"AUSTRALIEN", "au"}, {"AUSTRALIA", "au"}, {"NEW ZEALAND", "nz"},
{"MAROKKO", "ma"}, {"MOROCCO", "ma"}, {"KAMERUN", "cm"}, {"CAMEROON", "cm"},
{"SENEGAL", "sn"}, {"NIGERIA", "ng"}, {"ALGERIEN", "dz"}, {"ALGERIA", "dz"},
{"TUNESIEN", "tn"}, {"TUNISIA", "tn"}, {"ÄGYPTEN", "eg"}, {"EGYPT", "eg"},
{"TOGO", "tg"}, {"GHANA", "gh"}, {"SÜDAFRIKA", "za"}, {"SÜDARFIKA", "za"},
{"SOUTH AFRICA", "za"}, {"ELFENBEINKÜSTE", "ci"},
{"IRAN", "ir"}, {"JAPAN", "jp"}, {"CHINA", "cn"},
{"SÜDKOREA", "kr"}, {"SOUTH KOREA", "kr"}, {"SAUDI ARABIEN", "sa"}, {"SAUDI ARABIA", "sa"},
{"INDONESIA", "id"}, {"LEBANON", "lb"}, {"IRAQ", "iq"}, {"KUWAIT", "kw"},
{"JORDAN", "jo"}, {"JORADAN", "jo"}, {"SYRIA", "sy"}
};
const auto found = aliases.find(upper);
if (found == aliases.end()) return {"x-legacy-" + std::to_string(index), "other"};
const std::string& key = found->second;
const std::set<std::string> south = {"br", "ar", "uy", "pe", "cl", "co", "bo", "py", "ve", "ec"};
const std::set<std::string> north = {"us", "ca", "mx", "pa"};
const std::set<std::string> africa = {"ma", "cm", "sn", "ng", "dz", "tn", "eg", "tg", "gh", "za", "ci"};
const std::set<std::string> asia = {"au", "ir", "jp", "cn", "kr", "sa", "id", "lb", "iq", "kw", "jo", "sy"};
return {key, south.contains(key) ? "conmebol" : north.contains(key) ? "concacaf" :
africa.contains(key) ? "caf" : asia.contains(key) ? "afc" : key == "nz" ? "ofc" : "uefa"};
}
std::string po_quote(const std::string& value) {
std::string result = "\"";
for (unsigned char ch : value) {
switch (ch) {
case '\\': result += "\\\\"; break;
case '"': result += "\\\""; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default:
if (ch < 32 || ch == 127) {
result += '\\';
result += char('0' + (ch >> 6));
result += char('0' + ((ch >> 3) & 7));
result += char('0' + (ch & 7));
} else result += char(ch);
}
}
return result + '"';
}
const J& field(const J& value, std::string_view key, std::string_view path) {
const auto* object = value.object();
if (!object || !object->contains(key)) fail(std::string(path) + ": missing " + std::string(key));
return object->find(key)->second;
}
std::string string_field(const J& value, const std::string& key, const std::string& path) {
const auto* result = field(value, key, path).string();
if (!result) fail(path + ": " + key + " must be a string");
return *result;
}
} // namespace
Documents convert_database(const Database& db, const TextDb& texts, const LeImage& exe,
bool english, const Options& options) {
start_year(options.start_date);
if (db.club_names.size() != 419 || db.players.size() != 2574 || db.squad_list.size() < 2928 * 2)
fail("unsupported database counts (expected 419 clubs, 2574 players and 2928 squad slots)");
if (texts.strings.size() != TEXT_COUNT) fail("incomplete text database");
const int expected[9] = {english ? 20 : 18, english ? 20 : 18, english ? 20 : 18,
english ? 20 : 18, english ? 10 : 18, 12, 12, 12, 12};
for (size_t i = 0; i < 9; ++i)
if (exe.u8(layout::LeagueSizes + uint32_t(i)) != expected[i])
fail("unsupported edition league sizes");
Documents out;
A warnings, nations, clubs, players, stadiums, competitions, rules, calendar;
std::array<std::string, 62> nation_ids;
std::set<std::string> used_nation_ids;
const std::string language = english ? "en" : "de";
for (size_t i = 0; i < nation_ids.size(); ++i) {
const auto label = text(db.club_names.at(357 + i));
auto key = nation_key(label, i);
if (!used_nation_ids.insert(key.key).second) {
key = {"x-legacy-" + std::to_string(i), "other"};
used_nation_ids.insert(key.key);
}
if (key.key.starts_with("x-legacy-"))
warnings.emplace_back("unresolved nation identity at legacy index " + std::to_string(i));
nation_ids[i] = "nation:" + key.key;
nations.emplace_back(O{{"id", nation_ids[i]}, {"name", localized(label)},
{"confederation", key.confederation}, {"playable", i < 5},
{"national_team", "nt:" + key.key}, {"x-legacy", O{{"nationality_index", int(i)}, {"team_index", int(357 + i)}}}});
}
nations.emplace_back(O{{"id", "nation:x-legacy-unassigned"},
{"name", localized("Unassigned legacy nation")}, {"confederation", "other"}, {"playable", false}});
std::vector<std::string> club_ids(419);
int league_first = 0;
std::array<std::string, 9> comp_ids;
for (int league = 0; league < 9; ++league) {
const int nation = league < 5 ? 0 : league - 4;
const int tier = league < 5 ? (english ? league + 1 : (league < 3 ? league + 1 : league)) : 1;
comp_ids[size_t(league)] = "comp:" + nation_ids[size_t(nation)].substr(7) + '-' + std::to_string(tier);
if (!english && league == 2) comp_ids[2] += "-a";
if (!english && league == 3) comp_ids[3] += "-b";
for (int team = league_first; team < league_first + expected[league]; ++team)
club_ids[size_t(team)] = id("club", size_t(team));
league_first += expected[league];
}
for (size_t team = 138; team < 357; ++team)
if (named(text(db.club_names[team]))) club_ids[team] = id("club", team);
for (size_t i = 0; i < nation_ids.size(); ++i) club_ids[357 + i] = "nt:" + nation_ids[i].substr(7);
for (size_t team = 0; team < club_ids.size(); ++team) {
if (club_ids[team].empty()) continue;
int league = -1, first = 0;
for (int l = 0; l < 9; ++l) {
if (int(team) >= first && int(team) < first + expected[l]) league = l;
first += expected[l];
}
const std::string type = team >= 357 ? "national" : team >= 168 ? "foreign" : team >= 138 ? "amateur" : "club";
const std::string nation = team >= 357 ? nation_ids[team - 357] : team >= 168 ?
"nation:x-legacy-unassigned" : nation_ids[league >= 5 ? size_t(league - 4) : 0];
O row{{"id", club_ids[team]}, {"type", type}, {"name", localized(text(db.club_names[team]))}, {"nation", nation},
{"x-legacy", O{{"team_index", int(team)}, {"badge_word", int(le16(db.raw_club_badge_selectors, team * 2))},
{"kit_selector", int(db.raw_club_kit_selectors.at(team))}}}};
// This byte encodes a strength band and style flags, not a 0..99 rating.
if (team >= 168) row.at("x-legacy").object()->emplace("strength_code", int(db.raw_foreign_club_strength.at(team - 168)));
clubs.emplace_back(std::move(row));
}
std::vector<int> player_team(db.players.size(), -1);
std::vector<int> player_row(db.players.size(), -1);
for (int team = 0; team < 138; ++team) {
const size_t first = team < 90 ? size_t(team) * 24 : size_t(team) * 16 + 720;
const size_t count = team < 90 ? 24 : 16;
for (size_t row = 0; row < count; ++row) {
const auto word = le16(db.squad_list, (first + row) * 2);
const size_t player = word & 4095;
if (player == 4095) continue;
if (player >= db.players.size()) fail("squad slot references an unknown player");
if (player_team[player] >= 0) fail("player occurs in more than one squad slot");
player_team[player] = team;
player_row[player] = int(row);
}
}
constexpr const char* positions[] = {"gk", "def", "mid", "fwd"};
constexpr const char* skills[] = {"teamplay", "speed", "shooting", "passing", "tackling", "free_kick", "corner"};
for (size_t i = 0; i < db.players.size(); ++i) {
const auto& player = db.players[i];
int nationality = player.nationality() + ((db.raw_player_bonus_values.at(i) & 128) ? 32 : 0);
// Import the source record, not career initialization's nationality
// rewrites and random ratings. The original words remain in x-legacy.
if (nationality < 0 || size_t(nationality) >= nation_ids.size())
fail("player " + std::to_string(i) + " nationality " + std::to_string(nationality) + " is outside the nation table");
O attributes{{"form", player.form()}, {"technique", player.technique()}, {"condition", player.condition()},
{"strength", player.strength()}, {"bonus", int(db.raw_player_bonus_values.at(i) & 127)}};
for (int skill = 0; skill < 7; ++skill) attributes[skills[skill]] = player.skill(Player::Skill(skill));
O row{{"id", id("player", i)}, {"name", O{{"first", ""}, {"last", text(player.name)}}},
{"age_at_start", O{{"years", player.age()}, {"on", options.start_date}}},
{"nationalities", A{nation_ids[size_t(nationality)]}}, {"positions", A{positions[player.position()]}},
{"attribute_set", "bmh-classic@1"}, {"attributes", std::move(attributes)},
{"x-legacy", O{{"player_index", int(i)}, {"condition_technique_form_word", J(int64_t(player.w35c))},
{"skill_word", J(int64_t(player.w368))}, {"identity_word", J(int64_t(player.w364))},
{"squad_row", player_row[i]}}}};
if (player_team[i] >= 0) row["team"] = club_ids[size_t(player_team[i])];
players.emplace_back(std::move(row));
}
for (size_t i = 0; i < db.stadiums.size(); ++i)
stadiums.emplace_back(O{{"id", id("stadium", i)}, {"name", localized(text(db.stadiums[i]))},
{"x-legacy", O{{"name_pool_index", int(i)}}}});
A fixture_tables;
const std::vector<std::pair<int, uint32_t>> bindings = english ?
std::vector<std::pair<int, uint32_t>>{{4, layout::EnglishFourTeamFixtureTable}, {6, layout::EnglishSixTeamFixtureTable},
{12, layout::EnglishTwelveTeamFixtureTable}, {20, layout::EnglishTwentyTeamFixtureTable}} :
std::vector<std::pair<int, uint32_t>>{{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}};
for (const auto& [teams, address] : bindings) {
A rounds;
for (int round = 1; round < teams; ++round) {
const auto source = exe.cstring(exe.u32(address + uint32_t(round * 4)));
if (source.size() != size_t(teams)) fail("fixture table has an invalid round length");
std::set<char> seen;
A pairs;
for (const char ch : source)
if (ch < 'a' || ch >= 'a' + teams || !seen.insert(ch).second) fail("fixture round has an invalid team");
for (size_t i = 0; i < source.size(); i += 2) pairs.emplace_back(A{int(source[i] - 'a'), int(source[i + 1] - 'a')});
rounds.emplace_back(std::move(pairs));
}
fixture_tables.emplace_back(O{{"id", "legacy:" + std::to_string(teams)}, {"teams", teams}, {"rounds", std::move(rounds)}});
}
A series;
int first = 0, label_index = 0;
for (size_t league = 0; league < 9; ++league) {
const int teams = expected[league];
A members;
for (int t = first; t < first + teams; ++t) members.emplace_back(club_ids[size_t(t)]);
const auto bit = exe.u8(layout::LeagueCalendarBits + uint32_t(league));
const bool played = !(english && league == 4);
const auto series_id = "legacy-league-" + std::to_string(league);
std::string label;
if (league < 5) {
const auto label_slot = (layout::Achievements_FormatError_TextPointer3 - layout::TextPointerTable) / 4 + uint32_t(label_index);
label = text(texts.strings.at(label_slot));
const char suffix = char(exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField3 + uint32_t(league * 2)));
if (suffix) label += std::string(" ") + suffix;
if (league == 4 || exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField3 + uint32_t((league + 1) * 2)) < 'B') ++label_index;
} else label = text(db.club_names[357 + league - 4]);
O stage{{"id", "regular"}, {"format", "league"}, {"teams", teams}, {"legs", 2},
{"generator", "legacy:" + std::to_string(teams)}, {"slots", A{O{{"teams", std::move(members)}}}}};
// The unplayed English pool has no ten-team legacy fixture generator.
if (played) stage["matchdays"] = "calendar:" + series_id;
else stage.erase("generator");
const auto nation = league < 5 ? nation_ids[0] : nation_ids[league - 4];
const int tier = league < 5 ? (english ? int(league + 1) : (league < 3 ? int(league + 1) : int(league))) : 1;
competitions.emplace_back(O{{"id", comp_ids[league]}, {"name", localized(label)}, {"type", "league"},
{"trophy", "asset:comp/" + comp_ids[league].substr(5) + "/trophy"},
{"nation", nation}, {"tier", tier}, {"played", played}, {"stages", A{std::move(stage)}},
{"x-legacy", O{{"league_index", int(league)}, {"calendar_bit", int(bit)},
{"relegation_places", int(exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField2 + uint32_t(league)))},
{"europe_places", int(exe.u8(layout::CareerSession_InstallLeagueSizes_RuntimeField + uint32_t(league)))}}}});
if (played) series.emplace_back(O{{"id", series_id}, {"legacy_calendar_bit", int(bit)}});
first += teams;
}
O attribute_fields;
for (const char* attribute : {"form", "technique", "condition"})
attribute_fields[attribute] = O{{"min", 0}, {"max", 127}};
attribute_fields["strength"] = O{{"min", 0}, {"max", 99}, {"derived", true}};
attribute_fields["bonus"] = O{{"min", 0}, {"max", 127}};
for (const char* skill : skills) attribute_fields[skill] = O{{"min", 0}, {"max", 3}};
rules.emplace_back(O{{"id", "bmh-classic@1"}, {"type", "attribute_set"}, {"fields", std::move(attribute_fields)}});
rules.emplace_back(O{{"id", "rule:legacy-fixtures"}, {"type", "fixture_tables"}, {"tables", std::move(fixture_tables)}});
rules.emplace_back(O{{"id", "rule:legacy-ladder"}, {"type", "legacy_ladder"},
{"first_league", bytes_at(exe, layout::CalendarFirstLeague, 8)},
{"league_count", bytes_at(exe, layout::CalendarLeagueCounts, 8)},
{"below", bytes_at(exe, layout::CareerSession_InstallLeagueSizes_RuntimeField5, 8)},
{"below_count", bytes_at(exe, layout::CareerSession_InstallLeagueSizes_RuntimeField4, 8)},
{"newcomer_first", int(exe.u16(layout::CareerSession_DispatchLineup_RuntimeField))},
{"newcomer_count", int(exe.u16(layout::CareerSession_InstallLeagueSizes_RuntimeField6))}});
A resorts;
for (uint32_t resort = 0; resort < 8; ++resort)
resorts.emplace_back(O{{"id", "resort:" + std::to_string(resort)},
{"base_price", J(int64_t(int32_t(exe.u32(layout::DeskActions_ConfigureTrainingCampData_RuntimeField2 + resort * 4))))},
{"quality", bytes_at(exe, layout::DeskActions_ConfigureTrainingCampData_RuntimeField + resort * 4, 4)}});
rules.emplace_back(O{{"id", "rule:training-camps"}, {"type", "training_camps"}, {"resorts", std::move(resorts)}});
// Retain the floating-point divisor as IEEE-754 bytes, not a rounded money value.
rules.emplace_back(O{{"id", "rule:credit-rates"}, {"type", "credit_rates"},
{"factors", bytes_at(exe, layout::BankCredit_BankCreditContext_RuntimeField3, 49)},
{"x-legacy-divisor-low", J(int64_t(exe.u32(layout::BankCredit_BankCreditContext_RuntimeField)))},
{"x-legacy-divisor-high", J(int64_t(exe.u32(layout::BankCredit_BankCreditContext_RuntimeField2)))}});
A day_words;
for (uint32_t day = 0; day < 366; ++day) day_words.emplace_back(int(exe.u16(layout::CompetitionCalendar + day * 2)));
calendar.emplace_back(O{{"id", "calendar:legacy-season"}, {"season_start", "07-01"},
{"series", std::move(series)}, {"x-legacy", O{{"day_words", std::move(day_words)},
{"note", "Source day offsets, not final dated fixtures; career setup applies competition and weekday options."}}}});
const auto currency_suffix = exe.cstring(layout::CurrencySuffixText);
const std::string currency = english ? "GBP" : currency_suffix == " DM" ? "DEM" : currency_suffix == " EU" ? "EUR" : "X-LEGACY";
put(out, "manifest.json", O{{"format", "openbmh-world"}, {"format_version", "1.0"}, {"kind", "world"},
{"min_reader", "1.0"}, {"generator", std::string("OpenBMH importer ") + kOpenBmhVersion},
{"title", localized(options.title)}, {"provenance", english ? "import:fltd" : "import:bmh-de"},
{"content_license", "local-import-only"}, {"currency", O{{"code", currency}, {"minor_units", 0}, {"x-legacy-suffix", text(currency_suffix)}}},
{"start_date", options.start_date}, {"languages", A{language}}, {"limits", O{{"leagues", 32}}},
{"requires", A{"import:legacy-database-v1"}}, {"extensions", A{O{{"id", "x-legacy"}, {"version", "1.0"}}}},
{"x-import", O{{"profile", "legacy-database-v1"}, {"playable", false},
{"rule_profile", "openbmh-supported"}, {"default_attribute_set", "bmh-classic@1"}}}});
put(out, "world/nations.json", table("nations", std::move(nations)));
put(out, "world/clubs.json", table("clubs", std::move(clubs)));
put(out, "world/players.json", table("players", std::move(players)));
put(out, "world/stadiums.json", table("stadiums", std::move(stadiums)));
for (const char* empty : {"staff", "contracts", "finance"})
put(out, std::string("world/") + empty + ".json", table(empty, {}));
put(out, "world/competitions.json", table("competitions", std::move(competitions)));
put(out, "world/rules.json", table("rules", std::move(rules)));
put(out, "world/calendar.json", table("calendar", std::move(calendar)));
O raw_tables;
const std::pair<const char*, const Bytes*> raw[] = {
{"player_bonus_values", &db.raw_player_bonus_values}, {"database_metadata", &db.raw_database_metadata},
{"club_auxiliary_words", &db.raw_club_auxiliary_words}, {"club_badge_selectors", &db.raw_club_badge_selectors},
{"foreign_club_strength", &db.raw_foreign_club_strength}, {"league_auxiliary_bytes", &db.raw_league_auxiliary_bytes},
{"referee_properties", &db.raw_referee_properties}, {"club_kit_selectors", &db.raw_club_kit_selectors},
{"club_short_name_offsets", &db.raw_club_short_name_offsets}, {"club_name_offsets", &db.raw_club_name_offsets},
{"player_name_offsets", &db.raw_player_name_offsets}, {"squad_list", &db.squad_list}};
for (const auto& [name, data] : raw) raw_tables[name] = hex(*data);
A pools;
for (const auto& pool : db.pools) pools.emplace_back(hex(pool));
put(out, "x-legacy/database.json", O{{"schema", "legacy-database@1.0"}, {"encoding", "hex"},
{"counts", O{{"clubs", 419}, {"players", 2574}, {"n42", 168}, {"n66", 3096}}},
{"pools", std::move(pools)}, {"tables", std::move(raw_tables)}});
A original_texts;
std::string po = "# Local installation import; not licensed for redistribution.\nmsgid \"\"\nmsgstr \"\"\n"
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n\"Language: " + language + "\\n\"\n";
for (size_t i = 0; i < texts.strings.size(); ++i) {
original_texts.emplace_back(O{{"index", int(i)}, {"text", text(texts.strings[i])},
{"raw_hex", hex(Bytes(texts.strings[i].begin(), texts.strings[i].end()))}});
po += "\nmsgctxt \"legacy-text\"\nmsgid \"legacy.text." + std::to_string(i) + "\"\nmsgstr " + po_quote(text(texts.strings[i])) + '\n';
}
put(out, "x-legacy/texts.json", table("legacy-texts", std::move(original_texts)));
out["locale/" + language + "-original/openbmh.po"] = std::move(po);
warnings.emplace_back("foreign club nation assignments remain unresolved outside the four simulated foreign leagues");
put(out, "x-legacy/import-report.json", O{{"schema", "legacy-import-report@1.0"},
{"profile", "legacy-database-v1"}, {"warnings", std::move(warnings)},
{"unmapped", A{"staff and referee roles", "stadium capacities/owners", "contracts and finances",
"cup definitions and qualification", "dated calendar/competition options", "complete executable rule tables",
"foreign strength-band interpretation", "career initialization transforms", "graphics/assets"}},
{"notes", A{"Database attributes are seeds: legacy career initialization varies player ratings.",
"No career was started and no random numbers were consumed.",
"Executable tables use the existing OpenBMH loader and its supported rule profile, not an unmodified executable dump.",
"Source ages are retained without inventing exact birthdays; reference date is supplied by the user."}}});
validate(out);
return out;
}
Documents import_installation(const fs::path& source, const Options& options) {
if (!fs::exists(source)) fail("source does not exist");
if (!fs::is_directory(source)) {
auto filename = launch::path_to_utf8(source.filename());
for (char& ch : filename) ch = char(std::toupper(static_cast<unsigned char>(ch)));
if (filename != "BMH.EXE" && filename != "FLTD.EXE") fail("source must be a directory, BMH.EXE or FLTD.EXE; FBM conversion is not implemented");
}
fs::path root = fs::is_directory(source) ? source : source.parent_path();
auto german = launch::find_file(root, "BMH.EXE"), english_exe = launch::find_file(root, "FLTD.EXE");
if (!german && !english_exe && fs::is_directory(root)) {
std::vector<fs::path> candidates;
for (const auto& entry : fs::directory_iterator(root))
if (entry.is_directory() && (launch::find_file(entry.path(), "BMH.EXE") || launch::find_file(entry.path(), "FLTD.EXE")))
candidates.push_back(entry.path());
if (candidates.size() != 1) fail("expected exactly one BMH.EXE or FLTD.EXE installation");
root = candidates[0];
german = launch::find_file(root, "BMH.EXE");
english_exe = launch::find_file(root, "FLTD.EXE");
}
if (!german && !english_exe) fail("no BMH.EXE or FLTD.EXE found");
bool english = bool(english_exe) && !german;
if (german && english_exe) {
if (fs::is_directory(source)) fail("ambiguous installation: name BMH.EXE or FLTD.EXE explicitly");
if (fs::equivalent(source, *english_exe)) english = true;
else if (!fs::equivalent(source, *german)) fail("name BMH.EXE or FLTD.EXE explicitly");
}
const auto required = [&](const std::string& name) {
const auto file = launch::find_file(root, name);
if (!file || !fs::is_regular_file(*file)) fail("missing " + name);
return *file;
};
const auto exe = english ? launch::translate_fltd(*english_exe) : load_le(*german);
const std::string expected_mod = english ? "FLTD-classic" : "BMH-classic";
if (!options.mod.empty() && options.mod != expected_mod) fail("--mod must be " + expected_mod + " for this installation");
if (!options.database_only) {
const auto checked = launch::check_game_directory(english ? *english_exe : *german);
if (!checked.problems.empty()) {
std::string problem = "incomplete installation";
for (const auto& message : checked.problems) problem += "\n- " + message;
fail(problem + "\nUse --database-only only for an explicitly partial development export.");
}
}
const auto db_path = required(english ? "M3E.MAN" : "M3D.MAN");
const auto text_path = required(english ? "TEXTE.BLK" : "TEXTD.BLK");
const auto database = load_database(db_path);
auto out = convert_database(database, load_textd(text_path), exe, english, options);
// Exact source database for lossless future re-mapping, not an executable or a
// runnable legacy installation. No absolute developer paths enter the archive.
put(out, "x-legacy/source-database.json", O{{"schema", "legacy-source@1.0"},
{"name", english ? "M3E.MAN" : "M3D.MAN"}, {"encoding", "hex"}, {"bytes", hex(read_file(db_path))}});
if (!options.database_only) {
const auto source_tables = english ? launch::translate_fltd(*english_exe, false) : load_le(*german, false);
complete_classic(out, root, database, exe, source_tables, english, options);
}
validate(out);
return out;
}
void validate(const Documents& documents) {
const auto parse = [&](const std::string& path) {
const auto found = documents.find(path);
if (found == documents.end()) fail(path + ": missing document");
return cli::parse_json(found->second);
};
const auto manifest = parse("manifest.json");
for (const auto& [key, expected] : std::vector<std::pair<std::string, std::string>>{
{"format", "openbmh-world"}, {"format_version", "1.0"}, {"kind", "world"}, {"content_license", "local-import-only"}})
if (string_field(manifest, key, "manifest.json") != expected) fail("manifest.json: unsupported " + key);
start_year(string_field(manifest, "start_date", "manifest.json"));
uint64_t total = 0;
if (documents.size() > 8192) fail("world has too many entries");
for (const auto& [path, contents] : documents) {
total += contents.size();
if (contents.size() > 32 * 1024 * 1024 || total > 128ull * 1024 * 1024) fail("world exceeds import size limits");
if (!detail::safe_path(path)) fail("unsafe archive path: " + path);
}
const auto& features = field(manifest, "requires", "manifest.json");
const auto& profile = field(manifest, "x-import", "manifest.json");
const bool classic = string_field(profile, "profile", "manifest.json:x-import") == "classic-installation-v1";
if (classic) validate_classic(documents);
else {
if (!features.array() || features.array()->size() != 1 || !features.array()->front().string() ||
*features.array()->front().string() != "import:legacy-database-v1") fail("manifest.json: missing conversion-only feature guard");
const auto* playable = field(profile, "playable", "manifest.json:x-import").boolean();
if (!playable || *playable || string_field(profile, "profile", "manifest.json:x-import") != "legacy-database-v1")
fail("manifest.json: conversion profile must remain non-playable");
}
std::map<std::string, std::string> ids;
struct Reference { std::string value, prefix, path; };
std::vector<Reference> references;
for (const char* name : {"nations", "clubs", "players", "staff", "stadiums", "contracts", "finance", "competitions", "rules", "calendar"}) {
const std::string path = std::string("world/") + name + ".json";
const auto data = parse(path);
if (string_field(data, "schema", path) != std::string(name) + "@1.0") fail(path + ": unsupported schema");
const auto* items = field(data, "items", path).array();
if (!items) fail(path + ": items must be an array");
for (size_t i = 0; i < items->size(); ++i) {
const auto& item = items->at(i);
const auto at = path + ":items[" + std::to_string(i) + ']';
const auto entity_id = string_field(item, "id", at);
if (!ids.emplace(entity_id, name).second) fail(at + ": duplicate id " + entity_id);
const std::map<std::string, std::string> prefixes{{"nations", "nation:"}, {"players", "player:"},
{"staff", "staff:"}, {"stadiums", "stadium:"}, {"contracts", "contract:"},
{"finance", "finance:"}, {"competitions", "comp:"}, {"calendar", "calendar:"}};
if (const auto prefix = prefixes.find(name); prefix != prefixes.end() && !entity_id.starts_with(prefix->second))
fail(at + ": wrong id type " + entity_id);
if (std::string(name) == "clubs" && !entity_id.starts_with("club:") && !entity_id.starts_with("nt:"))
fail(at + ": wrong team id type " + entity_id);
const auto ref = [&](const std::string& key, const std::string& prefix) {
if (item.object()->contains(key)) references.push_back({string_field(item, key, at), prefix, at + '.' + key});
};
ref("nation", "nation:"); ref("team", "club:"); ref("stadium", "stadium:"); ref("national_team", "nt:");
if (std::string(name) == "contracts") ref("person", "player:");
if (std::string(name) == "players") {
const auto* nats = field(item, "nationalities", at).array();
if (!nats || nats->empty()) fail(at + ": nationalities must not be empty");
for (const auto& nat : *nats) {
if (!nat.string()) fail(at + ": invalid nationality");
references.push_back({*nat.string(), "nation:", at + ".nationalities"});
}
if (string_field(item, "attribute_set", at) != "bmh-classic@1") fail(at + ": invalid attribute set");
const auto& attributes = field(item, "attributes", at);
if (!attributes.object()) fail(at + ": attributes must be an object");
for (const auto& [attribute, value] : *attributes.object()) {
const auto* number = value.integer();
const int maximum = attribute == "strength" ? 99 :
(attribute == "form" || attribute == "technique" || attribute == "condition" || attribute == "bonus") ? 127 : 3;
if (!number || *number < 0 || *number > maximum) fail(at + ".attributes." + attribute + ": outside classic scale");
}
}
if (std::string(name) == "competitions") {
// Presentation references may be supplied by a later content pack.
// Missing assets use the documented generic trophy fallback.
if (item.object()->contains("trophy")) {
const auto key = string_field(item, "trophy", at);
constexpr std::string_view prefix = "asset:comp/", suffix = "/trophy";
if (!key.starts_with(prefix) || !key.ends_with(suffix) ||
key.size() <= prefix.size() + suffix.size()) fail(at + ": invalid trophy asset key");
const auto name = key.substr(prefix.size(), key.size() - prefix.size() - suffix.size());
if (!std::all_of(name.begin(), name.end(), [](unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-';
}) || name == "." || name == "..") fail(at + ": invalid trophy asset key");
}
const auto* stages = field(item, "stages", at).array();
if (!stages) fail(at + ": stages must be an array");
for (const auto& stage : *stages) {
const auto* slots = field(stage, "slots", at).array();
if (!slots) fail(at + ": slots must be an array");
size_t participants = 0;
std::set<std::string> unique_teams;
for (const auto& slot : *slots) {
if (classic && slot.object() && slot.object()->contains("resolver")) {
if (string_field(slot, "resolver", at) != "classic-entry@1") fail(at + ": unknown slot resolver");
const auto* count = field(slot, "count", at).integer();
if (!count || *count < 0 || *count > 255) fail(at + ": invalid classic slot count");
participants += size_t(*count);
continue;
}
const auto* teams = field(slot, "teams", at).array();
if (!teams) fail(at + ": slot teams must be an array");
for (const auto& team : *teams) {
if (!team.string()) fail(at + ": invalid slot team");
if (!unique_teams.insert(*team.string()).second) fail(at + ": duplicate stage participant");
references.push_back({*team.string(), "club:", at + ".stages.slots"});
}
participants += teams->size();
}
const auto* count = field(stage, "teams", at).integer();
if (!count || *count != int64_t(participants)) fail(at + ": stage team count disagrees with slots");
}
}
}
}
for (const auto& ref : references)
if (!ids.contains(ref.value) || !ref.value.starts_with(ref.prefix)) fail(ref.path + ": unknown or wrong-type id " + ref.value);
}
Documents read(const fs::path& source) {
Documents result;
uint64_t total = 0;
const auto add = [&](const std::string& name, const Bytes& bytes) {
if (!detail::safe_path(name)) fail("unsafe archive entry: " + name);
total += bytes.size();
if (total > 128ull * 1024 * 1024 || result.size() >= 8192) fail("world exceeds import size limits");
if (!result.emplace(name, detail::binary(bytes)).second) fail("duplicate archive entry: " + name);
};
if (fs::is_directory(source)) {
for (const auto& entry : fs::recursive_directory_iterator(source)) {
if (entry.is_symlink()) fail("symlinks are forbidden in an unpacked world");
if (!entry.is_regular_file()) continue;
if (entry.file_size() > 32 * 1024 * 1024 || total + entry.file_size() > 128ull * 1024 * 1024) fail("world exceeds import size limits");
const auto name = entry.path().lexically_relative(source).generic_u8string();
add(std::string(name.begin(), name.end()), read_file(entry.path()));
}
} else {
if (fs::file_size(source) > 128ull * 1024 * 1024) fail("world archive is too large");
auto archive = launch::Archive::open(source);
for (size_t i = 0; i < archive.entries().size(); ++i) {
const auto& entry = archive.entries()[i];
if (entry.directory) continue;
if (entry.size > 32 * 1024 * 1024 || total + entry.size > 128ull * 1024 * 1024) fail("world exceeds import size limits");
add(entry.name, archive.read(i));
}
}
validate(result);
return result;
}
void write(const Documents& documents, const fs::path& destination, bool directory) {
validate(documents);
if (fs::symlink_status(destination).type() != fs::file_type::not_found) fail("destination already exists");
const auto parent = destination.has_parent_path() ? destination.parent_path() : fs::path(".");
if (!fs::is_directory(parent)) fail("output parent directory does not exist");
fs::path staging;
for (int attempt = 0; attempt < 100; ++attempt) {
staging = parent / (".openbmh-import-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + '-' + std::to_string(attempt));
if (fs::create_directory(staging)) break;
staging.clear();
}
if (staging.empty()) fail("cannot reserve output staging directory");
struct Cleanup {
fs::path path;
~Cleanup() { std::error_code ec; fs::remove_all(path, ec); }
} cleanup{staging};
mz_zip_archive zip{};
if (!directory && !mz_zip_writer_init_heap(&zip, 0, 0)) fail("cannot initialize ZIP writer");
struct ZipCleanup { mz_zip_archive* zip; ~ZipCleanup() { if (zip) mz_zip_writer_end(zip); } } zip_cleanup{directory ? nullptr : &zip};
for (const auto& [name, contents] : documents) {
const fs::path relative = launch::path_from_utf8(name);
if (relative.empty() || relative.is_absolute() || relative.has_root_name() || name.find('\\') != std::string::npos)
fail("unsafe document path");
for (const auto& part : relative) if (part == ".." || part == ".") fail("unsafe document path");
if (directory) {
const auto file = staging / relative;
fs::create_directories(file.parent_path());
std::ofstream stream(file, std::ios::binary);
stream.write(contents.data(), std::streamsize(contents.size()));
stream.close();
if (!stream) fail("cannot write document " + name);
} else if (!mz_zip_writer_add_mem(&zip, name.c_str(), contents.data(), contents.size(), MZ_BEST_COMPRESSION))
fail("cannot add ZIP document " + name);
}
if (!directory) {
void* buffer = nullptr;
size_t size = 0;
if (!mz_zip_writer_finalize_heap_archive(&zip, &buffer, &size)) fail("cannot finish ZIP archive");
struct Free { void* value; ~Free() { mz_free(value); } } free{buffer};
std::ofstream stream(staging / "world.obw", std::ios::binary);
stream.write(static_cast<const char*>(buffer), std::streamsize(size));
stream.close();
if (!stream) fail("cannot write ZIP archive");
}
if (fs::symlink_status(destination).type() != fs::file_type::not_found) fail("destination appeared during conversion");
fs::rename(directory ? staging : staging / "world.obw", destination);
}
} // namespace bmh::obw
-41
View File
@@ -1,41 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <map>
#include <string>
#include "cli/json.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/textd.hpp"
namespace bmh::obw {
// An archive entry, deliberately independent of GameState and CareerSession.
// Keys are relative, authored paths; strings are binary-safe (including NUL).
using Documents = std::map<std::string, std::string>;
struct Options {
std::string start_date; // Required: legacy databases have ages, not birth dates.
std::string title = "Imported legacy world";
// Empty selects BMH-classic / FLTD-classic from the installation.
std::string mod;
// Explicit developer-only partial export; the default requires a complete installation.
bool database_only = false;
};
Documents convert_database(const Database& database, const TextDb& texts,
const LeImage& executable, bool english, const Options& options);
Documents import_installation(const std::filesystem::path& source, const Options& options);
// Checks the declared import profile, references and (for Classic) complete payload.
// This is not a generic competition engine or a JSON Schema implementation.
void validate(const Documents& documents);
Documents read(const std::filesystem::path& source);
// Refuses existing destinations. Publishes a complete sibling staging path by rename.
// No files in the installation are changed, copied back or executed.
void write(const Documents& documents, const std::filesystem::path& destination, bool directory);
} // namespace bmh::obw
-207
View File
@@ -1,207 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/save.hpp"
#include "formats/executable_layout.hpp"
#include "game/career.hpp"
#include <algorithm>
#include <map>
namespace bmh::obw {
namespace {
struct Record {
int target;
uint32_t native_address;
size_t size;
};
} // namespace
Bytes normalize_english_save(const Savegame &source, const DbCounts &counts) {
if (source.version != "V2.20" || !source.checksum_ok)
throw FormatError("Invalid Football Limited V2.20 save");
const auto layout = save_layout(counts, true);
const Record records[] = {
{0, 0, 0}, // Cup_AdvanceCup_RuntimeField3
{1, 0, 0}, // LiveMatchday_FormatError_RuntimeField14
{2, 0, 0}, // ManagerRecords
{3, 0, 0}, // Loans
{4, 0, 0}, // ManagerMatchHistory
{6, 0, 0}, // ManagerAutomation
{7, 0, 0}, // Desktops
{8, 0, 0}, // CareerSession_DispatchToto_RuntimeField
{10, 0, 0}, // CalendarState_FormatError_RuntimeField3
{11, 0, 0}, // ActiveManager
{12, 0, 0}, // CareerSession_RuntimeError_RuntimeField4
{13, 0, 0}, // LeaguePresentationOptions
{14, 0, 0}, // FriendlyTeams
{15, 0, 0}, // FriendlyDays
{16, 0, 0}, // Cup_AdvanceCup_ExecutableField
{17, 0, 0}, // MatchdaySetup_IndoorTournamentDraw_RuntimeField
{18, 0, 0}, // Placements
{19, 0, 0}, // ActiveSelectors
{20, 0, 0}, // Career_CareerAddManager_RuntimeField2
{21, 0, 0}, // DeskActions_SubmitPoolsCoupon_RuntimeField
{22, 0, 0}, // NextDeskManager
{23, 0, 0}, // Savestate_Layout_ExecutableField8
{24, 0, 0}, // DeskPosition
{25, 0, 0}, // DeskRecords_Teams_RuntimeField
{26, 0, 0}, // CareerSession_FormatError_RuntimeField7
{27, 0, 0}, // Cup_AdvanceCup_RuntimeField6
{28, 0, 0}, // CurrentMatchday
{29, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField3
{30, 0, 0}, // CoachActive
{31, 0, 0}, // OriginalManagerCount
{32, 0, 0}, // CareerSession_Invalid_RuntimeField2
{33, 0, 0}, // CareerDuration
{34, 0, 0}, // GameMode
{35, 0, 0}, // CompetitionSelection
{36, 0, 0}, // ManagerCount
{37, 0, 0}, // SavedCompetition
{38, 0, 0}, // Difficulty
{39, 0, 0}, // StockExchange
{40, 0, 0}, // FundBlock
{41, 0, 0}, // Coupon
{42, 0, 0}, // Savestate_Layout_ExecutableField2
{43, 0, 0}, // Savestate_Layout_ExecutableField
{44, 0, 0}, // AdGroupId
{45, 0, 0}, // OfferSlots
{46, 0, 0}, // ForeignClubStrength
{47, 0, 0}, // Career_Put_ExecutableField3
{48, 0, 0}, // ClubShortNameOffsets
{49, 0, 0}, // ClubKitSelectors
{50, 0, 0}, // Savestate_Layout_ExecutableField7
{51, 0, 0}, // ClubInfo_FormatError_RuntimeField
{52, 0, 0}, // Career_CareerManagersEnd_RuntimeField
{53, 0, 0}, // ClubInfo_FormatError_RuntimeField2
{54, 0, 0}, // DeskActions_Unsupported_RuntimeField
{55, 0, 0}, // Career_RemoveJoinLoans_RuntimeField
{56, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField
{57, 0, 0}, // ManagerRatings
{58, 0, 0}, // DaysIntoSeason
{-1, ::bmh::layout::EnglishFaCupResults, 0x86}, // fa_results
{-1, ::bmh::layout::EnglishLeagueCupFirstRoundResults, 0x56}, // league_results
{-1, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults, 0x3c}, // league_return
{-1, ::bmh::layout::EnglishLeagueCupField, 0xa4}, // league_field
{-1, ::bmh::layout::EnglishFaCupField, 0x134}, // fa_field
{61, 0, 0}, // CalendarDay
{62, 0, 0}, // SeasonIndex
{63, 0, 0}, // Savestate_Layout_ExecutableField5
{64, 0, 0}, // CompetitionCalendar
{65, 0, 0}, // Postponed
{66, 0, 0}, // LeagueTableDisplayModes
{67, 0, 0}, // CareerSession_FormatError_ExecutableField
{68, 0, 0}, // ManagerSettings
{69, 0, 0}, // CareerSession_DispatchOtherGames_RuntimeField
{70, 0, 0}, // CareerSession_AnyOf_ExecutableField
{71, 0, 0}, // Career_NewCareerMarketsAndMoods_RuntimeField2
{72, 0, 0}, // ManagerMailbox
{73, 0, 0}, // CareerSession_CloseLeagueFamily_ExecutableField
{74, 0, 0}, // Savestate_Layout_ExecutableField3
{75, 0, 0}, // Flags
{76, 0, 0}, // Formations
{77, 0, 0}, // PlayerDevelopmentBalance
{78, 0, 0}, // PlayerBonuses
{79, 0, 0}, // EditorList
{80, 0, 0}, // Field0
{81, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField13
{82, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField25
{83, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField22
{84, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField23
{85, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField19
{86, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField26
{87, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField21
{88, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField14
{89, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField17
{90, 0, 0}, // Savestate_Layout_ExecutableField4
{91, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField28
{92, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField31
{93, 0, 0}, // Teams
{94, 0, 0}, // MatchdayGroupWorkspace
{95, 0, 0}, // Savestate_Layout_ExecutableField6
{96, 0, 0}, // EventPasses
{97, 0, 0}, // LeagueResults
{98, 0, 0}, // LeagueRoundCounters
{99, 0, 0}, // TeamMorale
{100, 0, 0}, // ClubBadgeSelectors
{101, 0, 0}, // TeamFlags
{102, 0, 0}, // ClubIdentities
{103, 0, 0}, // PlayerNameOffsets
{104, 0, 0}, // MasterDatabaseMetadata
{105, 0, 0}, // ClubAuxiliaryWords
{106, 0, 0}, // LeagueRankHistory
{107, 0, 0}, // Titles
{108, 0, 0}, // Cup_AdvanceCup_RuntimeField6
{109, 0, 0}, // ClubAuxiliaryBytes
{110, 0, 0}, // CupTable
{111, 0, 0}, // SquadSlots
{112, 0, 0}, // PlayerConditionTechniqueForm
{113, 0, 0}, // PlayerCards
{114, 0, 0}, // PlayerSkillWords
{115, 0, 0}, // PlayerIdentityWords
{116, 0, 0}, // TacticsBoards
{117, 0, 0}, // TournamentName
{118, 0, 0}, // Career_EuropeanClub_ExecutableField
{119, 0, 0}, // Career_EuropeanClub_ExecutableField2
{120, 0, 0}, // Career_EuropeanClub_ExecutableField3
{121, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField24
{122, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField29
{123, 0, 0}, // ClubSeasonRecords
{124, 0, 0}, // ClubSeasonRecords
};
std::map<int, Bytes> decoded;
std::map<uint32_t, Bytes> native;
for (const auto &[address, size] : kEnglishCompetitionBlocks)
native[address] = Bytes(size, 0);
size_t offset = 0;
bool club_records = false;
for (const auto &record : records) {
if (record.target == 124 && !club_records)
continue;
const size_t size = record.target < 0 ? record.size : layout.at(size_t(record.target)).size;
if (offset + size > source.stream.size())
throw FormatError("V2.20 state is truncated");
Bytes bytes(source.stream.begin() + offset, source.stream.begin() + offset + size);
offset += size;
if (record.target == 123) {
if (size != 4)
throw FormatError("Invalid club record pointer");
club_records = le32(bytes, 0) != 0;
}
if (record.target >= 0)
decoded[record.target] = bytes;
uint32_t target = record.native_address;
if (record.target == 93)
target = ::bmh::layout::EnglishAdditionalCupField;
if (record.target == 94)
target = ::bmh::layout::EnglishAdditionalCupResults;
if (target)
for (auto &[at, block] : native)
if (target >= at && uint64_t(target) + bytes.size() <= uint64_t(at) + block.size())
std::copy(bytes.begin(), bytes.end(), block.begin() + (target - at));
}
Bytes normalized;
for (size_t i = 0; i < layout.size(); ++i) {
if (i == 124 && !club_records)
continue;
if (const auto it = decoded.find(int(i)); it != decoded.end())
normalized.insert(normalized.end(), it->second.begin(), it->second.end());
else
normalized.insert(normalized.end(), layout[i].size, 0);
}
// Four length-prefixed name pools, shared by both original editions.
for (int i = 0; i < 4; ++i) {
if (offset + 2 > source.stream.size())
throw FormatError("V2.20 name pool missing");
const size_t size = le16(source.stream, offset) + 2;
if (offset + size > source.stream.size())
throw FormatError("V2.20 name pool is truncated");
normalized.insert(normalized.end(), source.stream.begin() + offset,
source.stream.begin() + offset + size);
offset += size;
}
if (offset != source.stream.size())
throw FormatError("V2.20 state has unexpected trailing bytes");
std::vector<SaveState::ExtensionBlock> extension;
for (auto &[at, bytes] : native)
extension.push_back({at, std::move(bytes)});
append_save_extension(normalized, extension);
(void)SaveState(normalized, counts);
return normalized;
}
} // namespace bmh::obw
-9
View File
@@ -1,9 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/fbm.hpp"
#include "formats/savestate.hpp"
namespace bmh::obw {
// Translate the V2.20 state-block contract, including its native cup regions,
// to the existing in-memory Classic layout. No executable or FBM file is emitted.
Bytes normalize_english_save(const Savegame &, const DbCounts &counts = {});
} // namespace bmh::obw
+2 -10
View File
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/audio_layout.hpp"
#include "launch/fltd.hpp"
#include <algorithm>
@@ -72,7 +71,7 @@ const OwnText kOwnTexts[] = {
} // namespace
LeImage translate_fltd(const fs::path& fltd_exe, bool apply_supported_rules) {
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");
@@ -120,15 +119,8 @@ LeImage translate_fltd(const fs::path& fltd_exe, bool apply_supported_rules) {
}
}
}
// Bind the English audio driver's data explicitly; the general UI/table map
// does not cover its OPL voice slots or key-on frequency table.
for (uint32_t i = 0; i < 9; ++i)
put(layout::Audio_OriginalAudioAssets_RuntimeField + i * 16,
en(layout::EnglishAudioOperatorSlots + i * 16));
for (uint32_t i = 0; i < 96 * 2; ++i)
put(layout::Audio_OriginalAudioAssets_RuntimeField2 + i, en(layout::EnglishAudioNoteFrequencies + i));
LeImage out = LeImage::from_bytes(kDeBase, std::move(image));
if (apply_supported_rules) apply_rule_base(out);
apply_rule_base(out);
return out;
}
+1 -1
View File
@@ -26,7 +26,7 @@
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, bool apply_supported_rules = true);
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.
-3
View File
@@ -96,9 +96,6 @@
{::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::Desktop_Render_RuntimeField, 2, Kind::copy, ::bmh::layout::EnglishDesktopBinSourceX, {}},
{::bmh::layout::Desktop_Render_RuntimeField2, 2, Kind::copy, ::bmh::layout::EnglishDesktopBinSourceY, {}},
{::bmh::layout::Desktop_Render_RuntimeField3, 2, Kind::copy, ::bmh::layout::EnglishDesktopSocketSourceX, {}},
{::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, {}},
+1 -2
View File
@@ -379,8 +379,7 @@ ResolvedGame resolve_game(const fs::path& input, const fs::path& cache) {
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 14"; // 14: bind native English OPL slots and note frequencies
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);
-97
View File
@@ -1,97 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher.hpp"
#include "launch/launcher_ui.hpp"
#include "launch/process.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include <atomic>
#include <future>
#include <mutex>
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &migrate) {
auto ui = make_launcher_ui();
ModLibrary library(executable.parent_path());
for (;;)
try {
const auto mods = library.list();
const auto action = ui->next(mods);
if (action.action == LauncherAction::end)
return 0;
if (action.action == LauncherAction::add) {
const auto source = ui->choose_folder("BMH-/Football-Limited-Installation wählen");
if (!source)
continue;
const auto check = check_game_directory(*source);
// Raw English installations are importable before legacy directory
// normalisation, so their old runtime "playable" flag is irrelevant.
if ((check.family != GameFamily::german && check.family != GameFamily::english) ||
!check.problems.empty()) {
std::string reason = check.unsupported;
for (const auto &problem : check.problems)
reason += "\n" + problem;
throw FormatError("Installation wird nicht unterstützt: " + reason);
}
AddMod initial;
initial.source = check.directory;
initial.saves = check.directory;
initial.name = check.family == GameFamily::english ? "FTDL-classic" : "BMH-classic";
const auto request = ui->configure_add(initial);
if (!request)
continue;
std::mutex mutex;
std::string text = "Import wird vorbereitet …";
std::atomic_bool cancelled = false;
ui->progress(text, true);
auto job = std::async(std::launch::async, [&] {
return library.add(*request, migrate, [&](const std::string &s) {
if (cancelled.load())
throw FormatError("Import abgebrochen");
std::lock_guard lock(mutex);
text = s;
});
});
while (job.wait_for(std::chrono::milliseconds(20)) != std::future_status::ready) {
if (ui->pump())
cancelled = true;
std::lock_guard lock(mutex);
ui->progress(text, true);
}
ui->finish_progress();
const auto report = job.get();
std::string summary =
"Mod importiert: " + report.mod.name +
"\nÜbernommene Spielstände/Einstellungen: " + std::to_string(report.migrated);
for (const auto &error : report.errors)
summary += "\n" + error;
ui->message(summary, false);
continue;
}
if (action.selection < 0 || size_t(action.selection) >= mods.size())
continue;
const auto &mod = mods[size_t(action.selection)];
if (action.action == LauncherAction::remove) {
if (ui->confirm_delete(mod.name))
library.remove(mod);
} else if (action.action == LauncherAction::rename) {
if (const auto name = ui->rename(mod.name))
library.rename(mod, *name);
} else if (action.action == LauncherAction::start) {
if (!mod.error.empty())
throw FormatError(mod.error);
(void)content::open(mod.directory / "content.obw");
const auto userdata = library.user_directory(mod);
ui->progress("Spiel läuft: " + mod.name, false);
const int code = run_child(executable,
{"--run-mod", path_to_utf8(mod.directory / "content.obw"),
"--save-directory", path_to_utf8(userdata)},
[&] { ui->pump(); });
ui->finish_progress();
if (code)
ui->message("Das Spiel wurde mit Fehlercode " + std::to_string(code) + " beendet.", true);
}
} catch (const std::exception &e) {
ui->finish_progress();
ui->message(e.what(), true);
}
}
} // namespace bmh::launch
-6
View File
@@ -1,6 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &);
} // namespace bmh::launch
-508
View File
@@ -1,508 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/archive.hpp"
#include "launch/launcher_ui.hpp"
#include "launch/process.hpp"
#include "launch/rml_path.hpp"
#include "launch/rml_video.hpp"
#include "version.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
#include <RmlUi_Platform_SDL.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <nfd.hpp>
#include <stdexcept>
namespace bmh::launch {
namespace {
std::string escape(std::string_view value) {
std::string result;
for (char c : value)
switch (c) {
case '&':
result += "&amp;";
break;
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '"':
result += "&quot;";
break;
case '\n':
result += "<br/>";
break;
default:
result += c;
}
return result;
}
int modifiers(Uint16 state) {
int result = 0;
if (state & KMOD_CTRL)
result |= Rml::Input::KM_CTRL;
if (state & KMOD_SHIFT)
result |= Rml::Input::KM_SHIFT;
if (state & KMOD_ALT)
result |= Rml::Input::KM_ALT;
if (state & KMOD_GUI)
result |= Rml::Input::KM_META;
#ifdef __APPLE__
// RmlUI text widgets use the Ctrl flag for editing shortcuts.
if (state & KMOD_GUI)
result |= Rml::Input::KM_CTRL;
#endif
if (state & KMOD_CAPS)
result |= Rml::Input::KM_CAPSLOCK;
if (state & KMOD_NUM)
result |= Rml::Input::KM_NUMLOCK;
return result;
}
class RmlLauncher final : public LauncherUI, public Rml::EventListener {
rml::Video video_{"OpenBMH", 1100, 688, 800, 540};
rml::AssetFiles files_;
SystemInterface_SDL system_{video_.window};
rml::Renderer renderer_{video_};
TextInputMethodEditor_SDL ime_;
Rml::Context *context_ = nullptr;
Rml::ElementDocument *document_ = nullptr;
bool initialized_ = false, closed_ = false, dirty_ = true;
bool answered_ = false, accepted_ = false, busy_ = false, cancelled_ = false;
bool cancellable_ = false, modal_visible_ = false;
int selected_ = -1;
std::string selected_name_;
std::vector<ModEntry> mods_;
std::optional<LauncherAction> action_;
Rml::Element *element(const char *id) const {
auto *value = document_->GetElementById(id);
if (!value)
throw std::runtime_error(std::string("Launcher element missing: ") + id);
return value;
}
void text(const char *id, const std::string &value) {
element(id)->SetInnerRML(escape(value));
dirty_ = true;
}
void display(const char *id, bool shown, const char *style = "block") {
element(id)->SetProperty("display", shown ? style : "none");
dirty_ = true;
}
void enabled(const char *id, bool active) {
auto *button = element(id);
if (active)
button->RemoveAttribute("disabled");
else
button->SetAttribute("disabled", "disabled");
button->SetPseudoClass("disabled", !active);
button->SetProperty("focus", active ? "auto" : "none");
dirty_ = true;
}
std::string value(const char *id) const {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element(id));
if (!input)
throw std::runtime_error("Launcher input has the wrong type");
return input->GetValue();
}
void resize() {
int w = 0, h = 0, pixels_w = 0, pixels_h = 0;
SDL_GetWindowSize(video_.window, &w, &h);
video_.drawable_size(pixels_w, pixels_h);
if (w <= 0 || h <= 0 || pixels_w <= 0 || pixels_h <= 0)
return;
renderer_.SetViewport(pixels_w, pixels_h);
context_->SetDimensions({pixels_w, pixels_h});
const float scale = std::clamp(std::min(w / 1100.f, h / 688.f), .72f, 2.5f);
context_->SetDensityIndependentPixelRatio(float(pixels_w) / w * scale);
dirty_ = true;
}
void select(int index, bool focus = false) {
if (index < 0 || size_t(index) >= mods_.size())
index = -1;
selected_ = index;
selected_name_ = index >= 0 ? mods_[size_t(index)].name : std::string{};
for (size_t i = 0; i < mods_.size(); ++i) {
auto *row = document_->GetElementById("mod-" + std::to_string(i));
row->SetClass("selected", int(i) == selected_);
row->SetAttribute("aria-selected", int(i) == selected_ ? "true" : "false");
if (focus && int(i) == selected_) {
row->Focus(true);
row->ScrollIntoView();
}
}
enabled("start", selected_ >= 0);
enabled("delete", selected_ >= 0);
enabled("rename", selected_ >= 0);
}
bool modal_open() const { return modal_visible_; }
void close_modal() {
modal_visible_ = false;
display("overlay", false);
answered_ = false;
busy_ = false;
SDL_StopTextInput();
if (selected_ >= 0)
select(selected_, true);
else
element("add")->Focus(true);
}
void modal(const std::string &title, const std::string &body, const std::string &accept,
bool cancel = true, bool danger = false) {
text("modal-title", title);
element("modal-body")->SetInnerRML(body);
text("modal-error", "");
text("accept", accept);
element("accept")->SetClass("danger", danger);
element("accept")->SetClass("primary", !danger);
display("accept", !accept.empty(), "inline-block");
display("cancel", cancel, "inline-block");
answered_ = accepted_ = false;
display("overlay", true);
modal_visible_ = true;
context_->Update();
if (auto *input = document_->GetElementById("mod-name"))
input->Focus(true);
else
element(cancel ? "cancel" : "accept")->Focus(true);
context_->Update();
dirty_ = true;
}
void dispatch(const std::string &command) {
if (command == "cancel") {
if (busy_) {
if (cancellable_)
cancelled_ = true;
} else {
answered_ = true;
accepted_ = false;
}
} else if (command == "accept" && !busy_) {
answered_ = accepted_ = true;
} else if (command == "browse" && !busy_) {
try {
if (auto path =
choose_folder("Spielstandsordner wählen", path_from_utf8(value("save-folder")))) {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element("save-folder"));
input->SetValue(path_to_utf8(*path));
}
} catch (const std::exception &e) {
text("modal-error", e.what());
}
} else if (!modal_open()) {
if (command == "add")
action_ = LauncherAction::add;
else if (command == "end")
action_ = LauncherAction::end;
else if (selected_ >= 0) {
if (command == "start")
action_ = LauncherAction::start;
else if (command == "rename")
action_ = LauncherAction::rename;
else if (command == "delete")
action_ = LauncherAction::remove;
}
}
dirty_ = true;
}
void ProcessEvent(Rml::Event &event) override {
const bool double_click = event.GetType() == "dblclick";
if (event.GetType() != "click" && !double_click)
return;
for (auto *target = event.GetTargetElement(); target && target != document_;
target = target->GetParentNode()) {
if (target->HasAttribute("data-row") && !modal_open()) {
select(target->GetAttribute<int>("data-row", -1));
if (double_click)
dispatch("start");
return;
}
if (target->HasAttribute("data-action")) {
if (double_click)
return;
if (!target->HasAttribute("disabled"))
dispatch(target->GetAttribute<Rml::String>("data-action", ""));
return;
}
}
}
void step(bool wait) {
// Modal visibility and refreshed rows must be laid out before queued
// pointer events are hit-tested against the new document state.
if (dirty_) context_->Update();
SDL_Event event;
const int timeout = dirty_ ? 0 : int(std::clamp(context_->GetNextUpdateDelay(), 0.0, .2) * 1000);
bool got = wait ? SDL_WaitEventTimeout(&event, timeout) != 0 : SDL_PollEvent(&event) != 0;
bool redraw = dirty_ || got || context_->GetNextUpdateDelay() <= 0;
while (got) {
if (event.type == SDL_QUIT ||
(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE)) {
closed_ = answered_ = true;
accepted_ = false;
cancelled_ = true;
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_ESCAPE) {
if (modal_open())
dispatch("cancel");
else
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && modal_open() && event.key.keysym.sym == SDLK_TAB) {
Rml::ElementList controls;
element("modal")->QuerySelectorAll(controls, "input, button");
std::erase_if(controls, [](auto *control) {
return !control->IsVisible() || control->HasAttribute("disabled");
});
if (!controls.empty()) {
const auto at = std::find(controls.begin(), controls.end(), context_->GetFocusElement());
const int current = at == controls.end() ? -1 : int(at - controls.begin());
const int step = event.key.keysym.mod & KMOD_SHIFT ? -1 : 1;
const int next = (current + step + int(controls.size())) % int(controls.size());
controls[size_t(next)]->Focus(true);
}
} else if (event.type == SDL_KEYDOWN && !modal_open() && !event.key.repeat &&
(event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_DOWN)) {
const int direction = event.key.keysym.sym == SDLK_UP ? -1 : 1;
if (!mods_.empty())
select(std::clamp(selected_ < 0 ? 0 : selected_ + direction, 0, int(mods_.size()) - 1),
true);
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_SPACE) &&
context_->GetFocusElement() &&
context_->GetFocusElement()->HasAttribute("data-action")) {
auto *focused = context_->GetFocusElement();
if (!focused->HasAttribute("disabled"))
dispatch(focused->GetAttribute<Rml::String>("data-action", ""));
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_RETURN) {
if (modal_open() && !busy_)
dispatch("accept");
else if (!modal_open() && selected_ >= 0)
dispatch("start");
} else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
// Use the modifiers captured with this event, not SDL's final
// state after pumping a batch containing the key releases.
const auto key = RmlSDL::ConvertKey(event.key.keysym.sym);
if (event.type == SDL_KEYDOWN)
context_->ProcessKeyDown(key, modifiers(event.key.keysym.mod));
else
context_->ProcessKeyUp(key, modifiers(event.key.keysym.mod));
} else {
if (event.type == SDL_TEXTEDITING)
ime_.HandleEdit(event.edit);
// SDL2 reports mouse coordinates in window units on Retina/HiDPI.
int w = 0, h = 0, pw = 0, ph = 0;
SDL_GetWindowSize(video_.window, &w, &h);
video_.drawable_size(pw, ph);
if (w > 0 && h > 0) {
if (event.type == SDL_MOUSEMOTION) {
event.motion.x = int(double(event.motion.x) * pw / w);
event.motion.y = int(double(event.motion.y) * ph / h);
}
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) {
event.button.x = int(double(event.button.x) * pw / w);
event.button.y = int(double(event.button.y) * ph / h);
// Repeated clicks need a fresh hover target even when
// the pointer has not moved since a modal was closed.
context_->ProcessMouseMove(event.button.x, event.button.y,
RmlSDL::GetKeyModifierState());
}
}
RmlSDL::InputEventHandler(context_, video_.window, event);
}
if (event.type == SDL_WINDOWEVENT)
resize();
got = SDL_PollEvent(&event) != 0;
}
if (redraw) {
context_->Update();
renderer_.BeginFrame();
renderer_.Clear();
context_->Render();
renderer_.EndFrame();
video_.present();
dirty_ = false;
}
}
bool wait_modal() {
while (!answered_ && !closed_)
step(true);
answered_ = false;
return accepted_ && !closed_;
}
public:
RmlLauncher() {
SDL_StopTextInput();
if (!renderer_)
throw std::runtime_error("RmlUI could not create the graphics renderer");
try {
Rml::SetSystemInterface(&system_);
Rml::SetFileInterface(&files_);
Rml::SetRenderInterface(&renderer_);
Rml::SetTextInputHandler(&ime_);
initialized_ = Rml::Initialise();
if (!initialized_)
throw std::runtime_error("RmlUI initialization failed");
const auto assets = executable_path({}).parent_path() / "assets" / "launcher";
for (const char *weight : {"Regular", "Bold"})
if (!Rml::LoadFontFace(rml::asset_path(assets / (std::string("LatoLatin-") + weight + ".ttf"))))
throw std::runtime_error("Launcher font missing; extract the complete OpenBMH package");
context_ = Rml::CreateContext("launcher", {1100, 688});
if (!context_)
throw std::runtime_error("RmlUI launcher context failed");
document_ = context_->LoadDocument(rml::asset_path(assets / "launcher.rml"));
if (!document_)
throw std::runtime_error("Launcher layout missing; extract the complete OpenBMH package");
document_->AddEventListener("click", this);
document_->AddEventListener("dblclick", this);
text("version", std::string("v") + bmh::kOpenBmhVersion);
resize();
document_->Show();
SDL_ShowWindow(video_.window);
element("add")->Focus(true);
} catch (...) {
if (initialized_)
Rml::Shutdown();
throw;
}
}
~RmlLauncher() override {
if (initialized_)
Rml::Shutdown();
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
if (closed_)
return {LauncherAction::end, -1};
mods_ = mods;
std::string rows;
int selection = -1;
for (size_t i = 0; i < mods.size(); ++i) {
const auto &mod = mods[i];
if (mod.name == selected_name_)
selection = int(i);
rows += "<button id=\"mod-" + std::to_string(i) + "\" class=\"mod-row" +
(mod.error.empty() ? "" : " invalid") + "\" data-row=\"" + std::to_string(i) +
"\" title=\"" + escape(mod.error) + "\"><span class=\"name\">" + escape(mod.name) +
"</span><span class=\"type\">" + escape(mod.type) + "</span></button>";
}
if (mods.empty())
rows = "<div class=\"empty\">Keine Mods vorhanden.<div class=\"empty-detail\">Über Add eine "
"Installation hinzufügen.</div></div>";
element("mod-list")->SetInnerRML(rows);
text("mod-count", std::to_string(mods.size()) + (mods.size() == 1 ? " Mod" : " Mods"));
select(selection);
action_.reset();
while (!action_ && !closed_)
step(true);
return {action_.value_or(LauncherAction::end), selected_};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) override {
(void)title;
NFD::Guard guard;
NFD::UniquePathU8 result;
const auto directory = path_to_utf8(initial.empty() ? executable_path({}).parent_path() : initial);
const auto status = NFD::PickFolder(result, directory.c_str());
SDL_RaiseWindow(video_.window);
dirty_ = true;
if (status == NFD_CANCEL)
return {};
if (status != NFD_OKAY)
throw std::runtime_error(std::string("Ordnerauswahl: ") + NFD::GetError());
return path_from_utf8(result.get());
}
std::optional<AddMod> configure_add(AddMod initial) override {
modal("Classic-Mod hinzufügen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(initial.name) +
"\"/><div class=\"fields\"><div class=\"year\"><label>Startjahr (nur "
"Anzeige)</label><input id=\"start-year\" type=\"text\" maxlength=\"4\" value=\"" +
std::to_string(initial.start_year) +
"\"/></div></div><div class=\"check-row\"><input id=\"migrate\" class=\"checkbox\" "
"type=\"checkbox\" " +
(initial.migrate ? "checked=\"checked\"" : "") +
"/><label for=\"migrate\">Spielstände/Einstellungen "
"übernehmen</label></div><label>Spielstandsordner</label><div class=\"browse-row\"><input "
"id=\"save-folder\" type=\"text\" value=\"" +
escape(path_to_utf8(initial.saves)) +
"\"/><button data-action=\"browse\">Auswählen …</button></div>",
"Importieren");
while (wait_modal()) {
try {
initial.name = value("mod-name");
ModLibrary::validate_name(initial.name);
const auto year = value("start-year");
size_t end = 0;
initial.start_year = std::stoi(year, &end);
if (end != year.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen.");
initial.migrate = element("migrate")->HasAttribute("checked");
initial.saves = path_from_utf8(value("save-folder"));
close_modal();
return initial;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return {};
}
std::optional<std::string> rename(const std::string &old) override {
modal("Mod umbenennen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(old) + "\"/>",
"Umbenennen");
std::optional<std::string> result;
while (wait_modal()) {
try {
auto name = value("mod-name");
ModLibrary::validate_name(name);
result = name;
break;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return result;
}
bool confirm_delete(const std::string &name) override {
modal("Mod löschen?",
"„" + escape(name) + "“<br/><br/>Spielstände und persönliche Einstellungen bleiben erhalten.",
"Löschen", true, true);
const bool result = wait_modal();
close_modal();
return result;
}
void message(const std::string &value, bool error) override {
if (closed_)
return;
modal(error ? "OpenBMH · Hinweis" : "OpenBMH", escape(value), "OK", false);
wait_modal();
close_modal();
}
void progress(const std::string &value, bool cancellable) override {
if (!busy_) {
modal(cancellable ? "Mod importieren" : "Spiel läuft", escape(value), "", cancellable);
busy_ = true;
cancelled_ = false;
cancellable_ = cancellable;
} else
text("modal-body", value);
}
bool pump() override {
step(false);
return cancelled_ || closed_;
}
void finish_progress() override {
if (busy_)
close_modal();
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<RmlLauncher>(); }
} // namespace bmh::launch
-27
View File
@@ -1,27 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
#include <memory>
#include <optional>
namespace bmh::launch {
enum class LauncherAction { start, add, remove, rename, end };
struct LauncherChoice {
LauncherAction action = LauncherAction::end;
int selection = -1;
};
class LauncherUI {
public:
virtual ~LauncherUI() = default;
virtual LauncherChoice next(const std::vector<ModEntry> &) = 0;
virtual std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) = 0;
virtual std::optional<AddMod> configure_add(AddMod defaults) = 0;
virtual std::optional<std::string> rename(const std::string &) = 0;
virtual bool confirm_delete(const std::string &) = 0;
virtual void message(const std::string &, bool error) = 0;
virtual void progress(const std::string &, bool cancellable) = 0;
virtual bool pump() = 0; // cancellation requested
virtual void finish_progress() = 0;
};
std::unique_ptr<LauncherUI> make_launcher_ui();
} // namespace bmh::launch
-190
View File
@@ -1,190 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/mods.hpp"
#include "content/save.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <set>
namespace bmh::launch {
namespace fs = std::filesystem;
namespace {
std::string fold(std::string s) {
for (auto &c : s)
c = char(std::tolower(static_cast<unsigned char>(c)));
return s;
}
std::string filename(const fs::path &p) { return path_to_utf8(p.filename()); }
void safe_directory(const fs::path &path) {
const auto status = fs::symlink_status(path);
if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status)))
throw FormatError("Unsafe portable directory: " + path_to_utf8(path));
fs::create_directories(path);
}
} // namespace
ModLibrary::ModLibrary(fs::path root) : root_(fs::absolute(std::move(root)).lexically_normal()) {}
void ModLibrary::validate_name(const std::string &name) {
if (name.empty() || name.size() > 100 || name == "." || name == ".." || name.front() == '.' ||
name.back() == '.' || name.back() == ' ')
throw FormatError("Invalid mod name");
for (unsigned char c : name)
if (c < 32 || c == 127 || std::string("/\\:*?\"<>|").find(char(c)) != std::string::npos)
throw FormatError("Invalid character in mod name");
auto base = fold(name.substr(0, name.find('.')));
const std::set<std::string> reserved{"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4",
"com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
"lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
if (reserved.contains(base))
throw FormatError("Reserved mod name");
}
std::vector<ModEntry> ModLibrary::list() const {
std::vector<ModEntry> out;
const auto folder = root_ / "mods";
if (!fs::exists(fs::symlink_status(folder)))
return out;
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder)) {
const auto name = filename(entry.path());
if (name.starts_with('.'))
continue;
if (!entry.is_directory() && !entry.is_symlink())
continue;
ModEntry mod;
mod.name = name;
mod.directory = entry.path();
try {
validate_name(name);
if (entry.is_symlink())
throw FormatError("Linked mod directories are not supported");
for (const auto &child : fs::directory_iterator(entry.path()))
if (child.path().filename() != "content.obw")
throw FormatError("Unexpected files in sealed Classic mod");
const auto content = content::open(entry.path() / "content.obw");
mod.content_id = content->content_id;
} catch (const std::exception &e) {
mod.error = e.what();
}
out.push_back(std::move(mod));
}
std::sort(out.begin(), out.end(),
[](const auto &a, const auto &b) { return fold(a.name) < fold(b.name); });
return out;
}
void ModLibrary::available(const std::string &name) const {
validate_name(name);
const auto folder = root_ / "mods";
if (fs::exists(fs::symlink_status(folder))) {
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder))
if (fold(filename(entry.path())) == fold(name))
throw FormatError("A mod with this name already exists");
}
}
void ModLibrary::owned(const ModEntry &mod) const {
if (mod.directory.parent_path() != root_ / "mods" || filename(mod.directory) != mod.name ||
fs::is_symlink(fs::symlink_status(mod.directory)))
throw FormatError("Mod path is not owned by this library");
}
fs::path ModLibrary::user_directory(const ModEntry &mod) const {
if (mod.content_id.size() != 64 ||
mod.content_id.find_first_not_of("0123456789abcdef") != std::string::npos)
throw FormatError("Invalid mod identity");
safe_directory(root_ / "userdata");
const auto directory = root_ / "userdata" / mod.content_id;
safe_directory(directory);
return directory;
}
ImportReport ModLibrary::add(const AddMod &request, const SaveMigrator &migrate,
const ImportProgress &progress) {
available(request.name);
if (request.start_year < 1900 || request.start_year > 9998)
throw FormatError("Start year must be 1900–9998");
safe_directory(root_ / "mods");
const auto update = [&](const std::string &s) {
if (progress)
progress(s);
};
update("Installation wird konvertiert …");
obw::Options options;
options.start_date = std::to_string(request.start_year) + "-07-01";
options.title = "Classic installation";
auto docs = obw::import_installation(request.source, options);
const auto identity = content::seal(docs);
update("Konvertierte Inhalte werden geprüft …");
const auto staging =
root_ / "mods" /
(".import-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
if (!fs::create_directory(staging))
throw FormatError("Cannot reserve mod staging directory");
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{staging};
content::write_archive(docs, staging / "content.obw");
(void)content::open(staging / "content.obw");
ImportReport report;
report.mod = {request.name, "Classic", identity, {}, root_ / "mods" / path_from_utf8(request.name)};
const auto userdata = user_directory(report.mod);
// User data is retained separately, and never overwrites a previous migration.
if (request.migrate) {
const auto source = request.saves.empty() ? request.source : request.saves;
if (!fs::is_directory(source))
report.errors.push_back("Spielstandsordner ist nicht verfügbar");
else {
std::vector<fs::path> files;
for (const auto &entry : fs::directory_iterator(source))
if (entry.is_regular_file() && !entry.is_symlink())
files.push_back(entry.path());
std::sort(files.begin(), files.end());
for (const auto &input : files) {
const auto ext = fold(path_to_utf8(input.extension()));
if (ext != ".fbm" && ext != ".ein" && ext != ".men")
continue;
update("Übernahme: " + filename(input));
try {
auto destination = userdata / input.stem();
destination += ext == ".fbm" ? ".obs" : ext == ".ein" ? ".obsettings" : ".oblayout";
if (fs::exists(fs::symlink_status(destination)))
throw FormatError("Destination already exists; retained existing file");
if (ext == ".fbm") {
if (!migrate)
throw FormatError("Save migrator unavailable");
migrate(staging / "content.obw", input, destination);
} else {
auto bytes = read_file(input);
if (ext == ".ein" && bytes.size() != 180)
throw FormatError("Invalid settings length");
if (ext == ".men" && bytes.size() != 0x360)
throw FormatError("Invalid desktop layout length");
content::save_preferences(destination, ext == ".ein" ? "settings" : "layout", bytes,
false);
}
++report.migrated;
} catch (const std::exception &e) {
report.errors.push_back(filename(input) + ": " + e.what());
}
}
}
}
update("Mod wird eingetragen …");
available(request.name);
fs::rename(staging, report.mod.directory);
return report;
}
void ModLibrary::rename(const ModEntry &mod, const std::string &name) {
owned(mod);
if (name == mod.name)
return;
available(name);
fs::rename(mod.directory, root_ / "mods" / path_from_utf8(name));
}
void ModLibrary::remove(const ModEntry &mod) {
owned(mod);
fs::remove_all(mod.directory);
}
} // namespace bmh::launch
-41
View File
@@ -1,41 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "content/package.hpp"
#include <functional>
namespace bmh::launch {
struct ModEntry {
std::string name, type = "Classic", content_id, error;
std::filesystem::path directory;
};
struct AddMod {
std::filesystem::path source, saves;
std::string name;
int start_year = 2026;
bool migrate = true;
};
using SaveMigrator =
std::function<void(const std::filesystem::path &content, const std::filesystem::path &source,
const std::filesystem::path &destination)>;
using ImportProgress = std::function<void(const std::string &)>;
struct ImportReport {
ModEntry mod;
size_t migrated = 0;
std::vector<std::string> errors;
};
class ModLibrary {
public:
explicit ModLibrary(std::filesystem::path portable_root);
std::vector<ModEntry> list() const;
ImportReport add(const AddMod &, const SaveMigrator &, const ImportProgress &progress = {});
void rename(const ModEntry &, const std::string &name);
void remove(const ModEntry &);
std::filesystem::path user_directory(const ModEntry &) const;
const std::filesystem::path &root() const { return root_; }
static void validate_name(const std::string &);
private:
std::filesystem::path root_;
void available(const std::string &) const;
void owned(const ModEntry &) const;
};
} // namespace bmh::launch
-115
View File
@@ -1,115 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/process.hpp"
#include "launch/archive.hpp"
#include <chrono>
#include <thread>
#include <stdexcept>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <spawn.h>
#include <sys/wait.h>
#include <cerrno>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
extern char **environ;
#endif
namespace bmh::launch {
std::filesystem::path executable_path(const std::filesystem::path &invocation) {
#ifdef _WIN32
std::vector<wchar_t> buffer(1024);
for (;;) {
const auto length = GetModuleFileNameW(nullptr, buffer.data(), DWORD(buffer.size()));
if (!length)
throw std::runtime_error("Cannot locate OpenBMH executable");
if (length < buffer.size())
return std::filesystem::path(std::wstring(buffer.data(), length));
if (buffer.size() > 32768)
throw std::runtime_error("Executable path is too long");
buffer.resize(buffer.size() * 2);
}
#elif defined(__APPLE__)
uint32_t size = 0;
_NSGetExecutablePath(nullptr, &size);
std::vector<char> buffer(size);
if (_NSGetExecutablePath(buffer.data(), &size) != 0)
throw std::runtime_error("Cannot locate OpenBMH executable");
return std::filesystem::canonical(path_from_utf8(buffer.data()));
#else
std::error_code error;
const auto path = std::filesystem::read_symlink("/proc/self/exe", error);
if (!error)
return path;
return std::filesystem::absolute(invocation).lexically_normal();
#endif
}
int run_child(const std::filesystem::path &executable, const std::vector<std::string> &args,
const std::function<void()> &pump) {
#ifdef _WIN32
const auto quote = [](const std::wstring &value) {
std::wstring out = L"\"";
size_t slashes = 0;
for (wchar_t c : value) {
if (c == L'\\') {
++slashes;
continue;
}
if (c == L'\"')
out.append(slashes * 2 + 1, L'\\');
else
out.append(slashes, L'\\');
out += c;
slashes = 0;
}
out.append(slashes * 2, L'\\');
out += L'\"';
return out;
};
auto command = quote(executable.wstring());
for (const auto &a : args) {
command += L' ';
command += quote(path_from_utf8(a).wstring());
}
STARTUPINFOW start{};
start.cb = sizeof(start);
PROCESS_INFORMATION process{};
if (!CreateProcessW(executable.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
executable.parent_path().c_str(), &start, &process))
throw std::runtime_error("Cannot start OpenBMH game process");
CloseHandle(process.hThread);
while (WaitForSingleObject(process.hProcess, 20) == WAIT_TIMEOUT)
if (pump)
pump();
DWORD code = 1;
GetExitCodeProcess(process.hProcess, &code);
CloseHandle(process.hProcess);
return int(code);
#else
const auto binary = path_to_utf8(executable);
std::vector<std::string> storage{binary};
storage.insert(storage.end(), args.begin(), args.end());
std::vector<char *> argv;
for (auto &s : storage)
argv.push_back(s.data());
argv.push_back(nullptr);
pid_t pid;
const int error = posix_spawn(&pid, binary.c_str(), nullptr, nullptr, argv.data(), environ);
if (error)
throw std::runtime_error("Cannot start OpenBMH game process (" + std::to_string(error) + ")");
int status = 0;
for (;;) {
const auto result = waitpid(pid, &status, WNOHANG);
if (result == pid)
break;
if (result < 0 && errno != EINTR)
throw std::runtime_error("Cannot wait for game process");
if (pump)
pump();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
#endif
}
} // namespace bmh::launch
-11
View File
@@ -1,11 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <functional>
#include <string>
#include <vector>
namespace bmh::launch {
std::filesystem::path executable_path(const std::filesystem::path &invocation);
int run_child(const std::filesystem::path &, const std::vector<std::string> &,
const std::function<void()> &pump);
} // namespace bmh::launch
-35
View File
@@ -1,35 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <string>
#include <cstdio>
#include <RmlUi/Core/FileInterface.h>
namespace bmh::rml {
// RmlUI parses document locations as URLs. Native Windows backslashes make
// URL::GetPath() empty, so relative image sources lose their asset directory.
inline std::string asset_path(const std::filesystem::path &path) {
const auto utf8 = path.generic_u8string();
return {utf8.begin(), utf8.end()};
}
// RmlUI paths are UTF-8. The Windows narrow fopen API uses the system code page.
class AssetFiles : public Rml::FileInterface {
public:
Rml::FileHandle Open(const Rml::String &path) override {
#ifdef _WIN32
const std::u8string utf8(path.begin(), path.end());
return reinterpret_cast<Rml::FileHandle>(_wfopen(std::filesystem::path(utf8).c_str(), L"rb"));
#else
return reinterpret_cast<Rml::FileHandle>(std::fopen(path.c_str(), "rb"));
#endif
}
void Close(Rml::FileHandle file) override { std::fclose(reinterpret_cast<FILE *>(file)); }
size_t Read(void *buffer, size_t size, Rml::FileHandle file) override {
return std::fread(buffer, 1, size, reinterpret_cast<FILE *>(file));
}
bool Seek(Rml::FileHandle file, long offset, int origin) override {
return std::fseek(reinterpret_cast<FILE *>(file), offset, origin) == 0;
}
size_t Tell(Rml::FileHandle file) override { return size_t(std::ftell(reinterpret_cast<FILE *>(file))); }
};
} // namespace bmh::rml
-236
View File
@@ -1,236 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/rml_video.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <string_view>
#ifdef _WIN32
#include <SDL_syswm.h>
#endif
namespace bmh::rml {
namespace {
[[noreturn]] void sdl_error(const char *operation) {
throw std::runtime_error(std::string(operation) + ": " + SDL_GetError());
}
#ifdef _WIN32
void check(HRESULT result, const char *operation) {
if (FAILED(result)) {
char code[24];
std::snprintf(code, sizeof(code), "0x%08lX", static_cast<unsigned long>(result));
throw std::runtime_error(std::string(operation) + ": " + code);
}
}
std::wstring wide(const std::string &text) {
const int length = MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0);
std::wstring result(size_t(length), L' ');
MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), result.data(), length);
return result;
}
#endif
} // namespace
Video::Video(const char *title, int width, int height, int minimum_width, int minimum_height) {
try {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
sdl_error("Video initialization");
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
Uint32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN;
#ifndef _WIN32
flags |= SDL_WINDOW_OPENGL;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef __APPLE__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
#else
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#endif
window =
SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags);
if (!window)
sdl_error("Window creation");
SDL_SetWindowMinimumSize(window, minimum_width, minimum_height);
#ifdef _WIN32
SDL_SysWMinfo info{};
SDL_VERSION(&info.version);
if (!SDL_GetWindowWMInfo(window, &info))
sdl_error("Native window handle");
DXGI_SWAP_CHAIN_DESC desc{};
desc.BufferCount = 2;
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.OutputWindow = info.info.win.window;
desc.SampleDesc.Count = 1;
desc.Windowed = TRUE;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0};
auto create = [&](D3D_DRIVER_TYPE driver) {
return D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, 0, levels, 1, D3D11_SDK_VERSION,
&desc, swapchain_.ReleaseAndGetAddressOf(),
device_.ReleaseAndGetAddressOf(), nullptr,
context_.ReleaseAndGetAddressOf());
};
const auto mode = std::getenv("OPENBMH_RML_DRIVER");
const bool force_warp = mode && std::string_view(mode) == "warp";
HRESULT result = force_warp ? E_FAIL : create(D3D_DRIVER_TYPE_HARDWARE);
bool software = false;
if (FAILED(result)) {
result = create(D3D_DRIVER_TYPE_WARP);
software = true;
}
check(result, "Direct3D 11 initialization (hardware and WARP)");
// Upstream's full-featured renderer requires the 11.1 runtime interfaces.
Microsoft::WRL::ComPtr<ID3D11Device1> device1;
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> context1;
check(device_.As(&device1), "Direct3D 11.1 device");
check(context_.As(&context1), "Direct3D 11.1 context");
std::fprintf(stderr, "RmlUI renderer: Direct3D 11 (%s)\n", software ? "WARP software" : "hardware");
int pw, ph;
drawable_size(pw, ph);
resize(pw, ph);
#else
gl_ = SDL_GL_CreateContext(window);
if (!gl_)
sdl_error("OpenGL 3.3 initialization (macOS: 4.1)");
if (SDL_GL_MakeCurrent(window, gl_) != 0)
sdl_error("OpenGL context activation");
SDL_GL_SetSwapInterval(1);
std::string error;
if (!RmlGL3::Initialize(&error))
throw std::runtime_error("OpenGL renderer initialization: " + error);
loader_ = true;
#endif
} catch (...) {
close();
throw;
}
}
Video::~Video() { close(); }
void Video::close() noexcept {
#ifdef _WIN32
if (context_)
context_->ClearState();
target_.Reset();
swapchain_.Reset();
context_.Reset();
device_.Reset();
#else
if (loader_)
RmlGL3::Shutdown();
if (gl_)
SDL_GL_DeleteContext(gl_);
#endif
if (window)
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER);
}
void Video::drawable_size(int &width, int &height) const {
#ifdef _WIN32
SDL_GetWindowSizeInPixels(window, &width, &height);
#else
SDL_GL_GetDrawableSize(window, &width, &height);
#endif
}
#ifdef _WIN32
void Video::resize(int width, int height) {
if (width < 1 || height < 1 || (width == width_ && height == height_ && target_))
return;
context_->OMSetRenderTargets(0, nullptr, nullptr);
target_.Reset();
check(swapchain_->ResizeBuffers(0, UINT(width), UINT(height), DXGI_FORMAT_UNKNOWN, 0),
"Swapchain resize");
Microsoft::WRL::ComPtr<ID3D11Texture2D> buffer;
check(swapchain_->GetBuffer(0, IID_PPV_ARGS(&buffer)), "Swapchain buffer");
check(device_->CreateRenderTargetView(buffer.Get(), nullptr, &target_), "Render target");
width_ = width;
height_ = height;
}
#endif
void Video::present() {
#ifdef _WIN32
check(swapchain_->Present(1, 0), "Direct3D presentation");
#else
SDL_GL_SwapWindow(window);
#endif
}
std::vector<uint8_t> Video::capture(int &width, int &height) {
#ifdef _WIN32
Microsoft::WRL::ComPtr<ID3D11Texture2D> buffer, staging;
check(swapchain_->GetBuffer(0, IID_PPV_ARGS(&buffer)), "Screenshot buffer");
D3D11_TEXTURE2D_DESC desc{};
buffer->GetDesc(&desc);
width = static_cast<int>(desc.Width);
height = static_cast<int>(desc.Height);
std::vector<uint8_t> pixels(size_t(width) * size_t(height) * 4);
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;
check(device_->CreateTexture2D(&desc, nullptr, &staging), "Screenshot staging texture");
context_->CopyResource(staging.Get(), buffer.Get());
D3D11_MAPPED_SUBRESOURCE data{};
check(context_->Map(staging.Get(), 0, D3D11_MAP_READ, 0, &data), "Screenshot readback");
for (int row = 0; row < height; ++row)
std::memcpy(pixels.data() + size_t(row) * width * 4,
static_cast<const uint8_t *>(data.pData) + size_t(row) * data.RowPitch,
size_t(width) * 4);
context_->Unmap(staging.Get(), 0);
#else
drawable_size(width, height);
std::vector<uint8_t> pixels(size_t(width) * size_t(height) * 4);
using ReadPixels = void (*)(int, int, int, int, unsigned, unsigned, void *);
auto read = reinterpret_cast<ReadPixels>(SDL_GL_GetProcAddress("glReadPixels"));
if (!read)
sdl_error("Screenshot readback");
read(0, 0, width, height, 0x1908, 0x1401, pixels.data());
for (int row = 0; row < height / 2; ++row)
for (int col = 0; col < width * 4; ++col)
std::swap(pixels[size_t(row) * width * 4 + col],
pixels[size_t(height - row - 1) * width * 4 + col]);
#endif
return pixels;
}
void report_start_error(const char *product, const std::string &message, bool dialog) noexcept {
std::fprintf(stderr, "%s: %s\n", product, message.c_str());
#ifdef _WIN32
try {
wchar_t directory[32768]{};
const auto length = GetEnvironmentVariableW(L"LOCALAPPDATA", directory, 32768);
auto root = (length > 0 && length < 32768 ? std::filesystem::path(directory)
: std::filesystem::temp_directory_path()) /
L"OpenBMH";
std::filesystem::create_directories(root);
std::ofstream log(root / (std::string(product) + "-startup.log"), std::ios::app);
log << message << '\n';
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
MessageBoxW(nullptr, wide(message).c_str(), wide(product).c_str(), MB_OK | MB_ICONERROR);
} catch (...) {
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
MessageBoxW(nullptr, L"The application could not start.", L"OpenBMH", MB_OK | MB_ICONERROR);
}
#else
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, product, message.c_str(), nullptr);
#endif
}
void attach_parent_console() noexcept {
#ifdef _WIN32
const bool out_free = _fileno(stdout) < 0, err_free = _fileno(stderr) < 0;
if ((out_free || err_free) && AttachConsole(ATTACH_PARENT_PROCESS)) {
FILE *stream = nullptr;
if (out_free)
freopen_s(&stream, "CONOUT$", "w", stdout);
if (err_free)
freopen_s(&stream, "CONOUT$", "w", stderr);
}
#endif
}
} // namespace bmh::rml
-71
View File
@@ -1,71 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/startup_error.hpp"
#include <SDL.h>
#include <cstdint>
#include <string>
#include <vector>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <RmlUi_Renderer_DX11.h>
#include <wrl/client.h>
#else
#include <RmlUi_Renderer_GL3.h>
#endif
namespace bmh::rml {
// The native Windows renderer needs no OpenGL ICD in a Remote Desktop session.
// The device falls back to Microsoft's built-in WARP when hardware is absent.
class Video {
public:
SDL_Window *window = nullptr;
Video(const char *title, int width, int height, int minimum_width, int minimum_height);
~Video();
Video(const Video &) = delete;
Video &operator=(const Video &) = delete;
void drawable_size(int &width, int &height) const;
void present();
// RGBA rows in top-to-bottom order, independent of the graphics API.
std::vector<uint8_t> capture(int &width, int &height);
#ifdef _WIN32
ID3D11Device *device() const { return device_.Get(); }
ID3D11RenderTargetView *target() const { return target_.Get(); }
void resize(int width, int height);
#endif
private:
void close() noexcept;
#ifdef _WIN32
Microsoft::WRL::ComPtr<ID3D11Device> device_;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context_;
Microsoft::WRL::ComPtr<IDXGISwapChain> swapchain_;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> target_;
int width_ = 0, height_ = 0;
#else
SDL_GLContext gl_ = nullptr;
bool loader_ = false;
#endif
};
#ifdef _WIN32
class Renderer : public RenderInterface_DX11 {
Video &video_;
public:
explicit Renderer(Video &video) : RenderInterface_DX11(video.device()), video_(video) {}
void SetViewport(int width, int height) {
video_.resize(width, height);
RenderInterface_DX11::SetViewport(width, height);
}
void Clear() { RenderInterface_DX11::Clear(video_.target()); }
void EndFrame() { RenderInterface_DX11::EndFrame(video_.target()); }
explicit operator bool() const { return video_.device() != nullptr; }
};
#else
class Renderer : public RenderInterface_GL3 {
public:
explicit Renderer(Video &) {}
};
#endif
} // namespace bmh::rml
-49
View File
@@ -1,49 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-only
# A shared visual layer for the launcher and future modern screens.
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build dependencies statically" FORCE)
foreach(feature IN ITEMS ZLIB BZIP2 PNG HARFBUZZ BROTLI)
set(FT_DISABLE_${feature} ON CACHE BOOL "Keep the bundled font engine minimal" FORCE)
endforeach()
set(SKIP_INSTALL_ALL ON)
FetchContent_Declare(freetype
GIT_REPOSITORY https://github.com/freetype/freetype.git
GIT_TAG VER-2-13-3 GIT_SHALLOW TRUE GIT_SUBMODULES "")
FetchContent_MakeAvailable(freetype)
if(NOT TARGET Freetype::Freetype)
add_library(Freetype::Freetype ALIAS freetype)
endif()
set(RMLUI_SAMPLES OFF CACHE BOOL "" FORCE)
set(RMLUI_LUA_BINDINGS OFF CACHE BOOL "" FORCE)
set(RMLUI_SVG_PLUGIN OFF CACHE BOOL "" FORCE)
set(RMLUI_LOTTIE_PLUGIN OFF CACHE BOOL "" FORCE)
FetchContent_Declare(rmlui
GIT_REPOSITORY https://github.com/mikke89/RmlUi.git
GIT_TAG 6.3 GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(rmlui)
add_library(bmh_rmlui STATIC
${rmlui_SOURCE_DIR}/Backends/RmlUi_Platform_SDL.cpp
${CMAKE_SOURCE_DIR}/src/launch/rml_video.cpp)
if(WIN32)
target_sources(bmh_rmlui PRIVATE ${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_DX11.cpp)
target_link_libraries(bmh_rmlui PUBLIC d3d11 dxgi d3dcompiler)
# Upstream resolves its multisampled UI layer into the swapchain every frame.
target_compile_definitions(bmh_rmlui PUBLIC NUM_MSAA_SAMPLES=2 NOMINMAX)
else()
target_sources(bmh_rmlui PRIVATE ${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_GL3.cpp)
endif()
target_include_directories(bmh_rmlui PUBLIC ${rmlui_SOURCE_DIR}/Backends ${CMAKE_SOURCE_DIR}/src)
target_compile_definitions(bmh_rmlui PUBLIC RMLUI_SDL_VERSION_MAJOR=2 RMLUI_NUM_MSAA_SAMPLES=0)
target_link_libraries(bmh_rmlui PUBLIC RmlUi::Core ${BMH_SDL_TARGET} PRIVATE ${CMAKE_DL_LIBS})
# The background is project artwork, and the unmodified fonts come from the
# pinned dependency. All assets are located relative to the executable at runtime.
set(launcher_assets "${CMAKE_BINARY_DIR}/assets/launcher")
file(MAKE_DIRECTORY "${launcher_assets}")
foreach(asset IN ITEMS launcher.rml theme.rcss stadium.tga)
configure_file("${CMAKE_SOURCE_DIR}/assets/launcher/${asset}" "${launcher_assets}/${asset}" COPYONLY)
endforeach()
foreach(weight IN ITEMS Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${launcher_assets}/LatoLatin-${weight}.ttf" COPYONLY)
endforeach()
install(DIRECTORY "${launcher_assets}/" DESTINATION assets/launcher COMPONENT Runtime)
-10
View File
@@ -1,10 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <string>
namespace bmh::rml {
// Safe before video initialization, including when no graphics driver is available.
// No preferences or authentication tokens are logged.
void report_start_error(const char *product, const std::string &message, bool dialog = true) noexcept;
void attach_parent_console() noexcept;
} // namespace bmh::rml
+1 -2
View File
@@ -478,7 +478,7 @@ DeskDate desk_date(uint32_t counter, const LeImage& exe) {
d.day -= month_days();
if (++d.month == 13) { d.month = 1; ++years; }
}
d.year = exe.display_start_year() + years;
d.year = 2026 + years;
return d;
}
@@ -518,7 +518,6 @@ DeskState desk_from_game(const GameState& g, const LeImage& exe, uint64_t revisi
// 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;
d.date.year += g.display_start_year - exe.display_start_year();
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;
-13
View File
@@ -1,13 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <string>
namespace bmh::ui {
// Host paths use portable separators: the legacy font's backslash glyph is Ö.
inline std::string save_directory_label(const std::filesystem::path& directory) {
const auto value = directory.generic_u8string();
return std::string(value.begin(), value.end());
}
} // namespace bmh::ui
+14 -35
View File
@@ -8,15 +8,13 @@
#include <system_error>
#include "ui/manager.hpp"
#include "ui/host_path.hpp"
#include "ui/setup.hpp"
#include "formats/fbm.hpp"
#include "content/save.hpp"
namespace bmh::ui {
namespace {
constexpr uint32_t kTextBase = ::bmh::layout::TextPointerTable;
constexpr size_t kHostFilenameBytes = 255; // Includes the selected native or legacy extension.
constexpr size_t kFilenameBytes = 251; // Host filename limit, including the four-byte .FBM suffix.
std::string path_to_utf8(const std::filesystem::path& path) {
const auto value = path.u8string();
return std::string(value.begin(), value.end());
@@ -24,10 +22,11 @@ std::string path_to_utf8(const std::filesystem::path& path) {
std::filesystem::path path_from_utf8(std::string_view value) {
return std::filesystem::path(std::u8string(value.begin(), value.end()));
}
bool valid_filename(std::string_view value, size_t maximum) {
return !value.empty() && value.size() <= maximum && value != "." && value != ".." &&
std::all_of(value.begin(), value.end(),
[](unsigned char c) { return c >= 32 && c != 127 && c != '/' && c != '\\'; });
bool valid_filename(std::string_view value) {
return !value.empty() && value.size() <= kFilenameBytes && value != "." && value != ".." &&
std::all_of(value.begin(), value.end(), [](unsigned char c) {
return c >= 32 && c != 127 && c != '/' && c != '\\';
});
}
std::string_view text_at(const TextDb& texts, uint32_t address) {
if (address < kTextBase || ((address - kTextBase) & 3u) != 0)
@@ -38,21 +37,13 @@ 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;
}
bool has_file_kind_extension(const std::filesystem::path &path, SaveLoadFileKind kind, bool native) {
bool has_file_kind_extension(const std::filesystem::path& path, SaveLoadFileKind kind) {
std::string ext = path_to_utf8(path.extension());
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (native)
return ext == (kind == SaveLoadFileKind::menu_layout ? ".oblayout"
: kind == SaveLoadFileKind::settings ? ".obsettings"
: ".obs");
return ext == (kind == SaveLoadFileKind::menu_layout ? ".men" :
kind == SaveLoadFileKind::settings ? ".ein" : ".fbm");
}
std::string_view file_kind_extension(SaveLoadFileKind kind, bool native) {
if (native)
return kind == SaveLoadFileKind::menu_layout ? ".oblayout"
: kind == SaveLoadFileKind::settings ? ".obsettings"
: ".obs";
std::string_view file_kind_extension(SaveLoadFileKind kind) {
return kind == SaveLoadFileKind::menu_layout ? ".MEN" :
kind == SaveLoadFileKind::settings ? ".EIN" : ".FBM";
}
@@ -93,14 +84,13 @@ SaveLoadScreen::SaveLoadScreen(const std::filesystem::path& data, std::filesyste
throw FormatError("save/load: unsupported state");
if (widgets_.width != 77 || widgets_.height != 112 || font_.height != 8 || footer_font_.height != 6)
throw FormatError("save/load: unsupported Original font or widget atlas");
native_ = bool(content::find(data));
std::error_code ec;
if (std::filesystem::is_directory(directory_, ec)) {
for (std::filesystem::directory_iterator it(directory_, ec), end; !ec && it != end; it.increment(ec)) {
std::error_code file_error;
const auto status = it->symlink_status(file_error);
if (!file_error && std::filesystem::is_regular_file(status) &&
has_file_kind_extension(it->path(), file_kind_, native_))
has_file_kind_extension(it->path(), file_kind_))
entries_.push_back({it->path()});
}
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
@@ -134,10 +124,7 @@ Image SaveLoadScreen::render() const {
button(out, field_x, directory_y, field_width);
button(out, field_x, filename_y, field_width);
// ISO 646-DE uses the backslash code point for Ö. Generic separators retain
// a valid host path on Windows without displaying that unrelated glyph.
const auto directory_label = original_to_utf8(text_at(texts_, ::bmh::layout::SaveLoad_Render_TextPointer3)) +
save_directory_label(directory_);
const auto directory_label = original_to_utf8(text_at(texts_, ::bmh::layout::SaveLoad_Render_TextPointer3)) + path_to_utf8(directory_);
text(out, 55, 203, directory_label, 0x6c, 140, footer_font_, true);
text(out, 55, 216, original_to_utf8(text_at(texts_, ::bmh::layout::SaveLoad_Render_TextPointer4)), 0x6c, 50, footer_font_, true);
const std::string displayed_filename = mode_ == SaveLoadMode::load && selected_ >= 0 &&
@@ -192,13 +179,7 @@ bool SaveLoadScreen::info_press(int x, int y) {
if (file_kind_ != SaveLoadFileKind::game || pending_ || info_ || x <= 52 || x >= 200 || y <= 40 ||
y >= 192 || !select_row(y)) return false;
try {
Savegame saved;
if (native_) {
saved.plain_header = content::save_information(entries_.at(size_t(selected_)).path);
saved.version = "V2.24";
saved.checksum_ok = true;
} else
saved = load_savegame(entries_.at(size_t(selected_)).path);
const auto saved = load_savegame(entries_.at(size_t(selected_)).path);
const auto& h = saved.plain_header;
if (!saved.checksum_ok || saved.version != "V2.24" || h.size() < 172 || h[0] < 1 || h[0] > 4)
throw FormatError("save/load: invalid native information header");
@@ -318,11 +299,10 @@ void SaveLoadScreen::request_action() {
entries_[size_t(selected_)].path, false, file_kind_, origin_item_id_};
return;
}
if (!valid_filename(filename_, kHostFilenameBytes - file_kind_extension(file_kind_, native_).size())) {
if (!valid_filename(filename_)) {
feedback_ = "UNGUELTIGER DATEINAME"; return;
}
auto path =
directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_, native_)));
auto path = directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_)));
// Selecting an existing mixed-case extension must overwrite that same file.
if (selected_ >= 0 && size_t(selected_) < entries_.size() &&
path_to_utf8(entries_[size_t(selected_)].path.stem()) == filename_)
@@ -396,8 +376,7 @@ bool SaveLoadScreen::key(std::string_view value) {
bool SaveLoadScreen::text(std::string_view value) {
if (info_ || mode_ != SaveLoadMode::save || !filename_focus_ || pending_ || value.empty()) return false;
const std::string next = (filename_selected_ ? std::string{} : filename_) + std::string(value);
if (!valid_filename(next, kHostFilenameBytes - file_kind_extension(file_kind_, native_).size()))
return false;
if (!valid_filename(next)) return false;
filename_ = next; filename_selected_ = false;
overwrite_armed_ = false; feedback_.clear(); return true;
}
-1
View File
@@ -67,7 +67,6 @@ private:
TextDb texts_;
SpriteFont sprite_font_;
Font footer_font_;
bool native_ = false;
bool gradient_text_ = true;
std::vector<SaveLoadEntry> entries_;
int selected_ = 0, scroll_ = 0;
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff. Show more