Files
Dreierpack-Manager/src/modern/content/world_save.cpp
T

302 lines
18 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
#include "modern/content/world_save.hpp"
#include <algorithm>
#include <bit>
#include <cstdio>
#include <utility>
#include <variant>
#include <set>
#include "content/digest.hpp"
#include "content/package.hpp"
#include "content/save.hpp"
#include "formats/native_state.hpp"
#include "import/detail.hpp"
#include "modern/game/save.hpp"
#include "formats/executable_layout.hpp"
namespace bmh::modern {
namespace {
using namespace obw::detail;
J generator(uint32_t seed, uint64_t calls) {
return O{{"seed", int64_t(seed)}, {"calls", std::to_string(calls)}};
}
uint64_t draw_count(const J& value) {
const auto s = str(get(value, "calls"));
if (s.empty() || s.size() > 20 || !std::all_of(s.begin(), s.end(), [](unsigned char c) { return c >= '0' && c <= '9'; }))
fail("invalid random draw counter");
return std::stoull(s);
}
uint32_t seed_of(const J& value) {
const auto n = num(get(value, "seed"));
if (n < 0 || n > int64_t(UINT32_MAX)) fail("invalid random seed");
return uint32_t(n);
}
J strings(const std::vector<std::string>& values) {
A out;
for (const auto& v : values) out.push_back(v);
return out;
}
std::vector<std::string> strings(const J& value) {
std::vector<std::string> out;
for (const J& v : arr(value)) out.push_back(str(v));
return out;
}
J manager_presentations_json(const std::vector<ModernState::ManagerPresentation>& values) {
A out;
for (const auto& p : values) out.push_back(O{{"id", p.id}, {"name", p.name}, {"portrait_style", p.portrait_style}});
return out;
}
std::vector<ModernState::ManagerPresentation> manager_presentations_json(const J& value) {
std::vector<ModernState::ManagerPresentation> out; std::set<std::string> ids;
for (const auto& row : arr(value)) {
ModernState::ManagerPresentation p{str(get(row, "id")), str(get(row, "name")), str(get(row, "portrait_style"))};
if (!p.id.starts_with("manager:") || p.id.size() > 64 || !ids.insert(p.id).second || p.name.empty() || p.name.size() > 96 || p.name.find('\0') != std::string::npos || (p.portrait_style != "photo" && p.portrait_style != "painted")) fail("invalid manager presentation");
out.push_back(std::move(p));
}
return out;
}
std::string world_identity(const World& world) { return world.id + "@" + world.data_revision; }
// Exclusive sponsor offers and queued contracts per manager (docs/new_engine/trainingslager.md).
J sponsors_json(const std::vector<ModernState::ExclusiveSponsor>& sponsors) {
A out;
for (const auto& s : sponsors)
out.push_back(O{{"offered", s.offered}, {"queued", s.queued}, {"kind", int(s.kind)}, {"units", int(s.units)},
{"months", int(s.months)}, {"sponsor", int(s.sponsor)}, {"monthly", int64_t(s.monthly)}, {"score", int(s.score)}, {"camp", s.camp}});
return out;
}
std::vector<ModernState::ExclusiveSponsor> sponsors_json(const J& value) {
std::vector<ModernState::ExclusiveSponsor> out;
for (const J& row : arr(value)) {
ModernState::ExclusiveSponsor s;
const J& offered = get(row, "offered");
const J& queued = get(row, "queued");
if (!std::holds_alternative<bool>(offered.value) || !std::holds_alternative<bool>(queued.value)) fail("invalid sponsor flags");
s.offered = std::get<bool>(offered.value), s.queued = std::get<bool>(queued.value);
s.kind = uint8_t(num(get(row, "kind"))), s.units = uint8_t(num(get(row, "units")));
s.months = uint8_t(num(get(row, "months"))), s.sponsor = uint8_t(num(get(row, "sponsor")));
s.monthly = uint32_t(num(get(row, "monthly"))), s.camp = str(get(row, "camp"));
s.score = uint16_t(num(get(row, "score")));
if (s.kind > 1 || s.units > 14 || s.sponsor > 9) fail("invalid exclusive sponsor");
out.push_back(std::move(s));
}
return out;
}
// The press journal (content/press_journal.hpp): the entries with their facts as JSON text.
J press_json(const std::vector<ModernState::PressEntry>& press) {
A out;
for (const auto& e : press)
out.push_back(O{{"id", e.id}, {"type", e.type}, {"team", e.team}, {"date", int64_t(e.date)}, {"data", e.data}});
return out;
}
std::vector<ModernState::PressEntry> press_json(const J& value) {
std::vector<ModernState::PressEntry> out;
for (const J& row : arr(value))
out.push_back({str(get(row, "id")), str(get(row, "type")), str(get(row, "team")), uint32_t(num(get(row, "date"))), str(get(row, "data"))});
return out;
}
// The Toto columns 2-6 and the last settlement per manager (docs/new_engine/toto.md).
J pools_json(const std::vector<ModernState::PoolsColumns>& pools) {
A out;
for (const auto& p : pools) {
A extra, hits;
for (const auto& column : p.extra) {
A tips;
for (uint8_t t : column) tips.push_back(int(t));
extra.push_back(std::move(tips));
}
for (uint8_t h : p.hits) hits.push_back(int(h));
out.push_back(O{{"extra", std::move(extra)}, {"hits", std::move(hits)}, {"paid", int64_t(p.paid)}, {"won", int64_t(p.won)}});
}
return out;
}
std::vector<ModernState::PoolsColumns> pools_json(const J& value) {
std::vector<ModernState::PoolsColumns> out;
for (const J& row : arr(value)) {
ModernState::PoolsColumns p;
for (const J& column : arr(get(row, "extra"))) {
const A& tips = arr(column);
if (tips.size() != 11) fail("invalid Toto column");
std::array<uint8_t, 11> c{};
for (size_t i = 0; i < 11; ++i) {
const int64_t t = num(tips[i]);
if (t < 0 || t > 2) fail("invalid Toto tip");
c[i] = uint8_t(t);
}
p.extra.push_back(c);
}
for (const J& h : arr(get(row, "hits"))) p.hits.push_back(uint8_t(num(h)));
p.paid = uint32_t(num(get(row, "paid"))), p.won = uint32_t(num(get(row, "won")));
out.push_back(std::move(p));
}
return out;
}
} // namespace
void save_world_career(const std::filesystem::path& path, const World& world, const ModernState& state,
const WatcomRandom& random, const GameRandom& game, const TurnDriver& driver, bool overwrite,
const cli::Json& session) {
if (driver.stage != TurnDriver::Stage::Empty && driver.stage != TurnDriver::Stage::MatchdayDesks &&
driver.stage != TurnDriver::Stage::SeasonEndDesk)
fail("save unavailable outside a manager desk");
obw::Documents docs;
put(docs, "manifest.json",
O{{"format", "openbmh-world"}, {"format_version", "1.1"}, {"kind", "save"},
{"save_profile", "modern-career-v1"}, {"requires", A{J("runtime:modern-v1")}},
{"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", state.manager_presentations.empty() ? "modern-state@1.1" : "modern-state@1.2"},
{"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)},
{"league_ids", strings(state.world_league_id)},
{"league_names", strings(state.world_league_name)},
{"generated_players", int64_t(state.almanac.generated_players)},
{"pools", pools_json(state.pools)},
{"exclusive_sponsors", sponsors_json(state.exclusive_sponsors)},
{"career_id", state.career_id},
{"manager_ids", strings(state.manager_ids)},
{"manager_serial", int64_t(state.manager_serial)},
{"manager_presentations", manager_presentations_json(state.manager_presentations)},
{"traffic_scale", int64_t(state.traffic_scale)},
{"press", press_json(state.press)},
{"press_serial", int64_t(state.press_serial)},
{"press_month", int64_t(state.press_month)},
{"press_month_cash", [&] { A a; for (int64_t v : state.press_month_cash) a.push_back(v); return J(std::move(a)); }()},
{"career_end_reason", state.career_end_reason},
{"career_end_date", int64_t(state.career_end_date)}});
// 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())},
{"game", generator(uint32_t(game.seed()), game.calls())}});
put(docs, "state/session.json", session);
put(docs, "state/driver.json", content::driver_checkpoint(driver));
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/") || 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);
}
SavedWorldCareer load_world_career(const std::filesystem::path& path, const World& world) {
const auto docs = content::read_archive(path);
const auto manifest = parse(docs, "manifest.json");
if (str(get(manifest, "kind")) != "save" || str(get(manifest, "save_profile")) != "modern-career-v1")
fail("not a Modern career save");
const auto& saved_world = get(manifest, "world");
if (str(get(saved_world, "id")) != world.id || str(get(saved_world, "data_revision")) != world.data_revision)
fail("the save belongs to another world: " + str(get(saved_world, "id")) + "@" +
str(get(saved_world, "data_revision")) + ", loaded " + world_identity(world));
const auto integrity = parse(docs, "state/integrity.json");
if (str(get(integrity, "schema")) != "save-integrity@1.0") fail("unsupported save integrity");
O checks;
for (const auto& [name, value] : docs)
if ((name.starts_with("state/") || name.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");
const auto modern_schema = str(get(modern, "schema"));
if (modern_schema != "modern-state@1.1" && modern_schema != "modern-state@1.2") 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"));
out.state.world_player_id = strings(get(modern, "player_ids"));
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")));
out.state.pools = pools_json(get(modern, "pools"));
out.state.exclusive_sponsors = sponsors_json(get(modern, "exclusive_sponsors"));
// interface identities (since 27 October 2026); older saves get them on load (ensure_ui_identities)
if (const auto* o = modern.object(); o && o->count("career_id")) {
out.state.career_id = str(get(modern, "career_id"));
out.state.manager_ids = strings(get(modern, "manager_ids"));
out.state.manager_serial = uint32_t(num(get(modern, "manager_serial")));
if (o->count("manager_presentations")) out.state.manager_presentations = manager_presentations_json(get(modern, "manager_presentations"));
if (o->count("traffic_scale")) out.state.traffic_scale = uint8_t(num(get(modern, "traffic_scale")));
if (o->count("press")) {
out.state.press = press_json(get(modern, "press"));
out.state.press_serial = uint32_t(num(get(modern, "press_serial")));
}
if (o->count("press_month")) {
out.state.press_month = uint32_t(num(get(modern, "press_month")));
for (const J& v : arr(get(modern, "press_month_cash"))) out.state.press_month_cash.push_back(int64_t(num(v)));
}
if (o->count("career_end_reason")) {
out.state.career_end_reason = str(get(modern, "career_end_reason"));
out.state.career_end_date = uint32_t(num(get(modern, "career_end_date")));
}
}
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");
const auto generators = parse(docs, "state/rng.json");
if (str(get(generators, "schema")) != "classic-rng@1.0") fail("unsupported RNG checkpoint");
out.random.restore(seed_of(get(generators, "watcom")), draw_count(get(generators, "watcom")));
out.game.restore(std::bit_cast<int32_t>(seed_of(get(generators, "game"))), draw_count(get(generators, "game")));
out.session = parse(docs, "state/session.json");
out.driver = parse(docs, "state/driver.json");
out.header = decode_native_bytes(parse(docs, "state/information.json"), 172);
return out;
}
cli::Json world_career_metadata(const World& world,const ModernState& state) {
const bool coach=state.memory.has(::bmh::layout::CoachActive)&&state.memory.u8(::bmh::layout::CoachActive)!=0;
const int count=coach?state.memory.u8(::bmh::layout::OriginalManagerCount):int(state.manager_teams.size());
if(count<1||count>4)fail("unsupported saved manager count");
const int runtime=coach?0:state.memory.has(::bmh::layout::ActiveManager)?state.memory.u8(::bmh::layout::ActiveManager):0;
const int active=state.human_manager_slot(runtime);if(active<0||active>=count)fail("invalid saved active manager");
A managers;int active_team=-1;
for(int human=0;human<count;++human) {
const int record=state.manager_record_slot(human);const size_t at=size_t(record)*0xb0c;
if(at+0x292>state.manager_records.size())fail("saved manager record missing");
const int team=record>=0&&size_t(record)<state.manager_teams.size()?state.manager_teams[size_t(record)]:int(uint16_t(state.manager_records[at+0x290])|uint16_t(state.manager_records[at+0x291])<<8);
if(team<0||size_t(team)>=state.world_club_id.size())fail("saved manager team missing");
const auto* presentation=state.manager_presentation_for_human(human);std::string name;
if(presentation)name=presentation->name;else {for(size_t n=0;n<25&&state.manager_records[at+0xa8+n];++n)name.push_back(char(state.manager_records[at+0xa8+n]));name=almanac_utf8(name);}
const auto id=size_t(human)<state.manager_ids.size()&&!state.manager_ids[size_t(human)].empty()?state.manager_ids[size_t(human)]:"manager:slot-"+std::to_string(human);
managers.push_back(O{{"id",id},{"name",name},{"club",state.world_club_id[size_t(team)]},{"team_name",coach&&record==0?std::string("Deutschland"):size_t(team)<state.world_club_name.size()?state.world_club_name[size_t(team)]:std::string()},{"portrait",int(state.manager_records[at+0x221])},{"portrait_style",presentation?presentation->portrait_style:"photo"},{"national",coach&&record==0}});
if(human==active)active_team=team;
}
const auto date=almanac_date(state.date,state.display_start_year);char iso[16];std::snprintf(iso,sizeof iso,"%04d-%02d-%02d",date.year,date.month,date.day);
const int year=state.display_start_year+state.season,next=(year+1)%100;const auto season=std::to_string(year)+"/"+(next<10?"0":"")+std::to_string(next);std::string round="—";
if(!coach) {
std::vector<const WorldLeague*> leagues;for(const auto& l:world.leagues)if(l.index>=0)leagues.push_back(&l);std::sort(leagues.begin(),leagues.end(),[](auto* a,auto* b){return a->index<b->index;});
int first=0;for(const auto* l:leagues){const int size=int(l->members.size());if(active_team>=first&&active_team<first+size&&size>1&&size_t(l->index)<state.league_rounds.size())round=std::to_string(std::min(int(state.league_rounds[size_t(l->index)])+1,(size-1)*2))+". Spieltag";first+=size;}
}
return O{{"schema","modern-career-metadata@1"},{"career_id",state.career_id},{"world_id",world.id},{"world_revision",world.data_revision},{"date",iso},{"season",season},{"matchday",round},{"role",coach?"national":"club"},{"human_count",count},{"current_manager",managers.at(size_t(active))},{"managers",std::move(managers)}};
}
cli::Json read_world_career_metadata(const std::filesystem::path& path,const World& world) {
const auto saved=load_world_career(path,world);return world_career_metadata(world,saved.state);
}
} // namespace bmh::modern