// SPDX-License-Identifier: GPL-3.0-only // The football almanac (docs/new_engine/almanach.md, M8) on synthetic data: the binary // season round trip, damaged input, dates/identities, shoot-out recording and read-only // legacy normalization through the actual statistics projection. #include #include #include #include "formats/binary.hpp" #include "game/match_engine.hpp" #include "game/world_layout.hpp" #include "modern/content/statistics.hpp" #include "modern/game/almanac.hpp" #include "modern/game/modern_state.hpp" using namespace bmh; using namespace bmh::modern; namespace { int failures = 0; void check(bool ok, const char* what) { if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++failures; } } AlmanacMatch recorded_shootout(bool with_log, bool with_show, bool capped = false) { ModernState g; g.season = 0; g.display_start_year = 2026; const int home = first_foreign_cup(), away = home + 1; g.world_club_id.resize(size_t(away + 1)); g.world_club_name.resize(size_t(away + 1)); g.world_club_id[size_t(home)] = "club:a"; g.world_club_name[size_t(home)] = "A"; g.world_club_id[size_t(away)] = "club:b"; g.world_club_name[size_t(away)] = "B"; std::vector groups(1); auto& group = groups[0]; group.desc.resize(0xd0); group.desc[0] = 2; group.fixtures = {home, away}; group.spectators = {12345}; const int normal = capped ? 5 : 1; const int combined_home = capped ? 15 : 5, combined_away = capped ? 14 : 4; group.cup_results = {uint16_t(0x800 | combined_home << 5 | combined_away)}; AlmanacRecorder recorder(g, groups); const auto log = [&](int side, bool goal, int minute) { const int team = side ? away : home; group.log.insert(group.log.end(), {uint16_t(0xfff + (goal ? 0 : 0x1000)), uint16_t(team * 0x80 + minute), uint16_t(0x2fff), uint16_t(team * 0x80 + 1)}); }; for (int n = 0; n < normal; ++n) { log(0, true, 10+n); log(1, true, 70+n); } std::vector shown; const auto kick = [&](int side, bool goal) { if (with_log) log(side, goal, 121); if (with_show) { ShowEvent e{Show::PenaltyKick}; e.group = 0; e.match = 0; e.minute = 121; e.side = uint8_t(side); e.flag = goal; e.player = 0xfff; shown.push_back(e); } }; if (capped) { for (int i = 0; i < 12; ++i) { kick(0, true); kick(1, i != 11); } } else { const bool h[5] = {true,true,false,true,true}, a[5] = {true,false,true,true,false}; for (int i=0;i<5;++i) { kick(0,h[i]); kick(1,a[i]); } } const auto packed = group.cup_results; recorder.finish(shown); check(group.cup_results == packed, "recorder never rewrites packed match scores"); return g.almanac.current.matches.at(0); } void check_shootout_recording() { const auto both=recorded_shootout(true,true), background=recorded_shootout(true,false), shown_only=recorded_shootout(false,true), capped=recorded_shootout(true,true,true); check(both==background && both==shown_only, "visible/background/show-only shoot-outs agree"); check(both.home_goals==1 && both.away_goals==1 && both.home_shootout==4 && both.away_shootout==3, "normal and shoot-out goals stay separate"); check(both.events.size()==12 && std::count_if(both.events.begin(),both.events.end(),[](const auto& e){return e.kind==AlmanacEventKind::ShootoutKick;})==10, "each logged/shown kick is recorded exactly once"); check(std::none_of(both.events.begin(),both.events.end(),[](const auto& e){return e.minute==121 && e.kind!=AlmanacEventKind::ShootoutKick;}), "shoot-out misses and goals do not become normal match events"); check(capped.home_goals==5 && capped.away_goals==5 && capped.home_shootout==12 && capped.away_shootout==11, "packed-score clamping cannot erase actual shoot-out goals"); auto legacy=both; legacy.home_goals=5; legacy.away_goals=4; legacy.home_shootout=legacy.away_shootout=0; std::vector duplicates; for(const auto& e:both.events)if(e.kind==AlmanacEventKind::ShootoutKick) { auto copy=e;copy.kind=e.detail?AlmanacEventKind::Goal:AlmanacEventKind::Miss;copy.detail=0;duplicates.push_back(copy); } legacy.events.insert(legacy.events.begin()+2,duplicates.begin(),duplicates.end()); const auto original=legacy; check(normalize_legacy_shootout(legacy) && legacy==both, "exact legacy duplicate signature is recoverable"); check(!normalize_legacy_shootout(legacy), "legacy normalization is idempotent"); auto legacy_capped=capped; legacy_capped.home_goals=15;legacy_capped.away_goals=14;legacy_capped.home_shootout=legacy_capped.away_shootout=0; std::vector capped_duplicates; for(const auto& e:capped.events)if(e.kind==AlmanacEventKind::ShootoutKick){auto copy=e;copy.kind=e.detail?AlmanacEventKind::Goal:AlmanacEventKind::Miss;copy.detail=0;capped_duplicates.push_back(copy);} legacy_capped.events.insert(legacy_capped.events.begin()+10,capped_duplicates.begin(),capped_duplicates.end()); check(normalize_legacy_shootout(legacy_capped)&&legacy_capped==capped,"complete legacy sources also recover clamped shoot-out scores"); auto uncertain=original;uncertain.events.back().player=7; const auto uncertain_before=uncertain; check(!normalize_legacy_shootout(uncertain) && uncertain==uncertain_before, "disagreeing legacy sources remain unchanged"); uncertain=original;uncertain.events.pop_back(); const auto partial=uncertain; check(!normalize_legacy_shootout(uncertain) && uncertain==partial, "partial legacy series is not guessed"); } AlmanacSeason sample() { AlmanacSeason s; s.season = 3, s.start_year = 2029, s.display_start_year = 2026; s.leagues.push_back({0, "comp:bundesliga", "Bundesliga"}); s.referees.push_back({}); const uint16_t home = s.club({"club:sued", "FC Südstadt"}); const uint16_t away = s.club({"club:nord", "SV Nordstadt"}); const uint16_t a = s.player({"player:1", "Anton", "Beispiel", "nation:de"}); const uint16_t b = s.player({"player:gen-7", "", "Größer", "nation:de"}); AlmanacMatch m; m.date = 400, m.type = 2, m.stage = 5, m.round = 2, m.home = home, m.away = away; m.home_manager = s.manager({0, "Testmanager"}); m.home_goals = 1, m.away_goals = 1, m.home_shootout = 5, m.away_shootout = 3, m.decided = 2; m.referee = s.referee("Schiri A"); m.attendance = 75000, m.temperature = -3, m.rain = 6; m.lineup[0] = {a, b}; m.events.push_back({AlmanacEventKind::Goal, 12, 0, 3, a, b}); m.events.push_back({AlmanacEventKind::SecondYellow, 77, 1, 0, b, kAlmanacNone}); m.events.push_back({AlmanacEventKind::Substitution, 80, 0, 0, b, a}); m.events.push_back({AlmanacEventKind::ShootoutKick, 121, 1, 1, a, kAlmanacNone}); s.matches.push_back(m); // the same club again: two players from its previous line-up in a new order and a new one // (version 3 names them by their slot in the previous line-up) const uint16_t c = s.player({"player:3", "Carl", "Neu", "nation:at"}); AlmanacMatch next; next.date = 407, next.type = 0, next.league = 0, next.round = 3, next.home = away, next.away = home; next.lineup[1] = {b, c, a}; s.matches.push_back(next); AlmanacTable t; t.league = 0; t.rows.push_back({home, 1, 34, 25, 5, 4, 80, 30, 77}); t.rows.push_back({away, 2, 34, 20, 6, 8, 70, 40, -2}); s.tables.push_back(t); s.winners.push_back({0, 0, 0xff, 0, 300, home, away}); s.winners.push_back({12, 0xff, 4, 1, 310, away, 0xffff}); return s; } // A season in the row format of version 2 (one row per match), as older saves hold it. std::string encode_version_2(const AlmanacSeason& s) { std::string o = "OBAL"; auto u8 = [&](uint32_t v) { o.push_back(char(v & 0xff)); }; auto u16 = [&](uint32_t v) { u8(v), u8(v >> 8); }; auto u32 = [&](uint32_t v) { u16(v), u16(v >> 16); }; auto str = [&](const std::string& t) { u16(uint32_t(t.size())), o += t; }; u16(2), u16(uint32_t(int16_t(s.season))), u16(uint32_t(s.start_year)), u16(uint32_t(s.display_start_year)); u16(uint32_t(s.leagues.size())); for (const auto& l : s.leagues) u8(uint32_t(l.index)), str(l.id), str(l.name); u16(uint32_t(s.clubs.size())); for (const auto& c : s.clubs) str(c.id), str(c.name); u32(uint32_t(s.players.size())); for (const auto& p : s.players) str(p.id), str(p.first), str(p.last), str(p.nation); u8(uint32_t(s.managers.size())); for (const auto& m : s.managers) u8(uint32_t(uint8_t(int8_t(m.index)))), str(m.name); u16(uint32_t(s.referees.size())); for (const auto& r : s.referees) str(r); u32(uint32_t(s.matches.size())); for (const AlmanacMatch& m : s.matches) { u32(m.date), u8(m.type), u8(m.league), u8(m.stage), u8(m.round), u16(m.home), u16(m.away); u8(uint8_t(m.home_manager)), u8(uint8_t(m.away_manager)); u8(m.home_goals), u8(m.away_goals), u8(m.home_shootout), u8(m.away_shootout), u8(m.decided), u8(m.referee); u32(m.attendance), u8(uint8_t(m.temperature)), u8(m.rain); for (const auto& side : m.lineup) { u8(uint32_t(side.size())); for (uint16_t p : side) u16(p); } u16(uint32_t(m.events.size())); for (const AlmanacEvent& e : m.events) u8(uint32_t(e.kind)), u8(e.minute), u8(e.side), u8(e.detail), u16(e.player), u16(e.other); } u8(uint32_t(s.tables.size())); for (const AlmanacTable& t : s.tables) { u8(t.league), u8(uint32_t(t.rows.size())); for (const AlmanacStanding& r : t.rows) u16(r.club), u8(r.rank), u8(r.played), u8(r.won), u8(r.drawn), u8(r.lost), u8(r.goals_for), u8(r.goals_against), u16(uint32_t(uint16_t(r.points))); } u16(uint32_t(s.winners.size())); for (const AlmanacWinner& x : s.winners) u8(x.type), u8(x.league), u8(x.stage), u8(x.detail), u32(x.date), u16(x.winner), u16(x.runner_up); return o; } } // namespace const cli::Json& field(const cli::Json& j,const char* key) { return j.object()->at(key); } void check_shootout_projection() { auto match=recorded_shootout(true,true); auto season=sample();season.season=0;season.start_year=2026;season.matches={match}; // Valid historical player references let the same read prove that penalty // takers do not acquire normal goals in the statistics projection. for(auto& e:season.matches[0].events)e.player=e.side; auto& legacy=season.matches[0]; legacy.home_goals=5;legacy.away_goals=4;legacy.home_shootout=legacy.away_shootout=0; std::vector duplicate; for(const auto& e:legacy.events)if(e.kind==AlmanacEventKind::ShootoutKick){auto copy=e;copy.kind=e.detail?AlmanacEventKind::Goal:AlmanacEventKind::Miss;copy.detail=0;duplicate.push_back(copy);} legacy.events.insert(legacy.events.begin()+2,duplicate.begin(),duplicate.end()); ModernState g;g.season=0;g.display_start_year=2026;g.almanac.current=season; const auto bytes=encode_almanac_season(season); const auto read=[&]{return query_almanac(g,cli::Json::Object{{"kind","match"},{"id","match:2026-0"}});}; const auto result=read();const auto& scores=field(field(result,"match"),"result"); check(*field(scores,"final").array()->at(0).integer()==1 && *field(scores,"penalties").array()->at(0).integer()==4, "legacy running-season query separates scores"); const auto stats=query_statistics(g,cli::Json::Object{{"kind","player_stats"},{"competition","cup:1"}}); const auto* players=field(stats,"players").array(); check(players&&players->size()==2&&*field(players->at(0),"goals").integer()==1&&*field(players->at(1),"goals").integer()==1, "shoot-out hits are excluded from old-season scorer statistics"); check(encode_almanac_season(g.almanac.current)==bytes,"query normalization leaves running-season bytes unchanged"); g.almanac.current=AlmanacSeason{};g.almanac.finished={{"history/season-2026.bin",bytes}}; const auto finished=read(); check(cli::dump_json(finished)==cli::dump_json(result)&&g.almanac.finished[0].second==bytes, "finished-season query repairs view without rewriting history bytes"); g.almanac.finished.clear();g.almanac.current=season; auto& m=g.almanac.current.matches[0];m=match;m.type=12;m.events[1].minute=30; const auto indoor=read();const auto& ir=field(field(indoor,"match"),"result"); check(!std::get(field(ir,"extra_played").value)&&std::holds_alternative(field(ir,"extra").value)&&std::get(field(ir,"penalties_played").value), "indoor shoot-out does not invent extra time"); m=match;m.events[0].minute=91; const auto ambiguous=read();const auto& ar=field(field(ambiguous,"match"),"result"); check(std::holds_alternative(field(ar,"regulation").value)&&std::holds_alternative(field(ar,"extra").value), "overlapping stoppage/extra-time goal minute has unknown partial score"); } // The club analysis counts what the almanac recorded: records by venue, goals by quarter of // an hour, chances, the first goal and the points course of the league matches. void check_club_analysis() { AlmanacSeason s; s.season = 0; s.start_year = 2026; s.display_start_year = 2026; s.leagues.push_back({0, "league:test", "Testliga"}); const uint16_t own = s.club({"club:own", "Eigene Elf"}), other = s.club({"club:other", "Gegner"}); const uint16_t striker = s.player({"player:striker", "Anna", "Sturm", "nation:de"}); const uint16_t helper = s.player({"player:helper", "Ben", "Pass", "nation:de"}); const auto event = [](AlmanacEventKind kind, int minute, int side, uint16_t player, uint16_t assistant, int detail) { AlmanacEvent e; e.kind = kind; e.minute = uint8_t(minute); e.side = uint8_t(side); e.player = player; e.other = assistant; e.detail = uint8_t(detail); return e; }; AlmanacMatch home; // 2:1 at home: own goals in minutes 10 and 80, the guests score first in minute 5 home.type = 0; home.league = 0; home.round = 1; home.home = own; home.away = other; home.home_goals = 2; home.away_goals = 1; home.attendance = 30000; home.events = {event(AlmanacEventKind::Goal, 5, 1, kAlmanacNone, kAlmanacNone, 0), event(AlmanacEventKind::Goal, 10, 0, striker, helper, 0), event(AlmanacEventKind::Miss, 30, 0, striker, kAlmanacNone, 0), event(AlmanacEventKind::YellowCard, 40, 0, helper, kAlmanacNone, 0), event(AlmanacEventKind::Goal, 80, 0, striker, kAlmanacNone, 3)}; AlmanacMatch away; // 0:0 away away.type = 0; away.league = 0; away.round = 2; away.home = other; away.away = own; away.attendance = 12000; away.events = {event(AlmanacEventKind::Miss, 50, 1, helper, kAlmanacNone, 0)}; s.matches = {home, away}; ModernState g; g.season = 0; g.display_start_year = 2026; g.almanac.current = s; const auto a = club_analysis(g, "club:own"); const auto whole = [&](const cli::Json& j, const char* key) { return int(*field(j, key).integer()); }; check(std::get(field(a, "available").value) && field(a, "matches").array()->size() == 2, "analysis lists both matches"); check(whole(field(a, "home"), "won") == 1 && whole(field(a, "home"), "points") == 3 && whole(field(a, "away"), "drawn") == 1, "analysis keeps the records by venue"); check(whole(field(a, "goals"), "for") == 2 && whole(field(a, "goals"), "against") == 1 && whole(field(a, "chances"), "for") == 4 && whole(field(a, "chances"), "against") == 1, "analysis counts goals and chances of both sides"); const auto& buckets = *field(a, "buckets").array(); check(buckets.size() == 6 && whole(buckets[0], "for") == 1 && whole(buckets[0], "against") == 1 && whole(buckets[5], "for") == 1, "analysis sorts goals into quarters of an hour"); check(whole(field(a, "firstAgainst"), "played") == 1 && whole(field(a, "firstAgainst"), "won") == 1 && whole(field(a, "firstFor"), "played") == 0, "analysis notes who scored first and what came of it"); const auto& points = *field(a, "points").array(); check(points.size() == 2 && *points[0].integer() == 3 && *points[1].integer() == 4, "analysis follows the points course"); const auto& scorers = *field(a, "scorers").array(); check(scorers.size() == 2 && whole(scorers[0], "goals") == 2 && whole(scorers[1], "assists") == 1 && whole(field(a, "cards"), "yellow") == 1, "analysis ranks scorers and counts cards"); check(whole((*field(a, "kinds").array())[3], "for") == 1, "analysis keeps the goal kinds"); check(!std::get(field(club_analysis(g, "club:absent"), "available").value), "a club without a match has no analysis"); } int main() { check_club_analysis(); check_shootout_recording(); check_shootout_projection(); const AlmanacSeason s = sample(); const std::string bytes = encode_almanac_season(s); const AlmanacSeason back = decode_almanac_season(bytes); check(back == s, "season round trip"); check(encode_almanac_season(back) == bytes, "stable encoding"); check(decode_almanac_season(encode_version_2(s)) == s, "version 2 saves still read"); check(bytes.size() > 6 && bytes[4] == 3 && bytes[5] == 0, "written as version 3"); AlmanacSeason grown = back; // the lookups survive decoding: no duplicate entries check(grown.club({"club:sued", "FC Südstadt"}) == 0 && grown.clubs.size() == 2, "club lookup after decode"); check(grown.referee("Schiri A") == 1 && grown.referees.size() == 2, "referee lookup after decode"); bool refused = false; try { decode_almanac_season(bytes.substr(0, bytes.size() - 3)); } catch (const FormatError&) { refused = true; } check(refused, "truncated season refused"); refused = false; try { decode_almanac_season(bytes + "x"); } catch (const FormatError&) { refused = true; } check(refused, "trailing bytes refused"); refused = false; try { decode_almanac_season("OBAL\x09\x00"); } catch (const FormatError&) { refused = true; } check(refused, "unknown version refused"); // Day 0 is 1 July of the display start year; the calendar's first leap year comes after one year. const AlmanacDate d0 = almanac_date(0, 2026), d1 = almanac_date(183, 2026), d2 = almanac_date(365, 2026); check(d0.year == 2026 && d0.month == 7 && d0.day == 1, "date of day 0"); check(d1.year == 2026 && d1.month == 12 && d1.day == 31, "date of day 183"); check(d2.year == 2027 && d2.month == 7 && d2.day == 1, "date of day 365"); ModernState g; g.players.resize(5); new_player_identity(g, 3); new_player_identity(g, 3); check(g.world_player_id.size() == 5 && g.world_player_id[3] == "player:gen-2" && g.almanac.generated_players == 2, "new player identities"); if (failures == 0) std::printf("modern almanac tests passed\n"); return failures == 0 ? 0 : 1; }