Record every match in a football almanac (Modern, M8)

Modern careers keep every match they play: season, date, competition
type, league or cup stage, matchday, both clubs by world id with their
human managers, result with extra time and shoot-out, referee,
attendance, weather, both line-ups and all events (goals with assists
and kind, misses, cards, injuries, substitutions, shoot-out kicks).
Events come from the group event log the engine keeps for every match,
substitutions from the players on the pitch after each minute; nothing
draws random numbers (a 60-turn Modern run is unchanged).

Player indices reused for a new person get a new stable id. Saves hold
finished seasons as immutable history/season-<year>.bin files plus the
running season; modern-state@1.1 adds league names and the id counter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-23 23:49:13 +02:00
1 parent 57d75ab2f5
commit 201eef88e4
14 files changed
+935 -8

No files matched your search

+9
View File
@@ -394,6 +394,15 @@ ExpandReport expand_to_world(ModernState& g, const World& world) {
g.world_club_id.assign(size_t(new_total), {});
g.world_club_name.assign(size_t(new_total), {});
g.world_club_short.assign(size_t(new_total), {});
g.world_league_id.clear(), g.world_league_name.clear();
for (const WorldLeague& l : world.leagues) {
if (size_t(l.index) >= g.world_league_id.size()) {
g.world_league_id.resize(size_t(l.index) + 1);
g.world_league_name.resize(size_t(l.index) + 1);
}
g.world_league_id[size_t(l.index)] = l.id;
g.world_league_name[size_t(l.index)] = l.name;
}
for (int n = 0; n < new_total; ++n)
if (const WorldClub* c = club_at[size_t(n)]) {
g.world_club_id[size_t(n)] = c->id;
+21 -5
View File
@@ -59,14 +59,20 @@ void save_world_career(const std::filesystem::path& path, const World& world, co
{"world", O{{"id", world.id}, {"data_revision", world.data_revision}, {"title", world.title}}}});
put(docs, "state/career.json", encode_native_state(state));
put(docs, "state/modern.json",
O{{"schema", "modern-state@1.0"},
O{{"schema", "modern-state@1.1"},
{"club_ids", strings(state.world_club_id)},
{"club_names", strings(state.world_club_name)},
{"club_short_names", strings(state.world_club_short)},
{"player_ids", strings(state.world_player_id)},
{"player_first", strings(state.player_first)},
{"player_last", strings(state.player_last)},
{"player_nations", strings(state.player_nation)}});
{"player_nations", strings(state.player_nation)},
{"league_ids", strings(state.world_league_id)},
{"league_names", strings(state.world_league_name)},
{"generated_players", int64_t(state.almanac.generated_players)}});
// The almanac: finished seasons unchanged, the running one encoded now.
for (const auto& [name, bytes] : state.almanac.finished) docs[name] = bytes;
if (state.almanac.current.season >= 0) docs["history/current.bin"] = encode_almanac_season(state.almanac.current);
put(docs, "state/rng.json",
O{{"schema", "classic-rng@1.0"},
{"watcom", generator(random.seed(), random.calls())},
@@ -76,7 +82,7 @@ void save_world_career(const std::filesystem::path& path, const World& world, co
put(docs, "state/information.json", encode_native_bytes(modern::save_header(state)));
O checks;
for (const auto& [name, value] : docs)
if (name.starts_with("state/")) checks[name] = content::sha256(value);
if (name.starts_with("state/") || name.starts_with("history/")) checks[name] = content::sha256(value);
put(docs, "state/integrity.json", O{{"schema", "save-integrity@1.0"}, {"entries", std::move(checks)}});
content::write_archive(docs, path, overwrite);
}
@@ -94,13 +100,13 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl
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] = content::sha256(value);
if ((name.starts_with("state/") || name.starts_with("history/")) && name != "state/integrity.json") checks[name] = content::sha256(value);
if (cli::dump_json(get(integrity, "entries")) != cli::dump_json(checks)) fail("damaged Modern save");
SavedWorldCareer out;
out.state = ModernState(decode_native_state(parse(docs, "state/career.json")));
const auto modern = parse(docs, "state/modern.json");
if (str(get(modern, "schema")) != "modern-state@1.0") fail("unsupported Modern state");
if (str(get(modern, "schema")) != "modern-state@1.1") fail("unsupported Modern state");
out.state.world_club_id = strings(get(modern, "club_ids"));
out.state.world_club_name = strings(get(modern, "club_names"));
out.state.world_club_short = strings(get(modern, "club_short_names"));
@@ -108,6 +114,16 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl
out.state.player_first = strings(get(modern, "player_first"));
out.state.player_last = strings(get(modern, "player_last"));
out.state.player_nation = strings(get(modern, "player_nations"));
out.state.world_league_id = strings(get(modern, "league_ids"));
out.state.world_league_name = strings(get(modern, "league_names"));
out.state.almanac.generated_players = uint32_t(num(get(modern, "generated_players")));
for (const auto& [name, bytes] : docs) {
if (!name.starts_with("history/season-")) continue;
decode_almanac_season(bytes); // a damaged season fails here, not in the almanac screen
out.state.almanac.finished.emplace_back(name, bytes);
}
if (const auto it = docs.find("history/current.bin"); it != docs.end())
out.state.almanac.current = decode_almanac_season(it->second);
if (out.state.world_player_id.size() != out.state.players.size() ||
out.state.world_club_id.size() != out.state.club_ids.size())
fail("Modern names do not match the saved state");
+497
View File
@@ -0,0 +1,497 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/game/almanac.hpp"
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <string_view>
#include "formats/binary.hpp"
#include "game/match_engine.hpp"
#include "game/presentation.hpp"
#include "modern/game/cup.hpp"
#include "modern/game/matchday.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kManagerRecord = 0xB0C;
constexpr uint32_t kVersion = 1;
// Original single-byte text (ISO 646-DE) to UTF-8, as the interfaces show it.
std::string utf8(std::string_view original) {
static constexpr std::string_view german[] = {"Ä", "Ö", "Ü", "ä", "ö", "ü", "ß"};
static constexpr std::string_view codes = "[\\]{|}~";
std::string out;
for (char c : original) {
const size_t i = codes.find(c);
if (i != std::string_view::npos) out += german[i];
else if (static_cast<unsigned char>(c) < 128) out += c;
else out += '?';
}
return out;
}
const std::string& entry(const std::vector<std::string>& names, size_t i) {
static const std::string none;
return i < names.size() ? names[i] : none;
}
AlmanacClub club_of(const ModernState& g, int team) {
AlmanacClub c;
c.id = entry(g.world_club_id, size_t(team));
if (c.id.empty()) c.id = "team:" + std::to_string(team);
c.name = entry(g.world_club_name, size_t(team));
if (c.name.empty()) c.name = utf8(g.club_name(team));
return c;
}
AlmanacManager manager_of(const ModernState& g, int manager) {
AlmanacManager m;
m.index = manager;
const size_t at = size_t(manager) * kManagerRecord + 0xa8; // the manager's name (30 bytes)
for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i)
m.name.push_back(char(g.manager_records[at + i]));
m.name = utf8(m.name);
return m;
}
std::string referee_name(const ModernState& g, int referee) {
const size_t at = size_t(referee) * 2;
if (at + 1 >= g.master_database_metadata.size()) return "#" + std::to_string(referee);
const size_t offset = size_t(g.master_database_metadata[at] | g.master_database_metadata[at + 1] << 8);
std::string name;
for (size_t i = offset; i < g.referee_names.size() && g.referee_names[i]; ++i) name.push_back(char(g.referee_names[i]));
return utf8(name);
}
AlmanacSeason& current_season(ModernState& g) {
Almanac& a = g.almanac;
if (a.current.season != g.season) {
if (a.current.season >= 0 && !a.current.matches.empty())
a.finished.emplace_back("history/season-" + std::to_string(a.current.start_year) + ".bin",
encode_almanac_season(a.current));
a.current = AlmanacSeason{};
a.current.season = g.season;
a.current.display_start_year = g.display_start_year;
a.current.start_year = g.display_start_year + g.season;
a.current.referees.push_back({}); // index 0: no referee
for (size_t l = 0; l < g.world_league_id.size(); ++l)
a.current.leagues.push_back({int(l), g.world_league_id[l], entry(g.world_league_name, l)});
a.current.index();
}
return a.current;
}
// --- binary form -----------------------------------------------------------------------
struct Writer {
std::string out;
void u8(uint32_t v) { out.push_back(char(v & 0xff)); }
void u16(uint32_t v) { u8(v); u8(v >> 8); }
void u32(uint32_t v) { u16(v); u16(v >> 16); }
void str(const std::string& s) {
if (s.size() > 0xffff) throw FormatError("almanac: text too long");
u16(uint32_t(s.size()));
out += s;
}
};
struct Reader {
const std::string& in;
size_t at = 0;
uint32_t u8() {
if (at >= in.size()) throw FormatError("almanac: truncated season");
return uint8_t(in[at++]);
}
uint32_t u16() { const uint32_t lo = u8(); return lo | u8() << 8; }
uint32_t u32() { const uint32_t lo = u16(); return lo | u16() << 16; }
std::string str() {
const size_t n = u16();
if (at + n > in.size()) throw FormatError("almanac: truncated season");
std::string s = in.substr(at, n);
at += n;
return s;
}
};
} // namespace
uint16_t AlmanacSeason::club(const AlmanacClub& c) {
const auto it = club_at_.find(c.id);
if (it != club_at_.end()) return it->second;
if (clubs.size() >= 0xffff) throw FormatError("almanac: too many clubs in a season");
clubs.push_back(c);
return club_at_[c.id] = uint16_t(clubs.size() - 1);
}
uint16_t AlmanacSeason::player(const AlmanacPlayer& p) {
const auto it = player_at_.find(p.id);
if (it != player_at_.end()) return it->second;
if (players.size() >= kAlmanacNone) throw FormatError("almanac: too many players in a season");
players.push_back(p);
return player_at_[p.id] = uint16_t(players.size() - 1);
}
int8_t AlmanacSeason::manager(const AlmanacManager& m) {
for (size_t i = 0; i < managers.size(); ++i)
if (managers[i] == m) return int8_t(i);
if (managers.size() >= 0x7f) throw FormatError("almanac: too many managers in a season");
managers.push_back(m);
return int8_t(managers.size() - 1);
}
uint8_t AlmanacSeason::referee(const std::string& name) {
const auto it = referee_at_.find(name);
if (it != referee_at_.end()) return it->second;
if (referees.size() >= 0xff) throw FormatError("almanac: too many referees in a season");
referees.push_back(name);
return referee_at_[name] = uint8_t(referees.size() - 1);
}
void AlmanacSeason::index() {
club_at_.clear(), player_at_.clear(), referee_at_.clear();
for (size_t i = 0; i < clubs.size(); ++i) club_at_[clubs[i].id] = uint16_t(i);
for (size_t i = 0; i < players.size(); ++i) player_at_[players[i].id] = uint16_t(i);
for (size_t i = 1; i < referees.size(); ++i) referee_at_[referees[i]] = uint8_t(i);
}
AlmanacDate almanac_date(uint32_t counter, int display_start_year) {
// As the desk counts (desk_date): day 0 is 1 July, the fourth year of the cycle is a
// leap year (the first February the calendar reaches is in the first leap year).
static constexpr int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
AlmanacDate d;
int cycle = 3, years = 0;
while (counter > uint32_t(364 + (cycle == 4))) {
if (cycle == 4) { cycle = 0; --counter; }
++years, counter -= 365, ++cycle;
}
d.month = 7;
auto month_days = [&] { return d.month == 2 ? 28 + (cycle == 4) : kDays[d.month]; };
while (counter > uint32_t(month_days())) {
counter -= uint32_t(month_days());
if (++d.month == 13) d.month = 1, ++years;
}
d.day = int(counter) + 1;
if (d.day > month_days()) {
d.day -= month_days();
if (++d.month == 13) d.month = 1, ++years;
}
d.year = display_start_year + years;
return d;
}
std::string encode_almanac_season(const AlmanacSeason& s) {
Writer w;
w.out = "OBAL";
w.u16(kVersion);
w.u16(uint32_t(int16_t(s.season))), w.u16(uint32_t(s.start_year)), w.u16(uint32_t(s.display_start_year));
w.u16(uint32_t(s.leagues.size()));
for (const auto& l : s.leagues) w.u8(uint32_t(l.index)), w.str(l.id), w.str(l.name);
w.u16(uint32_t(s.clubs.size()));
for (const auto& c : s.clubs) w.str(c.id), w.str(c.name);
w.u32(uint32_t(s.players.size()));
for (const auto& p : s.players) w.str(p.id), w.str(p.first), w.str(p.last), w.str(p.nation);
w.u8(uint32_t(s.managers.size()));
for (const auto& m : s.managers) w.u8(uint32_t(uint8_t(int8_t(m.index)))), w.str(m.name);
w.u16(uint32_t(s.referees.size()));
for (const auto& r : s.referees) w.str(r);
w.u32(uint32_t(s.matches.size()));
for (const AlmanacMatch& m : s.matches) {
w.u32(m.date);
w.u8(m.type), w.u8(m.league), w.u8(m.stage), w.u8(m.round);
w.u16(m.home), w.u16(m.away);
w.u8(uint8_t(m.home_manager)), w.u8(uint8_t(m.away_manager));
w.u8(m.home_goals), w.u8(m.away_goals), w.u8(m.home_shootout), w.u8(m.away_shootout);
w.u8(m.decided), w.u8(m.referee);
w.u32(m.attendance);
w.u8(uint8_t(m.temperature)), w.u8(m.rain);
for (const auto& side : m.lineup) {
if (side.size() > 0xff) throw FormatError("almanac: line-up too long");
w.u8(uint32_t(side.size()));
for (uint16_t p : side) w.u16(p);
}
if (m.events.size() > 0xffff) throw FormatError("almanac: too many events in a match");
w.u16(uint32_t(m.events.size()));
for (const AlmanacEvent& e : m.events)
w.u8(uint32_t(e.kind)), w.u8(e.minute), w.u8(e.side), w.u8(e.detail), w.u16(e.player), w.u16(e.other);
}
return std::move(w.out);
}
AlmanacSeason decode_almanac_season(const std::string& bytes) {
if (bytes.size() < 6 || bytes.compare(0, 4, "OBAL") != 0) throw FormatError("almanac: not an almanac season");
Reader r{bytes, 4};
if (r.u16() != kVersion) throw FormatError("almanac: unknown season version");
AlmanacSeason s;
s.season = int16_t(r.u16()), s.start_year = int(r.u16()), s.display_start_year = int(r.u16());
for (uint32_t n = r.u16(); n > 0; --n) {
AlmanacLeague l;
l.index = int(r.u8()), l.id = r.str(), l.name = r.str();
s.leagues.push_back(std::move(l));
}
for (uint32_t n = r.u16(); n > 0; --n) {
AlmanacClub c;
c.id = r.str(), c.name = r.str();
s.clubs.push_back(std::move(c));
}
for (uint32_t n = r.u32(); n > 0; --n) {
AlmanacPlayer p;
p.id = r.str(), p.first = r.str(), p.last = r.str(), p.nation = r.str();
s.players.push_back(std::move(p));
}
for (uint32_t n = r.u8(); n > 0; --n) {
AlmanacManager m;
m.index = int8_t(r.u8()), m.name = r.str();
s.managers.push_back(std::move(m));
}
for (uint32_t n = r.u16(); n > 0; --n) s.referees.push_back(r.str());
for (uint32_t n = r.u32(); n > 0; --n) {
AlmanacMatch m;
m.date = r.u32();
m.type = uint8_t(r.u8()), m.league = uint8_t(r.u8()), m.stage = uint8_t(r.u8()), m.round = uint8_t(r.u8());
m.home = uint16_t(r.u16()), m.away = uint16_t(r.u16());
m.home_manager = int8_t(r.u8()), m.away_manager = int8_t(r.u8());
m.home_goals = uint8_t(r.u8()), m.away_goals = uint8_t(r.u8());
m.home_shootout = uint8_t(r.u8()), m.away_shootout = uint8_t(r.u8());
m.decided = uint8_t(r.u8()), m.referee = uint8_t(r.u8());
m.attendance = r.u32();
m.temperature = int8_t(r.u8()), m.rain = uint8_t(r.u8());
for (auto& side : m.lineup)
for (uint32_t k = r.u8(); k > 0; --k) side.push_back(uint16_t(r.u16()));
for (uint32_t k = r.u16(); k > 0; --k) {
AlmanacEvent e;
e.kind = AlmanacEventKind(r.u8());
e.minute = uint8_t(r.u8()), e.side = uint8_t(r.u8()), e.detail = uint8_t(r.u8());
e.player = uint16_t(r.u16()), e.other = uint16_t(r.u16());
if (uint8_t(e.kind) > uint8_t(AlmanacEventKind::Miss)) throw FormatError("almanac: unknown event kind");
m.events.push_back(e);
}
if (m.home >= s.clubs.size() || m.away >= s.clubs.size()) throw FormatError("almanac: unknown club in a match");
s.matches.push_back(std::move(m));
}
if (r.at != bytes.size()) throw FormatError("almanac: trailing bytes after the season");
s.index();
return s;
}
void new_player_identity(ModernState& g, int player) {
if (player < 0 || size_t(player) >= g.players.size()) return;
if (g.world_player_id.size() < g.players.size()) g.world_player_id.resize(g.players.size());
// The new person keeps the name of the index, as in the original (its name pool entry).
g.world_player_id[size_t(player)] = "player:gen-" + std::to_string(++g.almanac.generated_players);
}
// --- recording -------------------------------------------------------------------------
AlmanacRecorder::AlmanacRecorder(ModernState& g, const std::vector<MatchGroup>& groups) : g_(g), groups_(groups) {
AlmanacSeason& season = current_season(g);
for (size_t gi = 0; gi < groups.size(); ++gi) {
const MatchGroup& group = groups[gi];
if (group.desc.size() < 0xd0) continue;
for (int m = 0; m < group.matches(); ++m) {
if (group.void_mask() >> m & 1) continue;
const size_t f = size_t(m) * 2;
if (f + 1 >= group.fixtures.size()) continue;
const int home = group.fixtures[f], away = group.fixtures[f + 1];
const int teams = world_layout().total_teams();
if (home < 0 || away < 0 || home >= teams || away >= teams || home == no_team() || away == no_team()) continue;
Running r;
r.group = gi, r.match = m;
AlmanacMatch& rec = r.record;
rec.date = g.date;
rec.type = group.desc[0];
const uint32_t id = le32(group.desc, 0xcc);
if (rec.type == 0) {
rec.league = uint8_t(id);
if (id < g.league_rounds.size()) rec.round = uint8_t(g.league_rounds[id] + 1);
} else if (id >= kCupTable && id < kCupTable + kCupEntries * kCupEntrySize && (id - kCupTable) % kCupEntrySize == 0) {
rec.stage = uint8_t(modern::cup_entry_index(id));
rec.round = uint8_t(modern::cup_round(g.memory, rec.stage) + 1);
}
rec.home = season.club(club_of(g, home));
rec.away = season.club(club_of(g, away));
if (const int hm = g.manager_of(home); hm >= 0) rec.home_manager = season.manager(manager_of(g, hm));
if (const int am = g.manager_of(away); am >= 0) rec.away_manager = season.manager(manager_of(g, am));
rec.temperature = int8_t(group.desc.at(0x30 + size_t(m)));
rec.rain = group.desc.at(0x50 + size_t(m));
if (const int ref = group.desc.at(0x10 + size_t(m)); ref > 0) rec.referee = season.referee(referee_name(g, ref));
for (int side = 0; side < 2; ++side) {
const int team = side ? away : home;
if (team >= league_clubs()) continue; // only league clubs have squads
const SquadRange range = squad_range(team);
for (size_t s = 0; s < range.count; ++s) {
const uint16_t e = g.squad_slots.at(range.first + s);
const int player = e & 0x0fff;
if (player == 0x0fff) continue;
if (s < 11 || (e & 0x4000)) rec.lineup[size_t(side)].push_back(player_ref(player));
}
r.eleven[size_t(side)] = on_pitch(team);
}
running_.push_back(std::move(r));
}
}
}
uint16_t AlmanacRecorder::player_ref(int player) {
AlmanacPlayer p;
p.id = entry(g_.world_player_id, size_t(player));
if (p.id.empty()) p.id = "player:legacy-" + std::to_string(player);
p.first = entry(g_.player_first, size_t(player));
p.last = entry(g_.player_last, size_t(player));
if (p.last.empty()) p.last = utf8(g_.player_name(player));
p.nation = entry(g_.player_nation, size_t(player));
return g_.almanac.current.player(p);
}
// The players on the pitch: the first 11 slots that still carry a line-up flag (a player
// sent off or injured loses it; a substitute takes the slot of the player he replaces).
std::vector<uint16_t> AlmanacRecorder::on_pitch(int team) const {
std::vector<uint16_t> out;
if (team < 0 || team >= league_clubs()) return out;
const SquadRange range = squad_range(team);
for (size_t s = 0; s < std::min<size_t>(11, range.count); ++s) {
const uint16_t e = g_.squad_slots.at(range.first + s);
if ((e & 0x0fff) != 0x0fff && (e & 0xf000)) out.push_back(uint16_t(e & 0x0fff));
}
std::sort(out.begin(), out.end());
return out;
}
void AlmanacRecorder::after_minute(int minute) {
for (size_t i = 0; i < running_.size(); ++i) {
Running& r = running_[i];
const MatchGroup& group = groups_.at(r.group);
for (int side = 0; side < 2; ++side) {
const int team = group.fixtures.at(size_t(r.match) * 2 + size_t(side));
std::vector<uint16_t> now = on_pitch(team);
auto& before = r.eleven[size_t(side)];
if (now == before) continue;
std::vector<uint16_t> came, left;
std::set_difference(now.begin(), now.end(), before.begin(), before.end(), std::back_inserter(came));
std::set_difference(before.begin(), before.end(), now.begin(), now.end(), std::back_inserter(left));
// A player still in the first 11 slots left without a substitute (sent off or
// injured); the others went to the bench for the players who came on.
const SquadRange range = squad_range(team);
std::vector<uint16_t> replaced;
for (uint16_t p : left) {
bool in_eleven = false;
for (size_t s = 0; s < std::min<size_t>(11, range.count) && !in_eleven; ++s)
in_eleven = (g_.squad_slots.at(range.first + s) & 0x0fff) == p;
if (!in_eleven) replaced.push_back(p);
}
for (size_t k = 0; k < came.size(); ++k) {
AlmanacEvent e;
e.kind = AlmanacEventKind::Substitution;
e.minute = uint8_t(std::clamp(minute, 0, 255));
e.side = uint8_t(side);
e.player = player_ref(came[k]);
if (k < replaced.size()) e.other = player_ref(replaced[k]);
pending_.push_back(e);
pending_match_.push_back(i);
}
before = std::move(now);
}
}
}
void AlmanacRecorder::finish(const std::vector<ShowEvent>& shown) {
std::vector<std::vector<AlmanacEvent>> events(running_.size());
std::map<std::pair<size_t, int>, size_t> by_match;
for (size_t i = 0; i < running_.size(); ++i) by_match[{running_[i].group, running_[i].match}] = i;
auto ref = [&](int player) { return player >= 0 && player < 0x0fff ? player_ref(player) : kAlmanacNone; };
// Goals, misses, cards and injuries: the event log of each group (Matches), which the
// engine keeps for every match. A pair of words per entry: player + code * 0x1000, then
// team * 0x80 + value (the minute; for the second pair of a chance the distance).
// 0 goal, 1 miss: followed by the assistant pair, code 2 open play, 7 penalty / free
// kick, 8 follow-up, 9 corner
// 3 yellow card, 4 second yellow, 5 red card, 6 injury
std::map<std::pair<size_t, int>, size_t> by_team; // (group, team) -> running match
for (size_t i = 0; i < running_.size(); ++i)
for (int side = 0; side < 2; ++side)
by_team[{running_[i].group, groups_.at(running_[i].group).fixtures.at(size_t(running_[i].match) * 2 + size_t(side))}] = i;
for (size_t gi = 0; gi < groups_.size(); ++gi) {
const auto& log = groups_[gi].log;
for (size_t w = 0; w + 1 < log.size(); w += 2) {
const int code = log[w] >> 12, player = log[w] & 0x0fff;
const int team = log[w + 1] >> 7, value = log[w + 1] & 0x7f;
const bool chance = code == 0 || code == 1;
int assistant = 0x0fff, detail = 0;
if (chance && w + 3 < log.size()) {
const int follow = log[w + 2] >> 12;
assistant = log[w + 2] & 0x0fff;
detail = follow == 2 ? 0 : std::clamp(follow - 6, 0, 3);
w += 2;
}
const auto it = by_team.find({gi, team});
if (it == by_team.end()) continue;
AlmanacEvent e;
e.minute = uint8_t(value);
e.side = groups_[gi].fixtures.at(size_t(running_[it->second].match) * 2) == team ? 0 : 1;
e.player = ref(player);
switch (code) {
case 0: case 1:
e.kind = code == 0 ? AlmanacEventKind::Goal : AlmanacEventKind::Miss;
e.detail = uint8_t(detail);
e.other = ref(assistant);
break;
case 3: e.kind = AlmanacEventKind::YellowCard; break;
case 4: e.kind = AlmanacEventKind::SecondYellow; break;
case 5: e.kind = AlmanacEventKind::RedCard; break;
case 6: e.kind = AlmanacEventKind::Injury; break;
default: continue;
}
events[it->second].push_back(e);
}
}
// The kicks of a shoot-out (the log has none): the show events of the match engine.
for (const ShowEvent& s : shown) {
if (s.what != Show::PenaltyKick) continue;
const auto it = by_match.find({size_t(s.group), int(s.match)});
if (it == by_match.end()) continue;
AlmanacEvent e;
e.kind = AlmanacEventKind::ShootoutKick;
e.minute = uint8_t(std::clamp<int>(s.minute, 0, 255));
e.side = s.side;
e.detail = s.flag ? 1 : 0;
e.player = ref(s.player);
events[it->second].push_back(e);
}
// Substitutions after the shown events of their minute (an injury, then its substitute).
for (size_t k = 0; k < pending_.size(); ++k) {
auto& list = events[pending_match_[k]];
const auto at = std::upper_bound(list.begin(), list.end(), pending_[k].minute,
[](uint8_t minute, const AlmanacEvent& e) { return minute < e.minute; });
list.insert(at, pending_[k]);
}
AlmanacSeason& season = g_.almanac.current;
for (size_t i = 0; i < running_.size(); ++i) {
Running& r = running_[i];
const MatchGroup& group = groups_.at(r.group);
const int m = r.match;
if (group.results.empty() && (size_t(m) >= group.cup_results.size() || group.cup_results[size_t(m)] == 0xCCCC)) continue;
if (!group.results.empty() && group.results.at(size_t(m)) == 0xCC) continue;
int home = 0, away = 0;
if (!modern::match_score(group, m, home, away)) continue;
AlmanacMatch& rec = r.record;
rec.events = std::move(events[i]);
if (group.results.empty()) rec.decided = uint8_t(group.cup_results[size_t(m)] >> 10 & 3);
// After a shoot-out the stored score includes its goals (CupTie2): the goals of the
// match are those of the log, the rest were scored in the shoot-out.
if (rec.decided == 2) {
int goals[2] = {0, 0};
for (const AlmanacEvent& e : rec.events)
if (e.kind == AlmanacEventKind::Goal) ++goals[e.side];
rec.home_shootout = uint8_t(std::max(0, home - goals[0]));
rec.away_shootout = uint8_t(std::max(0, away - goals[1]));
}
rec.home_goals = uint8_t(std::max(0, home - rec.home_shootout));
rec.away_goals = uint8_t(std::max(0, away - rec.away_shootout));
if (size_t(m) < group.spectators.size()) rec.attendance = group.spectators[size_t(m)];
season.matches.push_back(std::move(rec));
}
}
} // namespace bmh::modern
+179
View File
@@ -0,0 +1,179 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The football almanac of a Modern career (docs/new_engine/almanach.md, data format F10).
//
// Every match the engine plays is kept: season, date, competition, matchday or cup stage,
// both clubs with their human managers, the result (extra time, penalties), referee,
// attendance, weather, both line-ups and every event with its minute (goals with the
// assistant, cards, injuries, substitutions, shoot-out kicks). The almanac only watches:
// it draws no random numbers and changes nothing the season core reads.
//
// Identities are the stable ones of the world (club and player ids), not runtime indices:
// clubs swap their runtime index on promotion, and a player index is reused for a new
// person when a player retires or a youth player is created (new_player_identity). Each
// season keeps its own tables of the clubs, players, managers and referees it mentions, so a
// finished season is self-contained and never changes again; a save holds every finished
// season as one compact binary file (history/season-<year>.bin) plus the running one.
#include <array>
#include <cstdint>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace bmh {
struct MatchGroup;
struct ShowEvent;
}
namespace bmh::modern {
struct ModernState;
enum class AlmanacEventKind : uint8_t {
Goal = 0, // player scorer, other assistant (or none), detail: chance kind (0 open
// play, 1 penalty / free kick, 2 follow-up, 3 corner)
YellowCard = 1,
RedCard = 2,
SecondYellow = 3, // yellow-red
Injury = 4,
Substitution = 5, // player comes on, other leaves (none when the slot was empty)
ShootoutKick = 6, // player takes the kick, detail 1 = scored
Miss = 7, // a chance without a goal: player shooter, other assistant, detail kind
};
constexpr uint16_t kAlmanacNone = 0xffff; // no player in an event or line-up entry
struct AlmanacEvent {
AlmanacEventKind kind = AlmanacEventKind::Goal;
uint8_t minute = 0; // 1-based match minute (121 for the shoot-out)
uint8_t side = 0; // 0 home, 1 away (the acting team)
uint8_t detail = 0;
uint16_t player = kAlmanacNone, other = kAlmanacNone; // indices into the season's players
bool operator==(const AlmanacEvent&) const = default;
};
// Competition of a match: a league (0-8 in Classic order, the world's league ids in the
// season header) or a cup (the cup id of the cup table: German cup, European cups, national
// team competitions, friendlies, indoor tournament, ...), with its stage entry.
struct AlmanacMatch {
uint32_t date = 0; // day counter of the calendar (almanac_date)
uint8_t type = 0; // descriptor type: 0 league, else cup id + 1
uint8_t league = 0xff; // league index for type 0
uint8_t stage = 0xff; // cup stage entry (cup table index) for cups
uint8_t round = 0; // league matchday 1.., or the round within the cup stage 1..
uint16_t home = 0, away = 0; // indices into the season's clubs
int8_t home_manager = -1, away_manager = -1; // indices into the season's managers, -1 computer
uint8_t home_goals = 0, away_goals = 0; // after regular / extra time, without the shoot-out
uint8_t home_shootout = 0, away_shootout = 0; // shoot-out goals (decided == 2)
uint8_t decided = 0; // 0 regular time, 1 extra time, 2 penalties
uint8_t referee = 0; // index into the season's referees (0 = none)
uint32_t attendance = 0;
int8_t temperature = 0; // degrees Celsius
uint8_t rain = 0; // 0-7 as the engine draws it (snow when cold)
std::array<std::vector<uint16_t>, 2> lineup; // home, away: 11 starters, then the bench
std::vector<AlmanacEvent> events; // in match order
bool operator==(const AlmanacMatch&) const = default;
};
struct AlmanacClub {
std::string id, name; // world club id (or team:<n> without a world), UTF-8 name
bool operator==(const AlmanacClub&) const = default;
};
struct AlmanacPlayer {
std::string id, first, last, nation;
bool operator==(const AlmanacPlayer&) const = default;
};
struct AlmanacManager {
int index = -1; // manager slot of the career (human managers)
std::string name;
bool operator==(const AlmanacManager&) const = default;
};
struct AlmanacLeague {
int index = -1;
std::string id, name;
bool operator==(const AlmanacLeague&) const = default;
};
struct AlmanacSeason {
int season = -1; // seasons played before (GameState::season)
int start_year = 0; // calendar year the season starts in
int display_start_year = 0; // year of day counter 0 (almanac_date)
std::vector<AlmanacLeague> leagues;
std::vector<AlmanacClub> clubs;
std::vector<AlmanacPlayer> players;
std::vector<AlmanacManager> managers;
std::vector<std::string> referees; // index 0 = none
std::vector<AlmanacMatch> matches; // in the order played
bool operator==(const AlmanacSeason&) const = default;
// Index of an entry, appending it when it is new (the lookups are rebuilt after decoding).
uint16_t club(const AlmanacClub& c);
uint16_t player(const AlmanacPlayer& p);
int8_t manager(const AlmanacManager& m);
uint8_t referee(const std::string& name);
void index(); // rebuilds the lookups from the tables
private:
std::map<std::string, uint16_t> club_at_, player_at_;
std::map<std::string, uint8_t> referee_at_;
};
struct Almanac {
// Finished seasons, encoded (encode_almanac_season) and never changed again: the file
// name in the save and its bytes.
std::vector<std::pair<std::string, std::string>> finished;
AlmanacSeason current;
// Counter of the identities new_player_identity gave out (saved with the career).
uint32_t generated_players = 0;
bool operator==(const Almanac& o) const {
return finished == o.finished && current == o.current && generated_players == o.generated_players;
}
};
struct AlmanacDate { int year = 0, month = 0, day = 0; };
// The calendar date of a day counter (day 0 = 1 July of display_start_year), as the desk shows it.
AlmanacDate almanac_date(uint32_t counter, int display_start_year);
// Binary form of a season (format version 1, little-endian; docs/new_engine/almanach.md).
std::string encode_almanac_season(const AlmanacSeason& season);
// Throws FormatError when the bytes are not an almanac season of a known version.
AlmanacSeason decode_almanac_season(const std::string& bytes);
// A player index now belongs to a new person (retirement or youth player): gives it a new
// stable identity so the almanac does not merge the two careers.
void new_player_identity(ModernState& g, int player);
// --- Recording (the Modern turn driver) ---------------------------------------------------
// One matchday as the turn driver plays it: begin after kick-off (line-ups, rounds), the
// minutes for substitutions, finish with the match engine's show events before the
// matchday's results are processed.
class AlmanacRecorder {
public:
AlmanacRecorder(ModernState& g, const std::vector<MatchGroup>& groups);
void after_minute(int minute);
void finish(const std::vector<ShowEvent>& events);
private:
struct Running {
size_t group = 0;
int match = 0;
AlmanacMatch record;
std::array<std::vector<uint16_t>, 2> eleven; // runtime players on the pitch per side
};
ModernState& g_;
const std::vector<MatchGroup>& groups_;
std::vector<Running> running_;
std::vector<AlmanacEvent> pending_; // substitutions found by after_minute, per running match
std::vector<size_t> pending_match_;
uint16_t player_ref(int player);
std::vector<uint16_t> on_pitch(int team) const;
};
} // namespace bmh::modern
+4
View File
@@ -15,6 +15,7 @@
#include "game/state.hpp"
#include "game/world_layout.hpp"
#include "modern/game/almanac.hpp"
#include "modern/game/training_camps.hpp"
namespace bmh::modern {
@@ -45,9 +46,12 @@ struct ModernState : GameState {
std::vector<std::string> world_club_id, world_club_name, world_club_short; // per team
std::vector<std::string> world_player_id, player_first, player_last; // per player
std::vector<std::string> player_nation; // nation id per player
std::vector<std::string> world_league_id, world_league_name; // per league index
// Training camps (M4): Classic data gives the eight original resorts, a Modern world its catalogue.
std::vector<CampMap> camp_maps;
std::vector<TrainingCamp> training_camps;
// The football almanac (docs/new_engine/almanach.md): every match of the career.
Almanac almanac;
ModernState() { season_hooks = &modern::season_hooks(); }
// Takes over a state built by shared code (save loading, career setup).
+2
View File
@@ -681,6 +681,7 @@ bool youth_academy_player(ModernState& g, int m, GameRandom& game, WatcomRandom&
const int band = league == 0 ? 0 : league == 1 ? 1 : league < 4 ? 2 : 3;
const int level = game.range(kLevel[band][0], kLevel[band][1]);
modern::generate_player(g, player, level | 0x3000, game, rand);
modern::new_player_identity(g, player); // the youth player is a new person (almanac)
// PendingOfferAnswer(manager, player | 0xf000, -1, squad start)
int slot = -1;
for (size_t q = own.first; q < own.first + 24 && slot < 0; q++)
@@ -1089,6 +1090,7 @@ bool release_player(ModernState& g, int slot, GameRandom& game, WatcomRandom& ra
if (g.squad_slots.at(size_t(s)) == 0x0FFF) free = s;
const uint32_t skills = g.players.at(size_t(player)).w35c; // RegeneratePlayer
regenerate_player(g, player, 0x32, game, rand);
modern::new_player_identity(g, player); // a new person for the almanac
Player& p = g.players.at(size_t(player));
p.w35c = skills;
g.player_bonus.at(size_t(player)) &= 0x80;
+20 -1
View File
@@ -5,7 +5,9 @@
#include <algorithm>
#include <array>
#include <cstdio>
#include <exception>
#include <optional>
#include "modern/game/desk.hpp"
#include "modern/game/driver.hpp"
@@ -163,7 +165,15 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game,
if (manager_match_played) engine.original_sound(3); // EndPhase / ReadButtons, crowd.
}
std::vector<ShowEvent> sportschau_show_events;
if (driver.sportschau.fixture) engine.show = &sportschau_show_events;
// The almanac reads goals, cards and shoot-out kicks of every match from the show
// events, so Modern always collects them (appending draws no random numbers).
engine.show = &sportschau_show_events;
std::optional<AlmanacRecorder> almanac;
try {
almanac.emplace(g, driver.groups);
} catch (const std::exception& e) {
std::fprintf(stderr, "almanac: matchday not recorded: %s\n", e.what());
}
engine.month = context.month;
engine.buttons = read_buttons(g);
engine.reality_rules = driver.reality_rules;
@@ -246,6 +256,7 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game,
};
auto after_minute = [&](int minute) {
collect_goals(minute);
if (almanac) almanac->after_minute(minute);
if (driver.live_minute) driver.live_minute(minute, engine, driver.groups, g);
};
turn_step = "play_matchday";
@@ -256,6 +267,14 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game,
if (manager_match_scored) events.push_back(audio_event(driver, TurnAudioKind::goal));
if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::full_time_whistle));
turn_step = "almanac";
if (almanac) {
try {
almanac->finish(sportschau_show_events);
} catch (const std::exception& e) {
std::fprintf(stderr, "almanac: matchday not recorded: %s\n", e.what());
}
}
turn_step = "finish_event";
modern::store_group_descriptors(g, driver.groups, true);
modern::finish_event(g, driver.groups, driver.calendar_entry, engine.buttons,