Build 0.2 native launcher and portable Classic runtime (by Codex)

This commit is contained in:
Codex committed 2026-10-18 11:28:51 +02:00
1 parent 3a021fc160
commit 2552528176
84 files changed
+5004 -197

No files matched your search

+3
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/binary.hpp"
#include <fstream>
@@ -7,6 +8,8 @@
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
@@ -0,0 +1,69 @@
// 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
@@ -0,0 +1,54 @@
// 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
+7
View File
@@ -1,9 +1,16 @@
// 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;
+8
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/le.hpp"
#include "formats/rule_base.hpp"
@@ -37,6 +38,13 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
}
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;
}
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; };
+20 -16
View File
@@ -18,20 +18,23 @@ namespace bmh {
class LeImage {
public:
uint32_t base() const { return base_; }
uint32_t size() const { return uint32_t(bytes_.size()); }
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
std::string cstring(uint32_t address) const;
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
const uint8_t* data(uint32_t address) const { return bytes_.data() + (address - base_); }
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
void patch(uint32_t address, const uint8_t* bytes, size_t count) {
for (size_t i = 0; i < count; ++i) bytes_.at(address - base_ + i) = bytes[i];
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];
}
// An image built by OpenBMH itself (the English FLTD.EXE translated into the German
@@ -47,8 +50,9 @@ public:
friend LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules);
private:
uint32_t base_ = 0;
Bytes bytes_;
int display_start_year_ = 2026;
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.
+6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/m3d.hpp"
#include <cstring>
@@ -35,6 +36,11 @@ 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);
}
+64
View File
@@ -0,0 +1,64 @@
// 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
@@ -0,0 +1,7 @@
// 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
@@ -0,0 +1,195 @@
// 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
@@ -0,0 +1,11 @@
// 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,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/palette.hpp"
#include "formats/binary.hpp"
@@ -6,6 +7,11 @@
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,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/textd.hpp"
#include "formats/binary.hpp"
@@ -6,6 +7,11 @@
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
+12 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/vga.hpp"
#include "formats/content.hpp"
namespace bmh {
@@ -40,6 +41,16 @@ Image decode_vga(const Bytes& d) {
return img;
}
Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); }
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));
}
} // namespace bmh