Initial public OpenBMH 0.1 source (by Codex)

This commit is contained in:
Codex committed 2026-10-16 19:36:32 +02:00
commit 558fbf166b
613 files changed
+168029

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/binary.hpp"
#include <fstream>
#include <iterator>
namespace bmh {
Bytes read_file(const std::filesystem::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw FormatError("cannot open " + path.string());
return Bytes(std::istreambuf_iterator<char>(in), {});
}
std::string iso646de_to_utf8(const char* s, size_t max_len) {
std::string out;
for (size_t i = 0; i < max_len && s[i] != '\0'; i++) {
switch (s[i]) {
case '[': out += "Ä"; break;
case '\\': out += "Ö"; break;
case ']': out += "Ü"; break;
case '{': out += "ä"; break;
case '|': out += "ö"; break;
case '}': out += "ü"; break;
case '~': out += "ß"; break;
default: out += s[i];
}
}
return out;
}
} // namespace bmh
+26
View File
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Little helpers for reading the original little-endian data files.
#include <cstdint>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <vector>
namespace bmh {
using Bytes = std::vector<uint8_t>;
struct FormatError : std::runtime_error {
using std::runtime_error::runtime_error;
};
Bytes read_file(const std::filesystem::path& path);
inline uint16_t le16(const Bytes& b, size_t o) { return uint16_t(b.at(o) | b.at(o + 1) << 8); }
inline uint32_t le32(const Bytes& b, size_t o) { return uint32_t(le16(b, o)) | uint32_t(le16(b, o + 2)) << 16; }
// Strings in the game use ISO 646-DE: [ \ ] { | } ~ are Ä Ö Ü ä ö ü ß
std::string iso646de_to_utf8(const char* s, size_t max_len = std::string::npos);
} // namespace bmh
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/fbm.hpp"
#include <algorithm>
#include <cstring>
namespace bmh {
void fbm_decrypt(uint8_t* data, size_t n, uint8_t key) {
for (size_t i = 0; i < n; i++) {
data[i] = uint8_t((data[i] - key) ^ key);
key = uint8_t(key - 0x29);
}
}
void fbm_encrypt(uint8_t* data, size_t n, uint8_t key) {
for (size_t i = 0; i < n; i++) {
data[i] = uint8_t((data[i] ^ key) + key);
key = uint8_t(key - 0x29);
}
}
Savegame load_savegame(const std::filesystem::path& path) {
Bytes d = read_file(path);
static const char magic[] = "KRON_FBM";
auto it = std::search(d.begin(), d.end(), magic, magic + 8);
if (it == d.end()) throw FormatError("FBM: magic KRON_FBM not found");
size_t m = size_t(it - d.begin());
if (m + 26 > d.size()) throw FormatError("FBM: truncated header");
Savegame s;
s.plain_header.assign(d.begin(), it);
size_t p = m + 10; // "KRON_FBM\0" + 1 byte
s.id1 = le32(d, p);
p += 4;
s.version.assign(reinterpret_cast<const char*>(&d[p]), strnlen(reinterpret_cast<const char*>(&d[p]), 6));
p += 6;
s.id2 = le32(d, p);
p += 4;
s.random = d[p++];
s.key = d[p++];
s.stream.assign(d.begin() + p, d.end() - 1);
s.checksum = d.back();
fbm_decrypt(s.stream.data(), s.stream.size(), s.key);
uint8_t sum = s.key;
for (uint8_t b : s.stream) sum = uint8_t(sum + b);
s.checksum_ok = sum == s.checksum;
return s;
}
} // namespace bmh
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// .FBM savegame container (docs/formats/FBM.md): plain header, magic, encrypted stream, checksum.
// Writer FbmDecrypt2 + NationalCoachAfterLoad, stream cipher in FbmDecrypt.
#include <cstdint>
#include <filesystem>
#include <string>
#include "formats/binary.hpp"
namespace bmh {
struct Savegame {
Bytes plain_header; // FbmDecrypt2 output (date, names for the load list)
uint32_t id1 = 0, id2 = 0;
std::string version; // "V2.24"
uint8_t random = 0, key = 0;
Bytes stream; // decrypted game state + trailer blocks
uint8_t checksum = 0;
bool checksum_ok = false;
};
// Stream cipher: encrypt c = (b ^ k) + k, decrypt b = (c - k) ^ k, then k -= 0x29
void fbm_decrypt(uint8_t* data, size_t n, uint8_t key);
void fbm_encrypt(uint8_t* data, size_t n, uint8_t key);
Savegame load_savegame(const std::filesystem::path& path);
} // namespace bmh
+58
View File
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/font.hpp"
namespace bmh {
Font load_font(const std::filesystem::path& path) {
Bytes d = read_file(path);
if (d.size() < 28) throw FormatError("FNT: file too short");
Font f;
f.height = le16(d, 0);
f.flags = d[3];
f.nominal_width = le16(d, 4);
f.baseline = le16(d, 6);
f.lo_char = d[8];
f.hi_char = d[9];
f.modulo = le16(d, 16);
size_t n = size_t(f.hi_char - f.lo_char + 2);
size_t bmp = 28, loc = bmp + size_t(f.height) * f.modulo, spc = loc + n * 4;
size_t end = spc + (f.flags == 2 ? 0 : n * 2);
if (end != d.size()) throw FormatError("FNT: size mismatch in " + path.string());
f.bitmap.assign(d.begin() + bmp, d.begin() + loc);
for (size_t i = 0; i < n; i++) {
int16_t adv = f.flags == 2 ? int16_t(f.nominal_width) : int16_t(le16(d, spc + i * 2));
f.glyphs.push_back({le16(d, loc + i * 4), le16(d, loc + i * 4 + 2), adv});
}
return f;
}
const Font::Glyph& Font::glyph(uint8_t c) const {
if (c < lo_char || c > hi_char) return glyphs.back();
return glyphs[c - lo_char];
}
int Font::text_width(std::string_view text) const {
int w = 0;
for (char c : text) w += glyph(uint8_t(c)).advance;
return w;
}
int Font::draw(Image& target, int x, int y, std::string_view text, uint8_t color) const {
for (char c : text) {
const Glyph& g = glyph(uint8_t(c));
for (int row = 0; row < height; row++) {
for (int b = 0; b < g.bit_width; b++) {
int bit = g.bit_offset + b;
if (!(bitmap[size_t(row) * modulo + bit / 8] & (0x80 >> (bit % 8)))) continue;
int px = x + b, py = y + row;
if (px >= 0 && py >= 0 && px < target.width && py < target.height) target.at(px, py) = color;
}
}
x += g.advance;
}
return x;
}
} // namespace bmh
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// .FNT bitmap fonts, Amiga TextFont layout (docs/formats/FNT.md), original loader Glyph
#include <cstdint>
#include <filesystem>
#include <string_view>
#include <vector>
#include "formats/vga.hpp"
namespace bmh {
struct Font {
int height = 0;
int baseline = 0;
int nominal_width = 0;
uint8_t flags = 0;
uint8_t lo_char = 0, hi_char = 0;
int modulo = 0;
std::vector<uint8_t> bitmap; // height * modulo, 1 bpp MSB first
struct Glyph { uint16_t bit_offset, bit_width; int16_t advance; };
std::vector<Glyph> glyphs; // hi - lo + 2, last one = replacement glyph
const Glyph& glyph(uint8_t c) const;
int text_width(std::string_view text) const;
// text in the game's ISO 646-DE encoding; returns the x after the last glyph
int draw(Image& target, int x, int y, std::string_view text, uint8_t color) const;
};
Font load_font(const std::filesystem::path& path);
} // namespace bmh
+140
View File
@@ -0,0 +1,140 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/le.hpp"
#include "formats/rule_base.hpp"
#include <algorithm>
#include <fstream>
#include <vector>
namespace bmh {
namespace {
struct Object {
uint32_t vsize, base, flags, page_index, page_count;
};
} // namespace
std::string LeImage::cstring(uint32_t address) const {
std::string s;
while (contains(address) && u8(address) != 0) s.push_back(char(u8(address++)));
return s;
}
namespace {
constexpr char kImageMagic[14] = "OPENBMH-IMAGE"; // 13 characters and the NUL
}
void save_image(const LeImage& image, const std::filesystem::path& path) {
Bytes out(kImageMagic, kImageMagic + sizeof kImageMagic);
for (uint32_t v : {image.base(), image.size()})
for (int b = 0; b < 4; ++b) out.push_back(uint8_t(v >> (8 * b)));
out.insert(out.end(), image.bytes().begin(), image.bytes().end());
std::ofstream file(path, std::ios::binary | std::ios::trunc);
file.write(reinterpret_cast<const char*>(out.data()), std::streamsize(out.size()));
if (!file) throw FormatError("cannot write the OpenBMH image");
}
LeImage load_le(const std::filesystem::path& path) {
const Bytes raw = read_file(path);
if (raw.size() >= sizeof kImageMagic + 8 && std::equal(kImageMagic, kImageMagic + sizeof kImageMagic, raw.begin())) {
const auto word = [&](size_t at) { return uint32_t(raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16) | uint32_t(raw[at + 3]) << 24; };
const uint32_t base = word(sizeof kImageMagic), size = word(sizeof kImageMagic + 4);
if (raw.size() != sizeof kImageMagic + 8 + size_t(size)) throw FormatError("OpenBMH image: wrong size");
LeImage img = LeImage::from_bytes(base, Bytes(raw.begin() + sizeof kImageMagic + 8, raw.end()));
apply_rule_base(img);
return img;
}
auto u8 = [&](size_t o) -> uint32_t {
if (o >= raw.size()) throw FormatError("LE: read beyond the file");
return raw[o];
};
auto u16 = [&](size_t o) { return u8(o) | u8(o + 1) << 8; };
auto u32 = [&](size_t o) { return u16(o) | uint32_t(u16(o + 2)) << 16; };
const size_t le = u32(0x3c);
if (u16(le) != 0x454c) throw FormatError("LE: no LE header");
auto h = [&](size_t off) { return u32(le + off); };
const uint32_t pages = h(0x14), page_size = h(0x28), last_page = h(0x2c);
const size_t object_table = le + h(0x40), page_map = le + h(0x48);
const size_t fixup_pages = le + h(0x68), fixup_records = le + h(0x6c);
const uint32_t objects = h(0x44), data_pages = h(0x80);
std::vector<Object> obj;
uint32_t lo = 0xFFFFFFFFu, hi = 0;
for (uint32_t i = 0; i < objects; i++) {
const size_t o = object_table + i * 24;
Object ob{u32(o), u32(o + 4), u32(o + 8), u32(o + 12), u32(o + 16)};
obj.push_back(ob);
const uint32_t span = std::max(ob.vsize, ob.page_count * page_size);
lo = std::min(lo, ob.base);
hi = std::max(hi, ob.base + (span + page_size - 1) / page_size * page_size);
}
LeImage img;
img.base_ = lo;
img.bytes_.assign(hi - lo, 0);
std::vector<uint32_t> page_address(pages + 1, 0);
for (const Object& ob : obj)
for (uint32_t p = 0; p < ob.page_count; p++) {
const uint32_t logical = ob.page_index + p;
const size_t e = page_map + (logical - 1) * 4;
const uint32_t file_page = u8(e) << 16 | u8(e + 1) << 8 | u8(e + 2);
const uint32_t va = ob.base + p * page_size;
if (logical <= pages) page_address[logical] = va;
if (u8(e + 3) != 0) continue; // not a loaded page
size_t size = file_page == pages ? last_page : page_size;
const size_t src = data_pages + size_t(file_page - 1) * page_size;
size = std::min(size, raw.size() - src);
std::copy(raw.begin() + long(src), raw.begin() + long(src + size), img.bytes_.begin() + (va - lo));
}
auto put16 = [&](size_t pos, uint32_t v) {
img.bytes_[pos] = uint8_t(v), img.bytes_[pos + 1] = uint8_t(v >> 8);
};
auto put32 = [&](size_t pos, uint32_t v) { put16(pos, v), put16(pos + 2, v >> 16); };
for (uint32_t pg = 1; pg <= pages; pg++) {
size_t r = fixup_records + u32(fixup_pages + (pg - 1) * 4);
const size_t end = fixup_records + u32(fixup_pages + pg * 4);
while (r < end) {
const uint32_t src = u8(r), flags = u8(r + 1);
r += 2;
const uint32_t type = src & 0x0f;
const bool list = (src & 0x20) != 0;
uint32_t count = 1;
int16_t source_offset = 0;
if (list) count = u8(r++);
else source_offset = int16_t(u16(r)), r += 2;
if (flags & 3) throw FormatError("LE: external fixup");
uint32_t target_object;
if (flags & 0x40) target_object = u16(r), r += 2;
else target_object = u8(r++);
uint32_t target_offset = 0;
if (type != 0x02) {
if (flags & 0x10) target_offset = u32(r), r += 4;
else target_offset = u16(r), r += 2;
}
std::vector<int16_t> offsets;
if (list)
for (uint32_t k = 0; k < count; k++) offsets.push_back(int16_t(u16(r))), r += 2;
else
offsets.push_back(source_offset);
const uint32_t target = obj.at(target_object - 1).base + target_offset;
for (int16_t so : offsets) {
const uint32_t sa = page_address[pg] + uint32_t(int32_t(so));
const int64_t pos = int64_t(sa) - lo;
if (pos < 0 || pos + 4 > int64_t(img.bytes_.size())) continue;
switch (type) {
case 0x07: put32(size_t(pos), target); break;
case 0x08: put32(size_t(pos), target - (sa + 4)); break;
case 0x05: put16(size_t(pos), target); break;
case 0x02: put16(size_t(pos), target_object); break;
case 0x06: put32(size_t(pos), target), put16(size_t(pos) + 4, target_object); break;
default: break;
}
}
}
}
apply_rule_base(img);
return img;
}
} // namespace bmh
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The original program itself (BMH.exe, a DOS/4GW "LE" linear executable) as a data file.
//
// Many tables and all message texts of the game live in the data object of BMH.exe. Like
// the other original files it is read at runtime, never shipped: load_le() loads every
// object at its link address and applies the internal fixups, so addresses and stored
// pointers are the "LE addresses" used throughout the port (e.g. MatchdaySetup_Attendance_ExecutableField), exactly as in
// the disassembly (runtime verification produces the same image for Ghidra).
#include <cstdint>
#include <filesystem>
#include <string>
#include "formats/binary.hpp"
namespace bmh {
class LeImage {
public:
uint32_t base() const { return base_; }
uint32_t size() const { return uint32_t(bytes_.size()); }
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
std::string cstring(uint32_t address) const;
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
const uint8_t* data(uint32_t address) const { return bytes_.data() + (address - base_); }
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
void patch(uint32_t address, const uint8_t* bytes, size_t count) {
for (size_t i = 0; i < count; ++i) bytes_.at(address - base_ + i) = bytes[i];
}
// An image built by OpenBMH itself (the English FLTD.EXE translated into the German
// address space, launch/fltd.hpp).
static LeImage from_bytes(uint32_t base, Bytes bytes) {
LeImage img;
img.base_ = base;
img.bytes_ = std::move(bytes);
return img;
}
const Bytes& bytes() const { return bytes_; }
friend LeImage load_le(const std::filesystem::path& path);
private:
uint32_t base_ = 0;
Bytes bytes_;
};
// OpenBMH deviates from the original: applies a shared supported rule profile when loading editions with different rule-table values.
// Throws FormatError for files that are not LE executables or use external fixups.
// A German BMH.EXE is loaded with the OpenBMH rule base applied (formats/rule_base.hpp):
// every edition plays by the supported rule profile rule values.
LeImage load_le(const std::filesystem::path& path);
// The OpenBMH image format: "OPENBMH-IMAGE" NUL, u32 base, u32 size, the bytes. load_le()
// reads it as well, so a translated image can stand in for BMH.exe in a data directory.
void save_image(const LeImage& image, const std::filesystem::path& path);
} // namespace bmh
+72
View File
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/m3d.hpp"
#include <cstring>
namespace bmh {
namespace {
struct Reader {
const Bytes& d;
size_t pos = 0;
Bytes take(size_t n) {
if (pos + n > d.size()) throw FormatError("M3D: unexpected end of file");
Bytes b(d.begin() + pos, d.begin() + pos + n);
pos += n;
return b;
}
};
std::vector<std::string> split_pool(const Bytes& pool) {
std::vector<std::string> out;
size_t start = 0;
for (size_t i = 0; i < pool.size(); i++)
if (pool[i] == 0) { out.emplace_back(reinterpret_cast<const char*>(pool.data() + start), i - start); start = i + 1; }
return out;
}
std::string pool_string(const Bytes& pool, size_t offset) {
if (offset >= pool.size()) throw FormatError("M3D: string offset out of range");
const char* s = reinterpret_cast<const char*>(pool.data() + offset);
return std::string(s, strnlen(s, pool.size() - offset));
}
} // namespace
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
Bytes d = read_file(path);
Reader r{d};
Bytes lens = r.take(8);
size_t len_clubs = le16(lens, 0), len_players = le16(lens, 2), len_refs = le16(lens, 4), len_stadiums = le16(lens, 6);
Database db;
db.raw_player_bonus_values = r.take(c.n66 + 0x32);
Bytes club_pool = r.take(len_clubs);
Bytes player_pool = r.take(len_players);
Bytes ref_pool = r.take(len_refs), stadium_pool = r.take(len_stadiums);
db.referees = split_pool(ref_pool);
db.stadiums = split_pool(stadium_pool);
Bytes club_ofs = r.take(c.clubs * 2);
Bytes player_ofs = r.take(c.players * 2);
db.pools[0] = club_pool, db.pools[1] = player_pool, db.pools[2] = ref_pool, db.pools[3] = stadium_pool;
db.raw_club_name_offsets = club_ofs, db.raw_player_name_offsets = player_ofs;
db.raw_database_metadata = r.take(100);
db.raw_club_auxiliary_words = r.take(c.n42 * 2);
db.raw_club_badge_selectors = r.take(c.clubs * 2);
db.raw_foreign_club_strength = r.take(0xFB);
db.raw_league_auxiliary_bytes = r.take(0xBD);
db.raw_referee_properties = r.take(0x32);
db.raw_club_kit_selectors = r.take(0x1A3);
db.raw_club_short_name_offsets = r.take(0xA8);
db.squad_list = r.take((c.n66 - 4) * 2 + 0x6C);
Bytes w35c = r.take(c.players * 4), w368 = r.take(c.players * 4), w364 = r.take(c.players * 4);
if (r.pos != d.size()) throw FormatError("M3D: trailing data, table sizes do not match");
for (uint32_t i = 0; i < c.clubs; i++) db.club_names.push_back(pool_string(club_pool, le16(club_ofs, i * 2)));
for (uint32_t i = 0; i < c.players; i++)
db.players.push_back({pool_string(player_pool, le16(player_ofs, i * 2)), le32(w35c, i * 4), le32(w368, i * 4), le32(w364, i * 4)});
return db;
}
} // namespace bmh
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// M3D.MAN master database (docs/formats/M3D.md), read in CareerFirstSteps2
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
#include "formats/binary.hpp"
namespace bmh {
// Table sizes, initial values of CareerSession_DataDirectory_RuntimeField / CareerSession_DataDirectory_RuntimeField3 / CareerSession_DataDirectory_RuntimeField2 / CareerSession_DataDirectory_RuntimeField4 in BMH.exe V2.24
struct DbCounts {
uint32_t clubs = 419;
uint32_t players = 2574;
uint32_t n42 = 168;
uint32_t n66 = 3096;
};
// A player as stored in the three parallel u32 tables of the database/savegame
// (named after the globals holding them in the original: *PlayerConditionTechniqueForm, *PlayerSkillWords, *PlayerIdentityWords).
// Player ids are 12 bit (squad lists store id | flags << 12).
//
// w35c bits 0- 6 form (FO) shown in the squad screen
// bits 7-13 technique (TE)
// bits 14-20 condition (KO)
// bits 21-26 unknown (0-63)
// bits 27-31 unknown, read by the code
// w368 bits 0-13 seven skills, 2 bits each (0-3), order: teamplay, speed, shooting,
// passing, tackling, free kick, corner (texts 135-141, "T.S.S.P.Z.F.E.")
// bits 14-26 unknown / runtime state
// bits 27-31 nationality (0 = Germany)
// w364 bits 0- 1 position: 0 goalkeeper, 1 defender, 2 midfielder, 3 forward
// bits 2-20 runtime state (injuries etc., not yet decoded)
// bits 21-25 age - 16
// bits 26-31 unknown
//
// The values in M3D.MAN differ from a running game: they are varied when a career starts.
struct Player {
std::string name; // ISO 646-DE
uint32_t w35c = 0, w368 = 0, w364 = 0;
enum Skill { TEAMPLAY, SPEED, SHOOTING, PASSING, TACKLING, FREE_KICK, CORNER };
int form() const { return int(w35c & 0x7F); }
int technique() const { return int(w35c >> 7 & 0x7F); }
int condition() const { return int(w35c >> 14 & 0x7F); }
int skill(Skill s) const { return int(w368 >> (2 * s) & 3); } // 0-3
int nationality() const { return int(w368 >> 27); } // 0 = Germany
int position() const { return int(w364 & 3); } // 0 GK, 1 DEF, 2 MID, 3 FWD
int age() const { return int(w364 >> 21 & 0x1F) + 16; }
// Strength "STÄ", Strength: form scales the sum of technique and condition.
// display = true gives the 0-99 value shown in the squad screen.
int strength(bool display = true) const {
int raw = ((form() >> 3) + 0x5E) * (technique() + condition()) / 100;
if (!display) return raw;
return raw / 2 > 99 ? 99 : raw / 2;
}
};
struct Database {
std::vector<std::string> club_names;
std::vector<std::string> referees;
std::vector<std::string> stadiums;
std::vector<Player> players;
Bytes squad_list; // *SquadSlots, u16 entries (& 0xFFF = player id)
// The data as read into memory (CareerFirstSteps2): string pools (0 clubs, 1 players, 2 referees,
// 3 stadiums) and their offset tables (*ClubIdentities clubs, *PlayerNameOffsets players).
Bytes pools[4];
Bytes raw_club_name_offsets, raw_player_name_offsets;
Bytes raw_player_bonus_values, raw_database_metadata, raw_club_auxiliary_words, raw_club_badge_selectors, raw_foreign_club_strength, raw_league_auxiliary_bytes, raw_referee_properties, raw_club_kit_selectors, raw_club_short_name_offsets;
};
Database load_database(const std::filesystem::path& path, const DbCounts& counts = {});
} // namespace bmh
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/palette.hpp"
#include "formats/binary.hpp"
namespace bmh {
Palette load_palette(const std::filesystem::path& path) {
Bytes b = read_file(path);
if (b.size() < 768) throw FormatError("palette too short: " + path.string());
Palette p;
for (int i = 0; i < 256; i++) {
auto c = [&](int k) { return uint32_t(vga_dac_rgb8(b[i * 3 + k])); };
p.argb[i] = 0xFF000000u | c(0) << 16 | c(1) << 8 | c(2);
}
return p;
}
uint8_t Palette::nearest(uint8_t r, uint8_t g, uint8_t b) const {
int best = 0, best_dist = INT32_MAX;
for (int i = 0; i < 256; i++) {
int dr = int(argb[i] >> 16 & 0xFF) - r, dg = int(argb[i] >> 8 & 0xFF) - g, db = int(argb[i] & 0xFF) - b;
int dist = dr * dr + dg * dg + db * db;
if (dist < best_dist) best = i, best_dist = dist;
}
return uint8_t(best);
}
} // namespace bmh
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// M3PC.COL: 256 x RGB, 6 bit per channel (docs/formats/COL.md)
#include <array>
#include <cstdint>
#include <filesystem>
namespace bmh {
struct Palette {
std::array<uint32_t, 256> argb{}; // 0xAARRGGBB, 8 bit per channel
// index of the palette entry closest to the given colour
uint8_t nearest(uint8_t r, uint8_t g, uint8_t b) const;
};
// Expand the low six VGA-DAC bits to the nearest RGB8 level. Verified against
// the running Original; truncation darkens many colours by one channel step.
constexpr uint8_t vga_dac_rgb8(uint8_t channel) {
return uint8_t(((channel & 0x3f) * 255u + 31u) / 63u);
}
Palette load_palette(const std::filesystem::path& path);
} // namespace bmh
+44
View File
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/rule_base.hpp"
#include <cstdint>
#include <vector>
namespace bmh {
namespace {
struct RuleBytes {
uint32_t address;
std::vector<uint8_t> bytes;
};
// OpenBMH deviates from the original: normalizes live-scene defaults, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit across supported editions.
// Every byte here differs in at least one German edition from supported rule profile 2026-27 and is read by
// the engine as a rule (runtime verification exe_diff over the ten editions, minus texts, calendar,
// season values and screen positions).
const std::vector<RuleBytes> kRuleBase = {
{::bmh::layout::LiveSceneOptions, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01}}, // live scene options (CareerSession_DispatchLiveTactic_RuntimeField2, RerateTeam)
// (The training camp resorts DeskActions_ConfigureTrainingCampData_RuntimeField.. - qualities and prices - are content, not rules:
// every edition, the English one too, keeps its own resorts;
{::bmh::layout::LeagueStrengthRanges, {0x47, 0x5d, 0x31, 0x47, 0x1c, 0x31, 0x1c, 0x31, 0x0a, 0x1c}}, // league strength ranges (LeagueStrengthRanges)
{::bmh::layout::AdditionalLeagueStrengthRanges, {0x5f, 0x5a, 0x5f, 0x4b, 0x5f}}, // league strength ranges
{::bmh::layout::FinalLeagueStrengthMaximum, {0x5f}}, // league strength ranges
{::bmh::layout::RuleOptionDefaults, {0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x04, 0x02, 0x03, 0x02, 0x03, 0x06, 0x08, 0x06, 0x08, 0x0a, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x1e}}, // option defaults (ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField4...)
{::bmh::layout::StadiumPriceTable, {0xa0, 0x25, 0x26, 0x00, 0xa0, 0xf0, 0x19, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0xc8, 0x10, 0x00, 0x60, 0xe3, 0x16, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0xc0, 0x45, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0x30, 0x57, 0x05, 0x00, 0xa0, 0xbb, 0x0d, 0x00, 0xb0, 0x71, 0x0b, 0x00, 0x40, 0x77, 0x1b, 0x00, 0xc0, 0x91, 0x21, 0x00, 0x30, 0x57, 0x05, 0x00, 0xc0, 0x27, 0x09, 0x00, 0x70, 0x64, 0x08, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0xd8, 0xb8, 0x05, 0x00, 0xe0, 0x93, 0x04, 0x00, 0x30, 0x57, 0x05, 0x00, 0xd0, 0x07, 0xb8, 0x0b, 0xb8, 0x0b, 0x40, 0x1f, 0xa0, 0x0f, 0xb8, 0x0b}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField)
{::bmh::layout::AdditionalStadiumPrices, {0x88, 0x13, 0xc0, 0x12, 0x60, 0x09, 0x40, 0x1f}}, // stadium prices (CareerSession_DispatchStadium_RuntimeField)
{::bmh::layout::StadiumBlockCapacities, {0x12, 0x08, 0x0e, 0x08, 0x12, 0x08, 0x0e}}, // stadium block places (CareerSession_Invalid_RuntimeField)
{::bmh::layout::ComputerBettingLimits, {0x33, 0x20, 0x50, 0x74}}, // computer tip gaps (CareerSession_DispatchLeagueTableControl_RuntimeField)
{::bmh::layout::ForeignPlayerLimitEnabled, {0x00}}, // substitution rule switch (ForeignPlayerLimitEnabled)
};
} // namespace
void apply_rule_base(LeImage& exe) {
// only the German data object has these addresses
if (exe.base() != 0x10000 || !exe.contains(::bmh::layout::GermanDataSegmentBegin) || !exe.contains(::bmh::layout::GermanDataCompatibilityEnd)) return;
for (const RuleBytes& r : kRuleBase) exe.patch(r.address, r.bytes.data(), r.bytes.size());
}
} // namespace bmh
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// One engine uses a shared rule profile across supported editions.
// OpenBMH deviates from the original: normalizes live-scene options, league
// strength ranges, option defaults, stadium prices and capacities, betting limits,
// and the foreign-player limit. Texts, currency, calendar, league structure, screen
// positions, season values, and edition-specific resort content stay loaded from data.
#include "formats/le.hpp"
namespace bmh {
// Applies the shared rule profile to compatible German executable images.
// Images without the matching data segment are left unchanged.
void apply_rule_base(LeImage& exe);
} // namespace bmh
+202
View File
@@ -0,0 +1,202 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/savestate.hpp"
#include <algorithm>
#include <string>
namespace bmh {
namespace {
// Size of a block, either fixed or derived from a database table size.
enum class Count { None, Clubs, Players, N42, N66, Teams, TeamsPlusCups };
struct BlockDef {
uint32_t address;
bool heap;
uint32_t fixed; // fixed part of the size
Count count; // table size multiplied by factor, added to fixed
uint32_t factor;
bool only_if_pointer; // block exists only if the preceding pointer value is non-zero
};
// The exact order of NationalCoachAfterLoad. Addresses are the globals in BMH.exe V2.24.
// Sizes marked with a Count depend on the master database:
// Clubs = CareerSession_DataDirectory_RuntimeField (419) Players = CareerSession_DataDirectory_RuntimeField3 (2574)
// N42 = CareerSession_DataDirectory_RuntimeField2 (168) N66 = CareerSession_DataDirectory_RuntimeField4 (3096)
// Teams = CareerSession_DispatchLineup_RuntimeField (138, teams in league play)
// TeamsPlusCups = CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 (138 + 30)
constexpr BlockDef kBlocks[] = {
{::bmh::layout::Cup_AdvanceCup_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::LiveMatchday_FormatError_RuntimeField14, false, 6, Count::None, 0, false},
{::bmh::layout::ManagerRecords, false, 0x373c, Count::None, 0, false}, // 5 manager records of 0xB0C bytes
{::bmh::layout::Loans, false, 0x1e0, Count::None, 0, false},
{::bmh::layout::ManagerMatchHistory, false, 0x20d0, Count::None, 0, false}, // form history: 5 managers x 168 teams x 10
{::bmh::layout::MatchdayGroupDescriptors, false, 0x4e0, Count::None, 0, false}, {::bmh::layout::ManagerAutomation, false, 0x14, Count::None, 0, false},
{::bmh::layout::Desktops, false, 0x10e0, Count::None, 0, false}, // desktop layouts (.MEN), 5 x 0x360
{::bmh::layout::CareerSession_DispatchToto_RuntimeField, false, 1, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField4, false, 1, Count::None, 0, false},
{::bmh::layout::CalendarState_FormatError_RuntimeField3, false, 2, Count::None, 0, false}, {::bmh::layout::ActiveManager, false, 1, Count::None, 0, false}, // active manager
{::bmh::layout::CareerSession_RuntimeError_RuntimeField4, false, 1, Count::None, 0, false},
{::bmh::layout::LeaguePresentationOptions, false, 0xb4, Count::None, 0, false}, // button settings (.EIN)
{::bmh::layout::FriendlyTeams, false, 0x78, Count::None, 0, false}, {::bmh::layout::FriendlyDays, false, 0x3c, Count::None, 0, false},
{::bmh::layout::Cup_AdvanceCup_ExecutableField, false, 0x50, Count::None, 0, false}, {::bmh::layout::MatchdaySetup_IndoorTournamentDraw_RuntimeField, false, 0x50, Count::None, 0, false},
{::bmh::layout::Placements, false, 0x50, Count::None, 0, false}, {::bmh::layout::ActiveSelectors, false, 8, Count::None, 0, false},
{::bmh::layout::Career_CareerAddManager_RuntimeField2, false, 0x90, Count::None, 0, false}, {::bmh::layout::DeskActions_SubmitPoolsCoupon_RuntimeField, false, 0x2c, Count::None, 0, false},
{::bmh::layout::NextDeskManager, false, 8, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField8, false, 10, Count::None, 0, false},
{::bmh::layout::DeskPosition, false, 1, Count::None, 0, false}, {::bmh::layout::DeskRecords_Teams_RuntimeField, false, 0x114, Count::None, 0, false},
{::bmh::layout::CareerSession_FormatError_RuntimeField7, false, 2, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField6, false, 6, Count::None, 0, false},
{::bmh::layout::CurrentMatchday, false, 4, Count::None, 0, false}, // seed of the game RNG (GameRandom)
{::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3, false, 1, Count::None, 0, false}, {::bmh::layout::CoachActive, false, 1, Count::None, 0, false},
{::bmh::layout::OriginalManagerCount, false, 1, Count::None, 0, false}, {::bmh::layout::CareerSession_Invalid_RuntimeField2, false, 4, Count::None, 0, false}, // saved RNG seed
{::bmh::layout::CareerDuration, false, 1, Count::None, 0, false}, {::bmh::layout::GameMode, false, 1, Count::None, 0, false},
{::bmh::layout::CompetitionSelection, false, 4, Count::None, 0, false}, {::bmh::layout::ManagerCount, false, 1, Count::None, 0, false}, // number of managers
{::bmh::layout::SavedCompetition, false, 4, Count::None, 0, false}, {::bmh::layout::Difficulty, false, 1, Count::None, 0, false},
{::bmh::layout::StockExchange, false, 0x450, Count::None, 0, false}, {::bmh::layout::FundBlock, false, 0xa8, Count::None, 0, false},
{::bmh::layout::Coupon, false, 100, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField2, false, 3, Count::None, 0, false},
{::bmh::layout::Savestate_Layout_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::AdGroupId, false, 1, Count::None, 0, false},
{::bmh::layout::OfferSlots, false, 0x10, Count::None, 0, false}, {::bmh::layout::ForeignClubStrength, false, 0xfb, Count::None, 0, false},
{::bmh::layout::Career_Put_ExecutableField3, false, 0xbd, Count::None, 0, false}, {::bmh::layout::ClubShortNameOffsets, false, 0xa8, Count::None, 0, false},
{::bmh::layout::ClubKitSelectors, false, 0x1a3, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField7, false, 0x18, Count::None, 0, false},
{::bmh::layout::ClubInfo_FormatError_RuntimeField, false, 0x420, Count::None, 0, false}, {::bmh::layout::Career_CareerManagersEnd_RuntimeField, false, 0x18, Count::None, 0, false},
{::bmh::layout::ClubInfo_FormatError_RuntimeField2, false, 0xc, Count::None, 0, false}, {::bmh::layout::DeskActions_Unsupported_RuntimeField, false, 4, Count::None, 0, false},
{::bmh::layout::Career_RemoveJoinLoans_RuntimeField, false, 800, Count::None, 0, false}, {::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField, false, 200, Count::None, 0, false},
{::bmh::layout::ManagerRatings, false, 0xf0, Count::None, 0, false}, {::bmh::layout::DaysIntoSeason, false, 2, Count::None, 0, false}, // day since 1 July
{::bmh::layout::Career_CompetitionPointers_ExecutableField, false, 0x7e, Count::None, 0, false}, {::bmh::layout::Field, false, 0x100, Count::None, 0, false},
{::bmh::layout::CalendarDay, false, 4, Count::None, 0, false}, {::bmh::layout::SeasonIndex, false, 2, Count::None, 0, false},
{::bmh::layout::Savestate_Layout_ExecutableField5, false, 2, Count::None, 0, false}, {::bmh::layout::CompetitionCalendar, false, 0x2dc, Count::None, 0, false}, // calendar, u16/day
{::bmh::layout::Postponed, false, 0xf0, Count::None, 0, false}, {::bmh::layout::LeagueTableDisplayModes, false, 8, Count::None, 0, false},
{::bmh::layout::CareerSession_FormatError_ExecutableField, false, 8, Count::None, 0, false}, {::bmh::layout::ManagerSettings, false, 8, Count::None, 0, false},
{::bmh::layout::CareerSession_DispatchOtherGames_RuntimeField, false, 4, Count::None, 0, false}, {::bmh::layout::CareerSession_AnyOf_ExecutableField, false, 8, Count::None, 0, false},
{::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2, false, 4, Count::None, 0, false}, {::bmh::layout::ManagerMailbox, true, 0x1900, Count::None, 0, false},
{::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField, false, 4, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField3, false, 8, Count::None, 0, false},
{::bmh::layout::Flags, false, 0xc, Count::None, 0, false}, {::bmh::layout::Formations, false, 0x580, Count::None, 0, false}, // M3.DAT
{::bmh::layout::PlayerDevelopmentBalance, false, 4, Count::None, 0, false}, {::bmh::layout::PlayerBonuses, true, 0x36, Count::N66, 1, false},
{::bmh::layout::EditorList, false, 0xf20, Count::None, 0, false}, {::bmh::layout::Field0, false, 0x70, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13, false, 0x68, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, false, 0x100, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22, false, 0x80, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23, false, 0x80, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, false, 0x80, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26, false, 0x40, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21, false, 0x40, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, false, 0x6c, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17, false, 0x9a, Count::None, 0, false}, {::bmh::layout::Savestate_Layout_ExecutableField4, false, 0x62, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, false, 4, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, false, 2, Count::None, 0, false},
{::bmh::layout::Teams, false, 0x20, Count::None, 0, false}, {::bmh::layout::MatchdayGroupWorkspace, false, 0x20, Count::None, 0, false},
{::bmh::layout::Savestate_Layout_ExecutableField6, false, 1, Count::None, 0, false}, {::bmh::layout::EventPasses, false, 1, Count::None, 0, false},
{::bmh::layout::LeagueResults, false, 0xd5c, Count::None, 0, false}, // match results, see game/schedule.hpp
{::bmh::layout::LeagueRoundCounters, false, 9, Count::None, 0, false},
{::bmh::layout::TeamMorale, true, 0, Count::Clubs, 1, false}, {::bmh::layout::ClubBadgeSelectors, true, 0, Count::Clubs, 2, false},
{::bmh::layout::TeamFlags, true, 0, Count::Clubs, 2, false}, {::bmh::layout::ClubIdentities, true, 0, Count::Clubs, 2, false}, // club name offsets
{::bmh::layout::PlayerNameOffsets, true, 0, Count::Players, 2, false}, // player name offsets
{::bmh::layout::MasterDatabaseMetadata, true, 100, Count::None, 0, false}, {::bmh::layout::ClubAuxiliaryWords, true, 0, Count::N42, 2, false},
{::bmh::layout::LeagueRankHistory, true, 0, Count::Teams, 0x1a, false}, // table position history, 26 bytes per team
{::bmh::layout::Titles, false, 0x384, Count::None, 0, false}, {::bmh::layout::Cup_AdvanceCup_RuntimeField6, false, 6, Count::None, 0, false},
{::bmh::layout::ClubAuxiliaryBytes, true, 0, Count::TeamsPlusCups, 1, false},
{::bmh::layout::CupTable, false, 0x5a0, Count::None, 0, false}, {::bmh::layout::SquadSlots, true, 0x6c, Count::N66, 2, false}, // squad lists
{::bmh::layout::PlayerConditionTechniqueForm, true, 0, Count::Players, 4, false}, // player word 1: form, technique, condition
{::bmh::layout::PlayerCards, true, 0, Count::Players, 2, false},
{::bmh::layout::PlayerSkillWords, true, 0, Count::Players, 4, false}, // player word 2: skills, nationality
{::bmh::layout::PlayerIdentityWords, true, 0, Count::Players, 4, false}, // player word 3: position, age
{::bmh::layout::TacticsBoards, false, 0x2940, Count::None, 0, false}, {::bmh::layout::TournamentName, true, 0x24, Count::None, 0, false},
{::bmh::layout::Career_EuropeanClub_ExecutableField, false, 1, Count::None, 0, false}, {::bmh::layout::Career_EuropeanClub_ExecutableField2, false, 1, Count::None, 0, false},
{::bmh::layout::Career_EuropeanClub_ExecutableField3, false, 1, Count::None, 0, false}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24, false, 0x28, Count::None, 0, false},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29, false, 0x14, Count::None, 0, false}, {::bmh::layout::ClubSeasonRecords, false, 4, Count::None, 0, false},
{::bmh::layout::ClubSeasonRecords, true, 0x3090, Count::None, 0, true}, // club records (168 x 74), only if pointer != 0
};
} // namespace
SaveState::SaveState(const Bytes& stream, const DbCounts& c) : stream_(stream) {
// Teams in league play and cup-only teams are not part of DbCounts yet;
// these are the V2.24 values (CareerSession_DispatchLineup_RuntimeField, CareerSession_InstallLeagueSizes_RuntimeField6).
constexpr uint32_t kTeams = 138, kCupTeams = 30;
size_t pos = 0;
uint32_t last_pointer = 0;
for (const BlockDef& d : kBlocks) {
if (d.only_if_pointer && last_pointer == 0) continue;
uint32_t n = 0;
switch (d.count) {
case Count::None: n = 0; break;
case Count::Clubs: n = c.clubs; break;
case Count::Players: n = c.players; break;
case Count::N42: n = c.n42; break;
case Count::N66: n = c.n66; break;
case Count::Teams: n = kTeams; break;
case Count::TeamsPlusCups: n = kTeams + kCupTeams; break;
}
size_t size = d.fixed + size_t(n) * d.factor;
if (pos + size > stream.size()) throw FormatError("savegame: state blocks exceed stream");
if (d.address == ::bmh::layout::ClubSeasonRecords && !d.heap) last_pointer = le32(stream, pos);
index_.try_emplace(d.address, blocks_.size());
blocks_.push_back({d.address, d.heap, pos, size});
pos += size;
}
// trailer: 4 string pools, each u16 length + data
for (int i = 0; i < 4; i++) {
if (pos + 2 > stream.size()) throw FormatError("savegame: trailer missing");
size_t len = le16(stream, pos);
if (pos + 2 + len > stream.size()) throw FormatError("savegame: trailer exceeds stream");
pools_.emplace_back(stream.begin() + pos + 2, stream.begin() + pos + 2 + len);
pos += 2 + len;
}
if (pos < stream.size()) {
// the OpenBMH extension (savestate.hpp)
static const char kMagic[8] = {0x4f, 0x42, 0x4d, 0x48, 0x45, 0x58, 0x54, 0x31}; // "OBMHEXT1"
if (stream.size() - pos < 10 || !std::equal(kMagic, kMagic + 8, stream.begin() + long(pos)))
throw FormatError("savegame: block sizes do not match stream length");
size_t count = le16(stream, pos + 8);
pos += 10;
for (size_t i = 0; i < count; ++i) {
if (pos + 8 > stream.size()) throw FormatError("savegame: extension cut off");
const uint32_t address = le32(stream, pos), size = le32(stream, pos + 4);
pos += 8;
if (pos + size > stream.size()) throw FormatError("savegame: extension block exceeds stream");
extension_.push_back({address, Bytes(stream.begin() + long(pos), stream.begin() + long(pos + size))});
pos += size;
}
}
if (pos != stream.size()) throw FormatError("savegame: block sizes do not match stream length");
}
void append_save_extension(Bytes& stream, const std::vector<SaveState::ExtensionBlock>& blocks) {
if (blocks.empty()) return;
for (char ch : std::string("OBMHEXT1")) stream.push_back(uint8_t(ch));
stream.push_back(uint8_t(blocks.size())), stream.push_back(uint8_t(blocks.size() >> 8));
for (const auto& b : blocks) {
for (uint32_t v : {b.address, uint32_t(b.bytes.size())})
for (int k = 0; k < 4; ++k) stream.push_back(uint8_t(v >> (8 * k)));
stream.insert(stream.end(), b.bytes.begin(), b.bytes.end());
}
}
const SaveBlock& SaveState::block(uint32_t address) const {
auto it = index_.find(address);
if (it == index_.end()) throw FormatError("savegame: unknown block");
return blocks_[it->second];
}
} // namespace bmh
namespace bmh {
std::vector<SaveBlock> save_layout(const DbCounts& c, bool club_records) {
constexpr uint32_t kTeams = 138, kCupTeams = 30;
std::vector<SaveBlock> out;
size_t pos = 0;
for (const BlockDef& d : kBlocks) {
if (d.only_if_pointer && !club_records) continue;
uint32_t n = 0;
switch (d.count) {
case Count::None: n = 0; break;
case Count::Clubs: n = c.clubs; break;
case Count::Players: n = c.players; break;
case Count::N42: n = c.n42; break;
case Count::N66: n = c.n66; break;
case Count::Teams: n = kTeams; break;
case Count::TeamsPlusCups: n = kTeams + kCupTeams; break;
}
const size_t size = d.fixed + size_t(n) * d.factor;
out.push_back({d.address, d.heap, pos, size});
pos += size;
}
return out;
}
} // namespace bmh
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Structured view of the decrypted savegame stream.
//
// The original writes its whole game state by dumping global variables one after
// another (NationalCoachAfterLoad, 125 calls of the stream writer FbmDecrypt). There are no
// headers or tags: the position of every block follows only from the fixed order and
// the size of the preceding blocks. This file reproduces that order so a block can be
// looked up by the address of the global it was dumped from, e.g. block(LeagueResults) for
// the match results.
//
// Block sizes are either constants or depend on table sizes of the master database
// (DbCounts). Blocks that were heap allocations in the original ("*PlayerConditionTechniqueForm") store the
// pointed-to data, not the pointer.
//
// After the state blocks follow four trailer blocks, each a u16 length plus data. They
// are the string pools of the master database (club names, player names, referees,
// stadiums), saved so that renamed clubs/players survive.
#include <cstdint>
#include <map>
#include <string>
#include <vector>
#include "formats/binary.hpp"
#include "formats/m3d.hpp"
namespace bmh {
struct SaveBlock {
uint32_t address = 0; // address of the global variable in BMH.exe V2.24 (for reference)
bool heap = false; // true if the global was a pointer to heap data
size_t offset = 0; // byte offset inside the decrypted stream
size_t size = 0;
};
// The blocks of a savegame in the order NationalCoachAfterLoad writes them (offsets counted from 0).
// The heap copy of the club records (ClubSeasonRecords) is present only if `club_records` is set.
std::vector<SaveBlock> save_layout(const DbCounts& counts = {}, bool club_records = true);
class SaveState {
public:
// Splits a decrypted stream (Savegame::stream). Throws FormatError if the block
// sizes do not add up exactly to the stream length.
SaveState(const Bytes& stream, const DbCounts& counts = {});
const std::vector<SaveBlock>& blocks() const { return blocks_; }
// First block dumped from the given global (some globals are dumped twice).
const SaveBlock& block(uint32_t address) const;
// Raw bytes of a block; valid as long as the stream passed to the constructor lives.
const uint8_t* data(uint32_t address) const { return stream_.data() + block(address).offset; }
const Bytes& stream() const { return stream_; }
// The four string pools from the trailer (0 = club names, 1 = player names,
// 2 = referees, 3 = stadiums), same layout as in M3D.MAN.
const Bytes& pool(int index) const { return pools_.at(index); }
// OpenBMH extension behind the trailer (only in OpenBMH saves of games that need it, such
// as the English cup memory): "OBMHEXT1", u16 count, then per block u32 address,
// u32 size, the bytes. Original saves have none.
struct ExtensionBlock {
uint32_t address;
Bytes bytes;
};
const std::vector<ExtensionBlock>& extension() const { return extension_; }
private:
const Bytes& stream_;
std::vector<SaveBlock> blocks_;
std::map<uint32_t, size_t> index_;
std::vector<Bytes> pools_;
std::vector<ExtensionBlock> extension_;
};
// Appends the OpenBMH extension (SaveState::extension) to a save stream.
void append_save_extension(Bytes& stream, const std::vector<SaveState::ExtensionBlock>& blocks);
} // namespace bmh
+26
View File
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/textd.hpp"
#include "formats/binary.hpp"
namespace bmh {
TextDb load_textd(const std::filesystem::path& path) {
Bytes d = read_file(path);
if (d.size() < 7) throw FormatError("TEXTD: file too short");
// header: u8 id, u16 buffer size, u32 unknown; the buffer may be larger than the file rest
TextDb db;
size_t p = 7;
db.blob.assign(d.begin() + 7, d.end());
while (db.strings.size() < TEXT_COUNT && p < d.size()) {
size_t start = p;
db.offsets.push_back(start - 7);
while (p < d.size() && d[p] != 0) p++;
db.strings.emplace_back(reinterpret_cast<const char*>(d.data() + start), p - start);
p++;
}
if (db.strings.size() != TEXT_COUNT) throw FormatError("TEXTD: expected 1382 strings");
return db;
}
} // namespace bmh
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// TEXTD.BLK: UI strings (docs/formats/TEXTD.md), loaded in CareerFirstSteps2
#include <filesystem>
#include <string>
#include <vector>
namespace bmh {
constexpr size_t TEXT_COUNT = 0x566; // pointer table TextPointerTable[1382]
struct TextDb {
std::vector<std::string> strings; // raw ISO 646-DE, index = text id
// The texts as the original keeps them in memory: one block, NUL separated. Some
// routines copy a fixed number of bytes from a text and so also take the following
// ones (see raw()).
std::vector<uint8_t> blob;
std::vector<size_t> offsets;
std::vector<uint8_t> raw(size_t id, size_t n) const {
std::vector<uint8_t> r(n, 0);
for (size_t i = 0; i < n && offsets.at(id) + i < blob.size(); i++) r[i] = blob[offsets.at(id) + i];
return r;
}
const std::string& operator[](size_t id) const { return strings.at(id); }
};
TextDb load_textd(const std::filesystem::path& path);
} // namespace bmh
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/vga.hpp"
namespace bmh {
void Image::blit(const Image& src, int x, int y) {
for (int sy = 0; sy < src.height; sy++) {
int dy = y + sy;
if (dy < 0 || dy >= height) continue;
for (int sx = 0; sx < src.width; sx++) {
int dx = x + sx;
if (dx >= 0 && dx < width) at(dx, dy) = src.pixels[size_t(sy) * src.width + sx];
}
}
}
Image decode_vga(const Bytes& d) {
if (d.size() < 8) throw FormatError("VGA: file too short");
Image img(le16(d, 0), le16(d, 2));
size_t end = 8 + size_t(le32(d, 4));
if (end > d.size()) throw FormatError("VGA: length field exceeds file");
size_t si = 8, di = 0, n = img.pixels.size();
while (di < n) {
if (si >= end) throw FormatError("VGA: RLE data ends early");
uint8_t c = d[si++];
if (c >= 0x80) { // run: next byte repeated c - 0x7F times
if (si >= end) throw FormatError("VGA: truncated run");
uint8_t v = d[si++];
for (int k = 0; k < c - 0x7F && di < n; k++) img.pixels[di++] = v;
} else { // literal: c + 1 bytes
for (int k = 0; k <= c && di < n; k++) {
if (si >= end) throw FormatError("VGA: truncated literal");
img.pixels[di++] = d[si++];
}
}
}
// exactly one trailing byte follows the pixel data in every original file
if (si + 1 != end) throw FormatError("VGA: unexpected data after image");
return img;
}
Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); }
} // namespace bmh
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// .VGA images: u16 width, u16 height, u32 length, RLE data (docs/formats/VGA.md)
#include <cstdint>
#include <filesystem>
#include <vector>
#include "formats/binary.hpp"
namespace bmh {
// 8-bit indexed image, row-major
struct Image {
int width = 0;
int height = 0;
std::vector<uint8_t> pixels;
Image() = default;
Image(int w, int h, uint8_t fill = 0) : width(w), height(h), pixels(size_t(w) * h, fill) {}
uint8_t& at(int x, int y) { return pixels[size_t(y) * width + x]; }
void blit(const Image& src, int x, int y);
};
Image decode_vga(const Bytes& data);
Image load_vga(const std::filesystem::path& path);
} // namespace bmh